xref: /qemu/hw/ide/atapi.c (revision d072cdf3)
1 /*
2  * QEMU ATAPI Emulation
3  *
4  * Copyright (c) 2003 Fabrice Bellard
5  * Copyright (c) 2006 Openedhand Ltd.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25 
26 #include "hw/ide/internal.h"
27 #include "hw/scsi/scsi.h"
28 
29 static void ide_atapi_cmd_read_dma_cb(void *opaque, int ret);
30 
31 static void padstr8(uint8_t *buf, int buf_size, const char *src)
32 {
33     int i;
34     for(i = 0; i < buf_size; i++) {
35         if (*src)
36             buf[i] = *src++;
37         else
38             buf[i] = ' ';
39     }
40 }
41 
42 static inline void cpu_to_ube16(uint8_t *buf, int val)
43 {
44     buf[0] = val >> 8;
45     buf[1] = val & 0xff;
46 }
47 
48 static inline void cpu_to_ube32(uint8_t *buf, unsigned int val)
49 {
50     buf[0] = val >> 24;
51     buf[1] = val >> 16;
52     buf[2] = val >> 8;
53     buf[3] = val & 0xff;
54 }
55 
56 static inline int ube16_to_cpu(const uint8_t *buf)
57 {
58     return (buf[0] << 8) | buf[1];
59 }
60 
61 static inline int ube32_to_cpu(const uint8_t *buf)
62 {
63     return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
64 }
65 
66 static void lba_to_msf(uint8_t *buf, int lba)
67 {
68     lba += 150;
69     buf[0] = (lba / 75) / 60;
70     buf[1] = (lba / 75) % 60;
71     buf[2] = lba % 75;
72 }
73 
74 static inline int media_present(IDEState *s)
75 {
76     return !s->tray_open && s->nb_sectors > 0;
77 }
78 
79 /* XXX: DVDs that could fit on a CD will be reported as a CD */
80 static inline int media_is_dvd(IDEState *s)
81 {
82     return (media_present(s) && s->nb_sectors > CD_MAX_SECTORS);
83 }
84 
85 static inline int media_is_cd(IDEState *s)
86 {
87     return (media_present(s) && s->nb_sectors <= CD_MAX_SECTORS);
88 }
89 
90 static void cd_data_to_raw(uint8_t *buf, int lba)
91 {
92     /* sync bytes */
93     buf[0] = 0x00;
94     memset(buf + 1, 0xff, 10);
95     buf[11] = 0x00;
96     buf += 12;
97     /* MSF */
98     lba_to_msf(buf, lba);
99     buf[3] = 0x01; /* mode 1 data */
100     buf += 4;
101     /* data */
102     buf += 2048;
103     /* XXX: ECC not computed */
104     memset(buf, 0, 288);
105 }
106 
107 static int cd_read_sector(IDEState *s, int lba, uint8_t *buf, int sector_size)
108 {
109     int ret;
110 
111     switch(sector_size) {
112     case 2048:
113         bdrv_acct_start(s->bs, &s->acct, 4 * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
114         ret = bdrv_read(s->bs, (int64_t)lba << 2, buf, 4);
115         bdrv_acct_done(s->bs, &s->acct);
116         break;
117     case 2352:
118         bdrv_acct_start(s->bs, &s->acct, 4 * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
119         ret = bdrv_read(s->bs, (int64_t)lba << 2, buf + 16, 4);
120         bdrv_acct_done(s->bs, &s->acct);
121         if (ret < 0)
122             return ret;
123         cd_data_to_raw(buf, lba);
124         break;
125     default:
126         ret = -EIO;
127         break;
128     }
129     return ret;
130 }
131 
132 void ide_atapi_cmd_ok(IDEState *s)
133 {
134     s->error = 0;
135     s->status = READY_STAT | SEEK_STAT;
136     s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
137     ide_set_irq(s->bus);
138 }
139 
140 void ide_atapi_cmd_error(IDEState *s, int sense_key, int asc)
141 {
142 #ifdef DEBUG_IDE_ATAPI
143     printf("atapi_cmd_error: sense=0x%x asc=0x%x\n", sense_key, asc);
144 #endif
145     s->error = sense_key << 4;
146     s->status = READY_STAT | ERR_STAT;
147     s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
148     s->sense_key = sense_key;
149     s->asc = asc;
150     ide_set_irq(s->bus);
151 }
152 
153 void ide_atapi_io_error(IDEState *s, int ret)
154 {
155     /* XXX: handle more errors */
156     if (ret == -ENOMEDIUM) {
157         ide_atapi_cmd_error(s, NOT_READY,
158                             ASC_MEDIUM_NOT_PRESENT);
159     } else {
160         ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
161                             ASC_LOGICAL_BLOCK_OOR);
162     }
163 }
164 
165 /* The whole ATAPI transfer logic is handled in this function */
166 void ide_atapi_cmd_reply_end(IDEState *s)
167 {
168     int byte_count_limit, size, ret;
169 #ifdef DEBUG_IDE_ATAPI
170     printf("reply: tx_size=%d elem_tx_size=%d index=%d\n",
171            s->packet_transfer_size,
172            s->elementary_transfer_size,
173            s->io_buffer_index);
174 #endif
175     if (s->packet_transfer_size <= 0) {
176         /* end of transfer */
177         s->status = READY_STAT | SEEK_STAT;
178         s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
179         ide_transfer_stop(s);
180         ide_set_irq(s->bus);
181 #ifdef DEBUG_IDE_ATAPI
182         printf("status=0x%x\n", s->status);
183 #endif
184     } else {
185         /* see if a new sector must be read */
186         if (s->lba != -1 && s->io_buffer_index >= s->cd_sector_size) {
187             ret = cd_read_sector(s, s->lba, s->io_buffer, s->cd_sector_size);
188             if (ret < 0) {
189                 ide_transfer_stop(s);
190                 ide_atapi_io_error(s, ret);
191                 return;
192             }
193             s->lba++;
194             s->io_buffer_index = 0;
195         }
196         if (s->elementary_transfer_size > 0) {
197             /* there are some data left to transmit in this elementary
198                transfer */
199             size = s->cd_sector_size - s->io_buffer_index;
200             if (size > s->elementary_transfer_size)
201                 size = s->elementary_transfer_size;
202             s->packet_transfer_size -= size;
203             s->elementary_transfer_size -= size;
204             s->io_buffer_index += size;
205             ide_transfer_start(s, s->io_buffer + s->io_buffer_index - size,
206                                size, ide_atapi_cmd_reply_end);
207         } else {
208             /* a new transfer is needed */
209             s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO;
210             byte_count_limit = s->lcyl | (s->hcyl << 8);
211 #ifdef DEBUG_IDE_ATAPI
212             printf("byte_count_limit=%d\n", byte_count_limit);
213 #endif
214             if (byte_count_limit == 0xffff)
215                 byte_count_limit--;
216             size = s->packet_transfer_size;
217             if (size > byte_count_limit) {
218                 /* byte count limit must be even if this case */
219                 if (byte_count_limit & 1)
220                     byte_count_limit--;
221                 size = byte_count_limit;
222             }
223             s->lcyl = size;
224             s->hcyl = size >> 8;
225             s->elementary_transfer_size = size;
226             /* we cannot transmit more than one sector at a time */
227             if (s->lba != -1) {
228                 if (size > (s->cd_sector_size - s->io_buffer_index))
229                     size = (s->cd_sector_size - s->io_buffer_index);
230             }
231             s->packet_transfer_size -= size;
232             s->elementary_transfer_size -= size;
233             s->io_buffer_index += size;
234             ide_transfer_start(s, s->io_buffer + s->io_buffer_index - size,
235                                size, ide_atapi_cmd_reply_end);
236             ide_set_irq(s->bus);
237 #ifdef DEBUG_IDE_ATAPI
238             printf("status=0x%x\n", s->status);
239 #endif
240         }
241     }
242 }
243 
244 /* send a reply of 'size' bytes in s->io_buffer to an ATAPI command */
245 static void ide_atapi_cmd_reply(IDEState *s, int size, int max_size)
246 {
247     if (size > max_size)
248         size = max_size;
249     s->lba = -1; /* no sector read */
250     s->packet_transfer_size = size;
251     s->io_buffer_size = size;    /* dma: send the reply data as one chunk */
252     s->elementary_transfer_size = 0;
253     s->io_buffer_index = 0;
254 
255     if (s->atapi_dma) {
256         bdrv_acct_start(s->bs, &s->acct, size, BDRV_ACCT_READ);
257         s->status = READY_STAT | SEEK_STAT | DRQ_STAT;
258         ide_start_dma(s, ide_atapi_cmd_read_dma_cb);
259     } else {
260         s->status = READY_STAT | SEEK_STAT;
261         ide_atapi_cmd_reply_end(s);
262     }
263 }
264 
265 /* start a CD-CDROM read command */
266 static void ide_atapi_cmd_read_pio(IDEState *s, int lba, int nb_sectors,
267                                    int sector_size)
268 {
269     s->lba = lba;
270     s->packet_transfer_size = nb_sectors * sector_size;
271     s->elementary_transfer_size = 0;
272     s->io_buffer_index = sector_size;
273     s->cd_sector_size = sector_size;
274 
275     s->status = READY_STAT | SEEK_STAT;
276     ide_atapi_cmd_reply_end(s);
277 }
278 
279 static void ide_atapi_cmd_check_status(IDEState *s)
280 {
281 #ifdef DEBUG_IDE_ATAPI
282     printf("atapi_cmd_check_status\n");
283 #endif
284     s->error = MC_ERR | (UNIT_ATTENTION << 4);
285     s->status = ERR_STAT;
286     s->nsector = 0;
287     ide_set_irq(s->bus);
288 }
289 /* ATAPI DMA support */
290 
291 /* XXX: handle read errors */
292 static void ide_atapi_cmd_read_dma_cb(void *opaque, int ret)
293 {
294     IDEState *s = opaque;
295     int data_offset, n;
296 
297     if (ret < 0) {
298         ide_atapi_io_error(s, ret);
299         goto eot;
300     }
301 
302     if (s->io_buffer_size > 0) {
303         /*
304          * For a cdrom read sector command (s->lba != -1),
305          * adjust the lba for the next s->io_buffer_size chunk
306          * and dma the current chunk.
307          * For a command != read (s->lba == -1), just transfer
308          * the reply data.
309          */
310         if (s->lba != -1) {
311             if (s->cd_sector_size == 2352) {
312                 n = 1;
313                 cd_data_to_raw(s->io_buffer, s->lba);
314             } else {
315                 n = s->io_buffer_size >> 11;
316             }
317             s->lba += n;
318         }
319         s->packet_transfer_size -= s->io_buffer_size;
320         if (s->bus->dma->ops->rw_buf(s->bus->dma, 1) == 0)
321             goto eot;
322     }
323 
324     if (s->packet_transfer_size <= 0) {
325         s->status = READY_STAT | SEEK_STAT;
326         s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
327         ide_set_irq(s->bus);
328         goto eot;
329     }
330 
331     s->io_buffer_index = 0;
332     if (s->cd_sector_size == 2352) {
333         n = 1;
334         s->io_buffer_size = s->cd_sector_size;
335         data_offset = 16;
336     } else {
337         n = s->packet_transfer_size >> 11;
338         if (n > (IDE_DMA_BUF_SECTORS / 4))
339             n = (IDE_DMA_BUF_SECTORS / 4);
340         s->io_buffer_size = n * 2048;
341         data_offset = 0;
342     }
343 #ifdef DEBUG_AIO
344     printf("aio_read_cd: lba=%u n=%d\n", s->lba, n);
345 #endif
346 
347     s->bus->dma->iov.iov_base = (void *)(s->io_buffer + data_offset);
348     s->bus->dma->iov.iov_len = n * 4 * 512;
349     qemu_iovec_init_external(&s->bus->dma->qiov, &s->bus->dma->iov, 1);
350 
351     s->bus->dma->aiocb = bdrv_aio_readv(s->bs, (int64_t)s->lba << 2,
352                                        &s->bus->dma->qiov, n * 4,
353                                        ide_atapi_cmd_read_dma_cb, s);
354     return;
355 
356 eot:
357     bdrv_acct_done(s->bs, &s->acct);
358     ide_set_inactive(s, false);
359 }
360 
361 /* start a CD-CDROM read command with DMA */
362 /* XXX: test if DMA is available */
363 static void ide_atapi_cmd_read_dma(IDEState *s, int lba, int nb_sectors,
364                                    int sector_size)
365 {
366     s->lba = lba;
367     s->packet_transfer_size = nb_sectors * sector_size;
368     s->io_buffer_index = 0;
369     s->io_buffer_size = 0;
370     s->cd_sector_size = sector_size;
371 
372     bdrv_acct_start(s->bs, &s->acct, s->packet_transfer_size, BDRV_ACCT_READ);
373 
374     /* XXX: check if BUSY_STAT should be set */
375     s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT;
376     ide_start_dma(s, ide_atapi_cmd_read_dma_cb);
377 }
378 
379 static void ide_atapi_cmd_read(IDEState *s, int lba, int nb_sectors,
380                                int sector_size)
381 {
382 #ifdef DEBUG_IDE_ATAPI
383     printf("read %s: LBA=%d nb_sectors=%d\n", s->atapi_dma ? "dma" : "pio",
384         lba, nb_sectors);
385 #endif
386     if (s->atapi_dma) {
387         ide_atapi_cmd_read_dma(s, lba, nb_sectors, sector_size);
388     } else {
389         ide_atapi_cmd_read_pio(s, lba, nb_sectors, sector_size);
390     }
391 }
392 
393 static inline uint8_t ide_atapi_set_profile(uint8_t *buf, uint8_t *index,
394                                             uint16_t profile)
395 {
396     uint8_t *buf_profile = buf + 12; /* start of profiles */
397 
398     buf_profile += ((*index) * 4); /* start of indexed profile */
399     cpu_to_ube16 (buf_profile, profile);
400     buf_profile[2] = ((buf_profile[0] == buf[6]) && (buf_profile[1] == buf[7]));
401 
402     /* each profile adds 4 bytes to the response */
403     (*index)++;
404     buf[11] += 4; /* Additional Length */
405 
406     return 4;
407 }
408 
409 static int ide_dvd_read_structure(IDEState *s, int format,
410                                   const uint8_t *packet, uint8_t *buf)
411 {
412     switch (format) {
413         case 0x0: /* Physical format information */
414             {
415                 int layer = packet[6];
416                 uint64_t total_sectors;
417 
418                 if (layer != 0)
419                     return -ASC_INV_FIELD_IN_CMD_PACKET;
420 
421                 total_sectors = s->nb_sectors >> 2;
422                 if (total_sectors == 0) {
423                     return -ASC_MEDIUM_NOT_PRESENT;
424                 }
425 
426                 buf[4] = 1;   /* DVD-ROM, part version 1 */
427                 buf[5] = 0xf; /* 120mm disc, minimum rate unspecified */
428                 buf[6] = 1;   /* one layer, read-only (per MMC-2 spec) */
429                 buf[7] = 0;   /* default densities */
430 
431                 /* FIXME: 0x30000 per spec? */
432                 cpu_to_ube32(buf + 8, 0); /* start sector */
433                 cpu_to_ube32(buf + 12, total_sectors - 1); /* end sector */
434                 cpu_to_ube32(buf + 16, total_sectors - 1); /* l0 end sector */
435 
436                 /* Size of buffer, not including 2 byte size field */
437                 stw_be_p(buf, 2048 + 2);
438 
439                 /* 2k data + 4 byte header */
440                 return (2048 + 4);
441             }
442 
443         case 0x01: /* DVD copyright information */
444             buf[4] = 0; /* no copyright data */
445             buf[5] = 0; /* no region restrictions */
446 
447             /* Size of buffer, not including 2 byte size field */
448             stw_be_p(buf, 4 + 2);
449 
450             /* 4 byte header + 4 byte data */
451             return (4 + 4);
452 
453         case 0x03: /* BCA information - invalid field for no BCA info */
454             return -ASC_INV_FIELD_IN_CMD_PACKET;
455 
456         case 0x04: /* DVD disc manufacturing information */
457             /* Size of buffer, not including 2 byte size field */
458             stw_be_p(buf, 2048 + 2);
459 
460             /* 2k data + 4 byte header */
461             return (2048 + 4);
462 
463         case 0xff:
464             /*
465              * This lists all the command capabilities above.  Add new ones
466              * in order and update the length and buffer return values.
467              */
468 
469             buf[4] = 0x00; /* Physical format */
470             buf[5] = 0x40; /* Not writable, is readable */
471             stw_be_p(buf + 6, 2048 + 4);
472 
473             buf[8] = 0x01; /* Copyright info */
474             buf[9] = 0x40; /* Not writable, is readable */
475             stw_be_p(buf + 10, 4 + 4);
476 
477             buf[12] = 0x03; /* BCA info */
478             buf[13] = 0x40; /* Not writable, is readable */
479             stw_be_p(buf + 14, 188 + 4);
480 
481             buf[16] = 0x04; /* Manufacturing info */
482             buf[17] = 0x40; /* Not writable, is readable */
483             stw_be_p(buf + 18, 2048 + 4);
484 
485             /* Size of buffer, not including 2 byte size field */
486             stw_be_p(buf, 16 + 2);
487 
488             /* data written + 4 byte header */
489             return (16 + 4);
490 
491         default: /* TODO: formats beyond DVD-ROM requires */
492             return -ASC_INV_FIELD_IN_CMD_PACKET;
493     }
494 }
495 
496 static unsigned int event_status_media(IDEState *s,
497                                        uint8_t *buf)
498 {
499     uint8_t event_code, media_status;
500 
501     media_status = 0;
502     if (s->tray_open) {
503         media_status = MS_TRAY_OPEN;
504     } else if (bdrv_is_inserted(s->bs)) {
505         media_status = MS_MEDIA_PRESENT;
506     }
507 
508     /* Event notification descriptor */
509     event_code = MEC_NO_CHANGE;
510     if (media_status != MS_TRAY_OPEN) {
511         if (s->events.new_media) {
512             event_code = MEC_NEW_MEDIA;
513             s->events.new_media = false;
514         } else if (s->events.eject_request) {
515             event_code = MEC_EJECT_REQUESTED;
516             s->events.eject_request = false;
517         }
518     }
519 
520     buf[4] = event_code;
521     buf[5] = media_status;
522 
523     /* These fields are reserved, just clear them. */
524     buf[6] = 0;
525     buf[7] = 0;
526 
527     return 8; /* We wrote to 4 extra bytes from the header */
528 }
529 
530 static void cmd_get_event_status_notification(IDEState *s,
531                                               uint8_t *buf)
532 {
533     const uint8_t *packet = buf;
534 
535     struct {
536         uint8_t opcode;
537         uint8_t polled;        /* lsb bit is polled; others are reserved */
538         uint8_t reserved2[2];
539         uint8_t class;
540         uint8_t reserved3[2];
541         uint16_t len;
542         uint8_t control;
543     } QEMU_PACKED *gesn_cdb;
544 
545     struct {
546         uint16_t len;
547         uint8_t notification_class;
548         uint8_t supported_events;
549     } QEMU_PACKED *gesn_event_header;
550     unsigned int max_len, used_len;
551 
552     gesn_cdb = (void *)packet;
553     gesn_event_header = (void *)buf;
554 
555     max_len = be16_to_cpu(gesn_cdb->len);
556 
557     /* It is fine by the MMC spec to not support async mode operations */
558     if (!(gesn_cdb->polled & 0x01)) { /* asynchronous mode */
559         /* Only polling is supported, asynchronous mode is not. */
560         ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
561                             ASC_INV_FIELD_IN_CMD_PACKET);
562         return;
563     }
564 
565     /* polling mode operation */
566 
567     /*
568      * These are the supported events.
569      *
570      * We currently only support requests of the 'media' type.
571      * Notification class requests and supported event classes are bitmasks,
572      * but they are build from the same values as the "notification class"
573      * field.
574      */
575     gesn_event_header->supported_events = 1 << GESN_MEDIA;
576 
577     /*
578      * We use |= below to set the class field; other bits in this byte
579      * are reserved now but this is useful to do if we have to use the
580      * reserved fields later.
581      */
582     gesn_event_header->notification_class = 0;
583 
584     /*
585      * Responses to requests are to be based on request priority.  The
586      * notification_class_request_type enum above specifies the
587      * priority: upper elements are higher prio than lower ones.
588      */
589     if (gesn_cdb->class & (1 << GESN_MEDIA)) {
590         gesn_event_header->notification_class |= GESN_MEDIA;
591         used_len = event_status_media(s, buf);
592     } else {
593         gesn_event_header->notification_class = 0x80; /* No event available */
594         used_len = sizeof(*gesn_event_header);
595     }
596     gesn_event_header->len = cpu_to_be16(used_len
597                                          - sizeof(*gesn_event_header));
598     ide_atapi_cmd_reply(s, used_len, max_len);
599 }
600 
601 static void cmd_request_sense(IDEState *s, uint8_t *buf)
602 {
603     int max_len = buf[4];
604 
605     memset(buf, 0, 18);
606     buf[0] = 0x70 | (1 << 7);
607     buf[2] = s->sense_key;
608     buf[7] = 10;
609     buf[12] = s->asc;
610 
611     if (s->sense_key == UNIT_ATTENTION) {
612         s->sense_key = NO_SENSE;
613     }
614 
615     ide_atapi_cmd_reply(s, 18, max_len);
616 }
617 
618 static void cmd_inquiry(IDEState *s, uint8_t *buf)
619 {
620     int max_len = buf[4];
621 
622     buf[0] = 0x05; /* CD-ROM */
623     buf[1] = 0x80; /* removable */
624     buf[2] = 0x00; /* ISO */
625     buf[3] = 0x21; /* ATAPI-2 (XXX: put ATAPI-4 ?) */
626     buf[4] = 31; /* additional length */
627     buf[5] = 0; /* reserved */
628     buf[6] = 0; /* reserved */
629     buf[7] = 0; /* reserved */
630     padstr8(buf + 8, 8, "QEMU");
631     padstr8(buf + 16, 16, "QEMU DVD-ROM");
632     padstr8(buf + 32, 4, s->version);
633     ide_atapi_cmd_reply(s, 36, max_len);
634 }
635 
636 static void cmd_get_configuration(IDEState *s, uint8_t *buf)
637 {
638     uint32_t len;
639     uint8_t index = 0;
640     int max_len;
641 
642     /* only feature 0 is supported */
643     if (buf[2] != 0 || buf[3] != 0) {
644         ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
645                             ASC_INV_FIELD_IN_CMD_PACKET);
646         return;
647     }
648 
649     /* XXX: could result in alignment problems in some architectures */
650     max_len = ube16_to_cpu(buf + 7);
651 
652     /*
653      * XXX: avoid overflow for io_buffer if max_len is bigger than
654      *      the size of that buffer (dimensioned to max number of
655      *      sectors to transfer at once)
656      *
657      *      Only a problem if the feature/profiles grow.
658      */
659     if (max_len > 512) {
660         /* XXX: assume 1 sector */
661         max_len = 512;
662     }
663 
664     memset(buf, 0, max_len);
665     /*
666      * the number of sectors from the media tells us which profile
667      * to use as current.  0 means there is no media
668      */
669     if (media_is_dvd(s)) {
670         cpu_to_ube16(buf + 6, MMC_PROFILE_DVD_ROM);
671     } else if (media_is_cd(s)) {
672         cpu_to_ube16(buf + 6, MMC_PROFILE_CD_ROM);
673     }
674 
675     buf[10] = 0x02 | 0x01; /* persistent and current */
676     len = 12; /* headers: 8 + 4 */
677     len += ide_atapi_set_profile(buf, &index, MMC_PROFILE_DVD_ROM);
678     len += ide_atapi_set_profile(buf, &index, MMC_PROFILE_CD_ROM);
679     cpu_to_ube32(buf, len - 4); /* data length */
680 
681     ide_atapi_cmd_reply(s, len, max_len);
682 }
683 
684 static void cmd_mode_sense(IDEState *s, uint8_t *buf)
685 {
686     int action, code;
687     int max_len;
688 
689     max_len = ube16_to_cpu(buf + 7);
690     action = buf[2] >> 6;
691     code = buf[2] & 0x3f;
692 
693     switch(action) {
694     case 0: /* current values */
695         switch(code) {
696         case MODE_PAGE_R_W_ERROR: /* error recovery */
697             cpu_to_ube16(&buf[0], 16 - 2);
698             buf[2] = 0x70;
699             buf[3] = 0;
700             buf[4] = 0;
701             buf[5] = 0;
702             buf[6] = 0;
703             buf[7] = 0;
704 
705             buf[8] = MODE_PAGE_R_W_ERROR;
706             buf[9] = 16 - 10;
707             buf[10] = 0x00;
708             buf[11] = 0x05;
709             buf[12] = 0x00;
710             buf[13] = 0x00;
711             buf[14] = 0x00;
712             buf[15] = 0x00;
713             ide_atapi_cmd_reply(s, 16, max_len);
714             break;
715         case MODE_PAGE_AUDIO_CTL:
716             cpu_to_ube16(&buf[0], 24 - 2);
717             buf[2] = 0x70;
718             buf[3] = 0;
719             buf[4] = 0;
720             buf[5] = 0;
721             buf[6] = 0;
722             buf[7] = 0;
723 
724             buf[8] = MODE_PAGE_AUDIO_CTL;
725             buf[9] = 24 - 10;
726             /* Fill with CDROM audio volume */
727             buf[17] = 0;
728             buf[19] = 0;
729             buf[21] = 0;
730             buf[23] = 0;
731 
732             ide_atapi_cmd_reply(s, 24, max_len);
733             break;
734         case MODE_PAGE_CAPABILITIES:
735             cpu_to_ube16(&buf[0], 30 - 2);
736             buf[2] = 0x70;
737             buf[3] = 0;
738             buf[4] = 0;
739             buf[5] = 0;
740             buf[6] = 0;
741             buf[7] = 0;
742 
743             buf[8] = MODE_PAGE_CAPABILITIES;
744             buf[9] = 30 - 10;
745             buf[10] = 0x3b; /* read CDR/CDRW/DVDROM/DVDR/DVDRAM */
746             buf[11] = 0x00;
747 
748             /* Claim PLAY_AUDIO capability (0x01) since some Linux
749                code checks for this to automount media. */
750             buf[12] = 0x71;
751             buf[13] = 3 << 5;
752             buf[14] = (1 << 0) | (1 << 3) | (1 << 5);
753             if (s->tray_locked) {
754                 buf[14] |= 1 << 1;
755             }
756             buf[15] = 0x00; /* No volume & mute control, no changer */
757             cpu_to_ube16(&buf[16], 704); /* 4x read speed */
758             buf[18] = 0; /* Two volume levels */
759             buf[19] = 2;
760             cpu_to_ube16(&buf[20], 512); /* 512k buffer */
761             cpu_to_ube16(&buf[22], 704); /* 4x read speed current */
762             buf[24] = 0;
763             buf[25] = 0;
764             buf[26] = 0;
765             buf[27] = 0;
766             buf[28] = 0;
767             buf[29] = 0;
768             ide_atapi_cmd_reply(s, 30, max_len);
769             break;
770         default:
771             goto error_cmd;
772         }
773         break;
774     case 1: /* changeable values */
775         goto error_cmd;
776     case 2: /* default values */
777         goto error_cmd;
778     default:
779     case 3: /* saved values */
780         ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
781                             ASC_SAVING_PARAMETERS_NOT_SUPPORTED);
782         break;
783     }
784     return;
785 
786 error_cmd:
787     ide_atapi_cmd_error(s, ILLEGAL_REQUEST, ASC_INV_FIELD_IN_CMD_PACKET);
788 }
789 
790 static void cmd_test_unit_ready(IDEState *s, uint8_t *buf)
791 {
792     /* Not Ready Conditions are already handled in ide_atapi_cmd(), so if we
793      * come here, we know that it's ready. */
794     ide_atapi_cmd_ok(s);
795 }
796 
797 static void cmd_prevent_allow_medium_removal(IDEState *s, uint8_t* buf)
798 {
799     s->tray_locked = buf[4] & 1;
800     bdrv_lock_medium(s->bs, buf[4] & 1);
801     ide_atapi_cmd_ok(s);
802 }
803 
804 static void cmd_read(IDEState *s, uint8_t* buf)
805 {
806     int nb_sectors, lba;
807 
808     if (buf[0] == GPCMD_READ_10) {
809         nb_sectors = ube16_to_cpu(buf + 7);
810     } else {
811         nb_sectors = ube32_to_cpu(buf + 6);
812     }
813 
814     lba = ube32_to_cpu(buf + 2);
815     if (nb_sectors == 0) {
816         ide_atapi_cmd_ok(s);
817         return;
818     }
819 
820     ide_atapi_cmd_read(s, lba, nb_sectors, 2048);
821 }
822 
823 static void cmd_read_cd(IDEState *s, uint8_t* buf)
824 {
825     int nb_sectors, lba, transfer_request;
826 
827     nb_sectors = (buf[6] << 16) | (buf[7] << 8) | buf[8];
828     lba = ube32_to_cpu(buf + 2);
829 
830     if (nb_sectors == 0) {
831         ide_atapi_cmd_ok(s);
832         return;
833     }
834 
835     transfer_request = buf[9];
836     switch(transfer_request & 0xf8) {
837     case 0x00:
838         /* nothing */
839         ide_atapi_cmd_ok(s);
840         break;
841     case 0x10:
842         /* normal read */
843         ide_atapi_cmd_read(s, lba, nb_sectors, 2048);
844         break;
845     case 0xf8:
846         /* read all data */
847         ide_atapi_cmd_read(s, lba, nb_sectors, 2352);
848         break;
849     default:
850         ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
851                             ASC_INV_FIELD_IN_CMD_PACKET);
852         break;
853     }
854 }
855 
856 static void cmd_seek(IDEState *s, uint8_t* buf)
857 {
858     unsigned int lba;
859     uint64_t total_sectors = s->nb_sectors >> 2;
860 
861     lba = ube32_to_cpu(buf + 2);
862     if (lba >= total_sectors) {
863         ide_atapi_cmd_error(s, ILLEGAL_REQUEST, ASC_LOGICAL_BLOCK_OOR);
864         return;
865     }
866 
867     ide_atapi_cmd_ok(s);
868 }
869 
870 static void cmd_start_stop_unit(IDEState *s, uint8_t* buf)
871 {
872     int sense;
873     bool start = buf[4] & 1;
874     bool loej = buf[4] & 2;     /* load on start, eject on !start */
875     int pwrcnd = buf[4] & 0xf0;
876 
877     if (pwrcnd) {
878         /* eject/load only happens for power condition == 0 */
879         return;
880     }
881 
882     if (loej) {
883         if (!start && !s->tray_open && s->tray_locked) {
884             sense = bdrv_is_inserted(s->bs)
885                 ? NOT_READY : ILLEGAL_REQUEST;
886             ide_atapi_cmd_error(s, sense, ASC_MEDIA_REMOVAL_PREVENTED);
887             return;
888         }
889 
890         if (s->tray_open != !start) {
891             bdrv_eject(s->bs, !start);
892             s->tray_open = !start;
893         }
894     }
895 
896     ide_atapi_cmd_ok(s);
897 }
898 
899 static void cmd_mechanism_status(IDEState *s, uint8_t* buf)
900 {
901     int max_len = ube16_to_cpu(buf + 8);
902 
903     cpu_to_ube16(buf, 0);
904     /* no current LBA */
905     buf[2] = 0;
906     buf[3] = 0;
907     buf[4] = 0;
908     buf[5] = 1;
909     cpu_to_ube16(buf + 6, 0);
910     ide_atapi_cmd_reply(s, 8, max_len);
911 }
912 
913 static void cmd_read_toc_pma_atip(IDEState *s, uint8_t* buf)
914 {
915     int format, msf, start_track, len;
916     int max_len;
917     uint64_t total_sectors = s->nb_sectors >> 2;
918 
919     max_len = ube16_to_cpu(buf + 7);
920     format = buf[9] >> 6;
921     msf = (buf[1] >> 1) & 1;
922     start_track = buf[6];
923 
924     switch(format) {
925     case 0:
926         len = cdrom_read_toc(total_sectors, buf, msf, start_track);
927         if (len < 0)
928             goto error_cmd;
929         ide_atapi_cmd_reply(s, len, max_len);
930         break;
931     case 1:
932         /* multi session : only a single session defined */
933         memset(buf, 0, 12);
934         buf[1] = 0x0a;
935         buf[2] = 0x01;
936         buf[3] = 0x01;
937         ide_atapi_cmd_reply(s, 12, max_len);
938         break;
939     case 2:
940         len = cdrom_read_toc_raw(total_sectors, buf, msf, start_track);
941         if (len < 0)
942             goto error_cmd;
943         ide_atapi_cmd_reply(s, len, max_len);
944         break;
945     default:
946     error_cmd:
947         ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
948                             ASC_INV_FIELD_IN_CMD_PACKET);
949     }
950 }
951 
952 static void cmd_read_cdvd_capacity(IDEState *s, uint8_t* buf)
953 {
954     uint64_t total_sectors = s->nb_sectors >> 2;
955 
956     /* NOTE: it is really the number of sectors minus 1 */
957     cpu_to_ube32(buf, total_sectors - 1);
958     cpu_to_ube32(buf + 4, 2048);
959     ide_atapi_cmd_reply(s, 8, 8);
960 }
961 
962 static void cmd_read_disc_information(IDEState *s, uint8_t* buf)
963 {
964     uint8_t type = buf[1] & 7;
965     uint32_t max_len = ube16_to_cpu(buf + 7);
966 
967     /* Types 1/2 are only defined for Blu-Ray.  */
968     if (type != 0) {
969         ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
970                             ASC_INV_FIELD_IN_CMD_PACKET);
971         return;
972     }
973 
974     memset(buf, 0, 34);
975     buf[1] = 32;
976     buf[2] = 0xe; /* last session complete, disc finalized */
977     buf[3] = 1;   /* first track on disc */
978     buf[4] = 1;   /* # of sessions */
979     buf[5] = 1;   /* first track of last session */
980     buf[6] = 1;   /* last track of last session */
981     buf[7] = 0x20; /* unrestricted use */
982     buf[8] = 0x00; /* CD-ROM or DVD-ROM */
983     /* 9-10-11: most significant byte corresponding bytes 4-5-6 */
984     /* 12-23: not meaningful for CD-ROM or DVD-ROM */
985     /* 24-31: disc bar code */
986     /* 32: disc application code */
987     /* 33: number of OPC tables */
988 
989     ide_atapi_cmd_reply(s, 34, max_len);
990 }
991 
992 static void cmd_read_dvd_structure(IDEState *s, uint8_t* buf)
993 {
994     int max_len;
995     int media = buf[1];
996     int format = buf[7];
997     int ret;
998 
999     max_len = ube16_to_cpu(buf + 8);
1000 
1001     if (format < 0xff) {
1002         if (media_is_cd(s)) {
1003             ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
1004                                 ASC_INCOMPATIBLE_FORMAT);
1005             return;
1006         } else if (!media_present(s)) {
1007             ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
1008                                 ASC_INV_FIELD_IN_CMD_PACKET);
1009             return;
1010         }
1011     }
1012 
1013     memset(buf, 0, max_len > IDE_DMA_BUF_SECTORS * 512 + 4 ?
1014            IDE_DMA_BUF_SECTORS * 512 + 4 : max_len);
1015 
1016     switch (format) {
1017         case 0x00 ... 0x7f:
1018         case 0xff:
1019             if (media == 0) {
1020                 ret = ide_dvd_read_structure(s, format, buf, buf);
1021 
1022                 if (ret < 0) {
1023                     ide_atapi_cmd_error(s, ILLEGAL_REQUEST, -ret);
1024                 } else {
1025                     ide_atapi_cmd_reply(s, ret, max_len);
1026                 }
1027 
1028                 break;
1029             }
1030             /* TODO: BD support, fall through for now */
1031 
1032         /* Generic disk structures */
1033         case 0x80: /* TODO: AACS volume identifier */
1034         case 0x81: /* TODO: AACS media serial number */
1035         case 0x82: /* TODO: AACS media identifier */
1036         case 0x83: /* TODO: AACS media key block */
1037         case 0x90: /* TODO: List of recognized format layers */
1038         case 0xc0: /* TODO: Write protection status */
1039         default:
1040             ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
1041                                 ASC_INV_FIELD_IN_CMD_PACKET);
1042             break;
1043     }
1044 }
1045 
1046 static void cmd_set_speed(IDEState *s, uint8_t* buf)
1047 {
1048     ide_atapi_cmd_ok(s);
1049 }
1050 
1051 enum {
1052     /*
1053      * Only commands flagged as ALLOW_UA are allowed to run under a
1054      * unit attention condition. (See MMC-5, section 4.1.6.1)
1055      */
1056     ALLOW_UA = 0x01,
1057 
1058     /*
1059      * Commands flagged with CHECK_READY can only execute if a medium is present.
1060      * Otherwise they report the Not Ready Condition. (See MMC-5, section
1061      * 4.1.8)
1062      */
1063     CHECK_READY = 0x02,
1064 };
1065 
1066 static const struct {
1067     void (*handler)(IDEState *s, uint8_t *buf);
1068     int flags;
1069 } atapi_cmd_table[0x100] = {
1070     [ 0x00 ] = { cmd_test_unit_ready,               CHECK_READY },
1071     [ 0x03 ] = { cmd_request_sense,                 ALLOW_UA },
1072     [ 0x12 ] = { cmd_inquiry,                       ALLOW_UA },
1073     [ 0x1b ] = { cmd_start_stop_unit,               0 }, /* [1] */
1074     [ 0x1e ] = { cmd_prevent_allow_medium_removal,  0 },
1075     [ 0x25 ] = { cmd_read_cdvd_capacity,            CHECK_READY },
1076     [ 0x28 ] = { cmd_read, /* (10) */               CHECK_READY },
1077     [ 0x2b ] = { cmd_seek,                          CHECK_READY },
1078     [ 0x43 ] = { cmd_read_toc_pma_atip,             CHECK_READY },
1079     [ 0x46 ] = { cmd_get_configuration,             ALLOW_UA },
1080     [ 0x4a ] = { cmd_get_event_status_notification, ALLOW_UA },
1081     [ 0x51 ] = { cmd_read_disc_information,         CHECK_READY },
1082     [ 0x5a ] = { cmd_mode_sense, /* (10) */         0 },
1083     [ 0xa8 ] = { cmd_read, /* (12) */               CHECK_READY },
1084     [ 0xad ] = { cmd_read_dvd_structure,            CHECK_READY },
1085     [ 0xbb ] = { cmd_set_speed,                     0 },
1086     [ 0xbd ] = { cmd_mechanism_status,              0 },
1087     [ 0xbe ] = { cmd_read_cd,                       CHECK_READY },
1088     /* [1] handler detects and reports not ready condition itself */
1089 };
1090 
1091 void ide_atapi_cmd(IDEState *s)
1092 {
1093     uint8_t *buf;
1094 
1095     buf = s->io_buffer;
1096 #ifdef DEBUG_IDE_ATAPI
1097     {
1098         int i;
1099         printf("ATAPI limit=0x%x packet:", s->lcyl | (s->hcyl << 8));
1100         for(i = 0; i < ATAPI_PACKET_SIZE; i++) {
1101             printf(" %02x", buf[i]);
1102         }
1103         printf("\n");
1104     }
1105 #endif
1106     /*
1107      * If there's a UNIT_ATTENTION condition pending, only command flagged with
1108      * ALLOW_UA are allowed to complete. with other commands getting a CHECK
1109      * condition response unless a higher priority status, defined by the drive
1110      * here, is pending.
1111      */
1112     if (s->sense_key == UNIT_ATTENTION &&
1113         !(atapi_cmd_table[s->io_buffer[0]].flags & ALLOW_UA)) {
1114         ide_atapi_cmd_check_status(s);
1115         return;
1116     }
1117     /*
1118      * When a CD gets changed, we have to report an ejected state and
1119      * then a loaded state to guests so that they detect tray
1120      * open/close and media change events.  Guests that do not use
1121      * GET_EVENT_STATUS_NOTIFICATION to detect such tray open/close
1122      * states rely on this behavior.
1123      */
1124     if (!(atapi_cmd_table[s->io_buffer[0]].flags & ALLOW_UA) &&
1125         !s->tray_open && bdrv_is_inserted(s->bs) && s->cdrom_changed) {
1126 
1127         if (s->cdrom_changed == 1) {
1128             ide_atapi_cmd_error(s, NOT_READY, ASC_MEDIUM_NOT_PRESENT);
1129             s->cdrom_changed = 2;
1130         } else {
1131             ide_atapi_cmd_error(s, UNIT_ATTENTION, ASC_MEDIUM_MAY_HAVE_CHANGED);
1132             s->cdrom_changed = 0;
1133         }
1134 
1135         return;
1136     }
1137 
1138     /* Report a Not Ready condition if appropriate for the command */
1139     if ((atapi_cmd_table[s->io_buffer[0]].flags & CHECK_READY) &&
1140         (!media_present(s) || !bdrv_is_inserted(s->bs)))
1141     {
1142         ide_atapi_cmd_error(s, NOT_READY, ASC_MEDIUM_NOT_PRESENT);
1143         return;
1144     }
1145 
1146     /* Execute the command */
1147     if (atapi_cmd_table[s->io_buffer[0]].handler) {
1148         atapi_cmd_table[s->io_buffer[0]].handler(s, buf);
1149         return;
1150     }
1151 
1152     ide_atapi_cmd_error(s, ILLEGAL_REQUEST, ASC_ILLEGAL_OPCODE);
1153 }
1154