xref: /openbmc/qemu/hw/ide/atapi.c (revision 6016b7b4)
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 "qemu/osdep.h"
27 #include "hw/ide/internal.h"
28 #include "hw/scsi/scsi.h"
29 #include "sysemu/block-backend.h"
30 #include "trace.h"
31 
32 #define ATAPI_SECTOR_BITS (2 + BDRV_SECTOR_BITS)
33 #define ATAPI_SECTOR_SIZE (1 << ATAPI_SECTOR_BITS)
34 
35 static void ide_atapi_cmd_read_dma_cb(void *opaque, int ret);
36 
37 static void padstr8(uint8_t *buf, int buf_size, const char *src)
38 {
39     int i;
40     for(i = 0; i < buf_size; i++) {
41         if (*src)
42             buf[i] = *src++;
43         else
44             buf[i] = ' ';
45     }
46 }
47 
48 static void lba_to_msf(uint8_t *buf, int lba)
49 {
50     lba += 150;
51     buf[0] = (lba / 75) / 60;
52     buf[1] = (lba / 75) % 60;
53     buf[2] = lba % 75;
54 }
55 
56 static inline int media_present(IDEState *s)
57 {
58     return !s->tray_open && s->nb_sectors > 0;
59 }
60 
61 /* XXX: DVDs that could fit on a CD will be reported as a CD */
62 static inline int media_is_dvd(IDEState *s)
63 {
64     return (media_present(s) && s->nb_sectors > CD_MAX_SECTORS);
65 }
66 
67 static inline int media_is_cd(IDEState *s)
68 {
69     return (media_present(s) && s->nb_sectors <= CD_MAX_SECTORS);
70 }
71 
72 static void cd_data_to_raw(uint8_t *buf, int lba)
73 {
74     /* sync bytes */
75     buf[0] = 0x00;
76     memset(buf + 1, 0xff, 10);
77     buf[11] = 0x00;
78     buf += 12;
79     /* MSF */
80     lba_to_msf(buf, lba);
81     buf[3] = 0x01; /* mode 1 data */
82     buf += 4;
83     /* data */
84     buf += 2048;
85     /* XXX: ECC not computed */
86     memset(buf, 0, 288);
87 }
88 
89 static int
90 cd_read_sector_sync(IDEState *s)
91 {
92     int ret;
93     block_acct_start(blk_get_stats(s->blk), &s->acct,
94                      ATAPI_SECTOR_SIZE, BLOCK_ACCT_READ);
95 
96     trace_cd_read_sector_sync(s->lba);
97 
98     switch (s->cd_sector_size) {
99     case 2048:
100         ret = blk_pread(s->blk, (int64_t)s->lba << ATAPI_SECTOR_BITS,
101                         s->io_buffer, ATAPI_SECTOR_SIZE);
102         break;
103     case 2352:
104         ret = blk_pread(s->blk, (int64_t)s->lba << ATAPI_SECTOR_BITS,
105                         s->io_buffer + 16, ATAPI_SECTOR_SIZE);
106         if (ret >= 0) {
107             cd_data_to_raw(s->io_buffer, s->lba);
108         }
109         break;
110     default:
111         block_acct_invalid(blk_get_stats(s->blk), BLOCK_ACCT_READ);
112         return -EIO;
113     }
114 
115     if (ret < 0) {
116         block_acct_failed(blk_get_stats(s->blk), &s->acct);
117     } else {
118         block_acct_done(blk_get_stats(s->blk), &s->acct);
119         s->lba++;
120         s->io_buffer_index = 0;
121     }
122 
123     return ret;
124 }
125 
126 static void cd_read_sector_cb(void *opaque, int ret)
127 {
128     IDEState *s = opaque;
129 
130     trace_cd_read_sector_cb(s->lba, ret);
131 
132     if (ret < 0) {
133         block_acct_failed(blk_get_stats(s->blk), &s->acct);
134         ide_atapi_io_error(s, ret);
135         return;
136     }
137 
138     block_acct_done(blk_get_stats(s->blk), &s->acct);
139 
140     if (s->cd_sector_size == 2352) {
141         cd_data_to_raw(s->io_buffer, s->lba);
142     }
143 
144     s->lba++;
145     s->io_buffer_index = 0;
146     s->status &= ~BUSY_STAT;
147 
148     ide_atapi_cmd_reply_end(s);
149 }
150 
151 static int cd_read_sector(IDEState *s)
152 {
153     void *buf;
154 
155     if (s->cd_sector_size != 2048 && s->cd_sector_size != 2352) {
156         block_acct_invalid(blk_get_stats(s->blk), BLOCK_ACCT_READ);
157         return -EINVAL;
158     }
159 
160     buf = (s->cd_sector_size == 2352) ? s->io_buffer + 16 : s->io_buffer;
161     qemu_iovec_init_buf(&s->qiov, buf, ATAPI_SECTOR_SIZE);
162 
163     trace_cd_read_sector(s->lba);
164 
165     block_acct_start(blk_get_stats(s->blk), &s->acct,
166                      ATAPI_SECTOR_SIZE, BLOCK_ACCT_READ);
167 
168     ide_buffered_readv(s, (int64_t)s->lba << 2, &s->qiov, 4,
169                        cd_read_sector_cb, s);
170 
171     s->status |= BUSY_STAT;
172     return 0;
173 }
174 
175 void ide_atapi_cmd_ok(IDEState *s)
176 {
177     s->error = 0;
178     s->status = READY_STAT | SEEK_STAT;
179     s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
180     ide_transfer_stop(s);
181     ide_set_irq(s->bus);
182 }
183 
184 void ide_atapi_cmd_error(IDEState *s, int sense_key, int asc)
185 {
186     trace_ide_atapi_cmd_error(s, sense_key, asc);
187     s->error = sense_key << 4;
188     s->status = READY_STAT | ERR_STAT;
189     s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
190     s->sense_key = sense_key;
191     s->asc = asc;
192     ide_transfer_stop(s);
193     ide_set_irq(s->bus);
194 }
195 
196 void ide_atapi_io_error(IDEState *s, int ret)
197 {
198     /* XXX: handle more errors */
199     if (ret == -ENOMEDIUM) {
200         ide_atapi_cmd_error(s, NOT_READY,
201                             ASC_MEDIUM_NOT_PRESENT);
202     } else {
203         ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
204                             ASC_LOGICAL_BLOCK_OOR);
205     }
206 }
207 
208 static uint16_t atapi_byte_count_limit(IDEState *s)
209 {
210     uint16_t bcl;
211 
212     bcl = s->lcyl | (s->hcyl << 8);
213     if (bcl == 0xffff) {
214         return 0xfffe;
215     }
216     return bcl;
217 }
218 
219 /* The whole ATAPI transfer logic is handled in this function */
220 void ide_atapi_cmd_reply_end(IDEState *s)
221 {
222     int byte_count_limit, size, ret;
223     while (s->packet_transfer_size > 0) {
224         trace_ide_atapi_cmd_reply_end(s, s->packet_transfer_size,
225                                       s->elementary_transfer_size,
226                                       s->io_buffer_index);
227 
228         /* see if a new sector must be read */
229         if (s->lba != -1 && s->io_buffer_index >= s->cd_sector_size) {
230             if (!s->elementary_transfer_size) {
231                 ret = cd_read_sector(s);
232                 if (ret < 0) {
233                     ide_atapi_io_error(s, ret);
234                 }
235                 return;
236             } else {
237                 /* rebuffering within an elementary transfer is
238                  * only possible with a sync request because we
239                  * end up with a race condition otherwise */
240                 ret = cd_read_sector_sync(s);
241                 if (ret < 0) {
242                     ide_atapi_io_error(s, ret);
243                     return;
244                 }
245             }
246         }
247         if (s->elementary_transfer_size > 0) {
248             /* there are some data left to transmit in this elementary
249                transfer */
250             size = s->cd_sector_size - s->io_buffer_index;
251             if (size > s->elementary_transfer_size)
252                 size = s->elementary_transfer_size;
253         } else {
254             /* a new transfer is needed */
255             s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO;
256             ide_set_irq(s->bus);
257             byte_count_limit = atapi_byte_count_limit(s);
258             trace_ide_atapi_cmd_reply_end_bcl(s, byte_count_limit);
259             size = s->packet_transfer_size;
260             if (size > byte_count_limit) {
261                 /* byte count limit must be even if this case */
262                 if (byte_count_limit & 1)
263                     byte_count_limit--;
264                 size = byte_count_limit;
265             }
266             s->lcyl = size;
267             s->hcyl = size >> 8;
268             s->elementary_transfer_size = size;
269             /* we cannot transmit more than one sector at a time */
270             if (s->lba != -1) {
271                 if (size > (s->cd_sector_size - s->io_buffer_index))
272                     size = (s->cd_sector_size - s->io_buffer_index);
273             }
274             trace_ide_atapi_cmd_reply_end_new(s, s->status);
275         }
276         s->packet_transfer_size -= size;
277         s->elementary_transfer_size -= size;
278         s->io_buffer_index += size;
279         assert(size <= s->io_buffer_total_len);
280         assert(s->io_buffer_index <= s->io_buffer_total_len);
281 
282         /* Some adapters process PIO data right away.  In that case, we need
283          * to avoid mutual recursion between ide_transfer_start
284          * and ide_atapi_cmd_reply_end.
285          */
286         if (!ide_transfer_start_norecurse(s,
287                                           s->io_buffer + s->io_buffer_index - size,
288                                           size, ide_atapi_cmd_reply_end)) {
289             return;
290         }
291     }
292 
293     /* end of transfer */
294     trace_ide_atapi_cmd_reply_end_eot(s, s->status);
295     ide_atapi_cmd_ok(s);
296     ide_set_irq(s->bus);
297 }
298 
299 /* send a reply of 'size' bytes in s->io_buffer to an ATAPI command */
300 static void ide_atapi_cmd_reply(IDEState *s, int size, int max_size)
301 {
302     if (size > max_size)
303         size = max_size;
304     s->lba = -1; /* no sector read */
305     s->packet_transfer_size = size;
306     s->io_buffer_size = size;    /* dma: send the reply data as one chunk */
307     s->elementary_transfer_size = 0;
308 
309     if (s->atapi_dma) {
310         block_acct_start(blk_get_stats(s->blk), &s->acct, size,
311                          BLOCK_ACCT_READ);
312         s->status = READY_STAT | SEEK_STAT | DRQ_STAT;
313         ide_start_dma(s, ide_atapi_cmd_read_dma_cb);
314     } else {
315         s->status = READY_STAT | SEEK_STAT;
316         s->io_buffer_index = 0;
317         ide_atapi_cmd_reply_end(s);
318     }
319 }
320 
321 /* start a CD-CDROM read command */
322 static void ide_atapi_cmd_read_pio(IDEState *s, int lba, int nb_sectors,
323                                    int sector_size)
324 {
325     assert(0 <= lba && lba < (s->nb_sectors >> 2));
326 
327     s->lba = lba;
328     s->packet_transfer_size = nb_sectors * sector_size;
329     s->elementary_transfer_size = 0;
330     s->io_buffer_index = sector_size;
331     s->cd_sector_size = sector_size;
332 
333     ide_atapi_cmd_reply_end(s);
334 }
335 
336 static void ide_atapi_cmd_check_status(IDEState *s)
337 {
338     trace_ide_atapi_cmd_check_status(s);
339     s->error = MC_ERR | (UNIT_ATTENTION << 4);
340     s->status = ERR_STAT;
341     s->nsector = 0;
342     ide_set_irq(s->bus);
343 }
344 /* ATAPI DMA support */
345 
346 static void ide_atapi_cmd_read_dma_cb(void *opaque, int ret)
347 {
348     IDEState *s = opaque;
349     int data_offset, n;
350 
351     if (ret < 0) {
352         if (ide_handle_rw_error(s, -ret, ide_dma_cmd_to_retry(s->dma_cmd))) {
353             if (s->bus->error_status) {
354                 s->bus->dma->aiocb = NULL;
355                 return;
356             }
357             goto eot;
358         }
359     }
360 
361     if (s->io_buffer_size > 0) {
362         /*
363          * For a cdrom read sector command (s->lba != -1),
364          * adjust the lba for the next s->io_buffer_size chunk
365          * and dma the current chunk.
366          * For a command != read (s->lba == -1), just transfer
367          * the reply data.
368          */
369         if (s->lba != -1) {
370             if (s->cd_sector_size == 2352) {
371                 n = 1;
372                 cd_data_to_raw(s->io_buffer, s->lba);
373             } else {
374                 n = s->io_buffer_size >> 11;
375             }
376             s->lba += n;
377         }
378         s->packet_transfer_size -= s->io_buffer_size;
379         if (s->bus->dma->ops->rw_buf(s->bus->dma, 1) == 0)
380             goto eot;
381     }
382 
383     if (s->packet_transfer_size <= 0) {
384         s->status = READY_STAT | SEEK_STAT;
385         s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
386         ide_set_irq(s->bus);
387         goto eot;
388     }
389 
390     s->io_buffer_index = 0;
391     if (s->cd_sector_size == 2352) {
392         n = 1;
393         s->io_buffer_size = s->cd_sector_size;
394         data_offset = 16;
395     } else {
396         n = s->packet_transfer_size >> 11;
397         if (n > (IDE_DMA_BUF_SECTORS / 4))
398             n = (IDE_DMA_BUF_SECTORS / 4);
399         s->io_buffer_size = n * 2048;
400         data_offset = 0;
401     }
402     trace_ide_atapi_cmd_read_dma_cb_aio(s, s->lba, n);
403     qemu_iovec_init_buf(&s->bus->dma->qiov, s->io_buffer + data_offset,
404                         n * ATAPI_SECTOR_SIZE);
405 
406     s->bus->dma->aiocb = ide_buffered_readv(s, (int64_t)s->lba << 2,
407                                             &s->bus->dma->qiov, n * 4,
408                                             ide_atapi_cmd_read_dma_cb, s);
409     return;
410 
411 eot:
412     if (ret < 0) {
413         block_acct_failed(blk_get_stats(s->blk), &s->acct);
414     } else {
415         block_acct_done(blk_get_stats(s->blk), &s->acct);
416     }
417     ide_set_inactive(s, false);
418 }
419 
420 /* start a CD-CDROM read command with DMA */
421 /* XXX: test if DMA is available */
422 static void ide_atapi_cmd_read_dma(IDEState *s, int lba, int nb_sectors,
423                                    int sector_size)
424 {
425     assert(0 <= lba && lba < (s->nb_sectors >> 2));
426 
427     s->lba = lba;
428     s->packet_transfer_size = nb_sectors * sector_size;
429     s->io_buffer_size = 0;
430     s->cd_sector_size = sector_size;
431 
432     block_acct_start(blk_get_stats(s->blk), &s->acct, s->packet_transfer_size,
433                      BLOCK_ACCT_READ);
434 
435     /* XXX: check if BUSY_STAT should be set */
436     s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT;
437     ide_start_dma(s, ide_atapi_cmd_read_dma_cb);
438 }
439 
440 static void ide_atapi_cmd_read(IDEState *s, int lba, int nb_sectors,
441                                int sector_size)
442 {
443     trace_ide_atapi_cmd_read(s, s->atapi_dma ? "dma" : "pio",
444                              lba, nb_sectors);
445     if (s->atapi_dma) {
446         ide_atapi_cmd_read_dma(s, lba, nb_sectors, sector_size);
447     } else {
448         ide_atapi_cmd_read_pio(s, lba, nb_sectors, sector_size);
449     }
450 }
451 
452 void ide_atapi_dma_restart(IDEState *s)
453 {
454     /*
455      * At this point we can just re-evaluate the packet command and start over.
456      * The presence of ->dma_cb callback in the pre_save ensures that the packet
457      * command has been completely sent and we can safely restart command.
458      */
459     s->unit = s->bus->retry_unit;
460     s->bus->dma->ops->restart_dma(s->bus->dma);
461     ide_atapi_cmd(s);
462 }
463 
464 static inline uint8_t ide_atapi_set_profile(uint8_t *buf, uint8_t *index,
465                                             uint16_t profile)
466 {
467     uint8_t *buf_profile = buf + 12; /* start of profiles */
468 
469     buf_profile += ((*index) * 4); /* start of indexed profile */
470     stw_be_p(buf_profile, profile);
471     buf_profile[2] = ((buf_profile[0] == buf[6]) && (buf_profile[1] == buf[7]));
472 
473     /* each profile adds 4 bytes to the response */
474     (*index)++;
475     buf[11] += 4; /* Additional Length */
476 
477     return 4;
478 }
479 
480 static int ide_dvd_read_structure(IDEState *s, int format,
481                                   const uint8_t *packet, uint8_t *buf)
482 {
483     switch (format) {
484         case 0x0: /* Physical format information */
485             {
486                 int layer = packet[6];
487                 uint64_t total_sectors;
488 
489                 if (layer != 0)
490                     return -ASC_INV_FIELD_IN_CMD_PACKET;
491 
492                 total_sectors = s->nb_sectors >> 2;
493                 if (total_sectors == 0) {
494                     return -ASC_MEDIUM_NOT_PRESENT;
495                 }
496 
497                 buf[4] = 1;   /* DVD-ROM, part version 1 */
498                 buf[5] = 0xf; /* 120mm disc, minimum rate unspecified */
499                 buf[6] = 1;   /* one layer, read-only (per MMC-2 spec) */
500                 buf[7] = 0;   /* default densities */
501 
502                 /* FIXME: 0x30000 per spec? */
503                 stl_be_p(buf + 8, 0); /* start sector */
504                 stl_be_p(buf + 12, total_sectors - 1); /* end sector */
505                 stl_be_p(buf + 16, total_sectors - 1); /* l0 end sector */
506 
507                 /* Size of buffer, not including 2 byte size field */
508                 stw_be_p(buf, 2048 + 2);
509 
510                 /* 2k data + 4 byte header */
511                 return (2048 + 4);
512             }
513 
514         case 0x01: /* DVD copyright information */
515             buf[4] = 0; /* no copyright data */
516             buf[5] = 0; /* no region restrictions */
517 
518             /* Size of buffer, not including 2 byte size field */
519             stw_be_p(buf, 4 + 2);
520 
521             /* 4 byte header + 4 byte data */
522             return (4 + 4);
523 
524         case 0x03: /* BCA information - invalid field for no BCA info */
525             return -ASC_INV_FIELD_IN_CMD_PACKET;
526 
527         case 0x04: /* DVD disc manufacturing information */
528             /* Size of buffer, not including 2 byte size field */
529             stw_be_p(buf, 2048 + 2);
530 
531             /* 2k data + 4 byte header */
532             return (2048 + 4);
533 
534         case 0xff:
535             /*
536              * This lists all the command capabilities above.  Add new ones
537              * in order and update the length and buffer return values.
538              */
539 
540             buf[4] = 0x00; /* Physical format */
541             buf[5] = 0x40; /* Not writable, is readable */
542             stw_be_p(buf + 6, 2048 + 4);
543 
544             buf[8] = 0x01; /* Copyright info */
545             buf[9] = 0x40; /* Not writable, is readable */
546             stw_be_p(buf + 10, 4 + 4);
547 
548             buf[12] = 0x03; /* BCA info */
549             buf[13] = 0x40; /* Not writable, is readable */
550             stw_be_p(buf + 14, 188 + 4);
551 
552             buf[16] = 0x04; /* Manufacturing info */
553             buf[17] = 0x40; /* Not writable, is readable */
554             stw_be_p(buf + 18, 2048 + 4);
555 
556             /* Size of buffer, not including 2 byte size field */
557             stw_be_p(buf, 16 + 2);
558 
559             /* data written + 4 byte header */
560             return (16 + 4);
561 
562         default: /* TODO: formats beyond DVD-ROM requires */
563             return -ASC_INV_FIELD_IN_CMD_PACKET;
564     }
565 }
566 
567 static unsigned int event_status_media(IDEState *s,
568                                        uint8_t *buf)
569 {
570     uint8_t event_code, media_status;
571 
572     media_status = 0;
573     if (s->tray_open) {
574         media_status = MS_TRAY_OPEN;
575     } else if (blk_is_inserted(s->blk)) {
576         media_status = MS_MEDIA_PRESENT;
577     }
578 
579     /* Event notification descriptor */
580     event_code = MEC_NO_CHANGE;
581     if (media_status != MS_TRAY_OPEN) {
582         if (s->events.new_media) {
583             event_code = MEC_NEW_MEDIA;
584             s->events.new_media = false;
585         } else if (s->events.eject_request) {
586             event_code = MEC_EJECT_REQUESTED;
587             s->events.eject_request = false;
588         }
589     }
590 
591     buf[4] = event_code;
592     buf[5] = media_status;
593 
594     /* These fields are reserved, just clear them. */
595     buf[6] = 0;
596     buf[7] = 0;
597 
598     return 8; /* We wrote to 4 extra bytes from the header */
599 }
600 
601 /*
602  * Before transferring data or otherwise signalling acceptance of a command
603  * marked CONDDATA, we must check the validity of the byte_count_limit.
604  */
605 static bool validate_bcl(IDEState *s)
606 {
607     /* TODO: Check IDENTIFY data word 125 for defacult BCL (currently 0) */
608     if (s->atapi_dma || atapi_byte_count_limit(s)) {
609         return true;
610     }
611 
612     /* TODO: Move abort back into core.c and introduce proper error flow between
613      *       ATAPI layer and IDE core layer */
614     ide_abort_command(s);
615     return false;
616 }
617 
618 static void cmd_get_event_status_notification(IDEState *s,
619                                               uint8_t *buf)
620 {
621     const uint8_t *packet = buf;
622 
623     struct {
624         uint8_t opcode;
625         uint8_t polled;        /* lsb bit is polled; others are reserved */
626         uint8_t reserved2[2];
627         uint8_t class;
628         uint8_t reserved3[2];
629         uint16_t len;
630         uint8_t control;
631     } QEMU_PACKED *gesn_cdb;
632 
633     struct {
634         uint16_t len;
635         uint8_t notification_class;
636         uint8_t supported_events;
637     } QEMU_PACKED *gesn_event_header;
638     unsigned int max_len, used_len;
639 
640     gesn_cdb = (void *)packet;
641     gesn_event_header = (void *)buf;
642 
643     max_len = be16_to_cpu(gesn_cdb->len);
644 
645     /* It is fine by the MMC spec to not support async mode operations */
646     if (!(gesn_cdb->polled & 0x01)) { /* asynchronous mode */
647         /* Only polling is supported, asynchronous mode is not. */
648         ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
649                             ASC_INV_FIELD_IN_CMD_PACKET);
650         return;
651     }
652 
653     /* polling mode operation */
654 
655     /*
656      * These are the supported events.
657      *
658      * We currently only support requests of the 'media' type.
659      * Notification class requests and supported event classes are bitmasks,
660      * but they are build from the same values as the "notification class"
661      * field.
662      */
663     gesn_event_header->supported_events = 1 << GESN_MEDIA;
664 
665     /*
666      * We use |= below to set the class field; other bits in this byte
667      * are reserved now but this is useful to do if we have to use the
668      * reserved fields later.
669      */
670     gesn_event_header->notification_class = 0;
671 
672     /*
673      * Responses to requests are to be based on request priority.  The
674      * notification_class_request_type enum above specifies the
675      * priority: upper elements are higher prio than lower ones.
676      */
677     if (gesn_cdb->class & (1 << GESN_MEDIA)) {
678         gesn_event_header->notification_class |= GESN_MEDIA;
679         used_len = event_status_media(s, buf);
680     } else {
681         gesn_event_header->notification_class = 0x80; /* No event available */
682         used_len = sizeof(*gesn_event_header);
683     }
684     gesn_event_header->len = cpu_to_be16(used_len
685                                          - sizeof(*gesn_event_header));
686     ide_atapi_cmd_reply(s, used_len, max_len);
687 }
688 
689 static void cmd_request_sense(IDEState *s, uint8_t *buf)
690 {
691     int max_len = buf[4];
692 
693     memset(buf, 0, 18);
694     buf[0] = 0x70 | (1 << 7);
695     buf[2] = s->sense_key;
696     buf[7] = 10;
697     buf[12] = s->asc;
698 
699     if (s->sense_key == UNIT_ATTENTION) {
700         s->sense_key = NO_SENSE;
701     }
702 
703     ide_atapi_cmd_reply(s, 18, max_len);
704 }
705 
706 static void cmd_inquiry(IDEState *s, uint8_t *buf)
707 {
708     uint8_t page_code = buf[2];
709     int max_len = buf[4];
710 
711     unsigned idx = 0;
712     unsigned size_idx;
713     unsigned preamble_len;
714 
715     /* If the EVPD (Enable Vital Product Data) bit is set in byte 1,
716      * we are being asked for a specific page of info indicated by byte 2. */
717     if (buf[1] & 0x01) {
718         preamble_len = 4;
719         size_idx = 3;
720 
721         buf[idx++] = 0x05;      /* CD-ROM */
722         buf[idx++] = page_code; /* Page Code */
723         buf[idx++] = 0x00;      /* reserved */
724         idx++;                  /* length (set later) */
725 
726         switch (page_code) {
727         case 0x00:
728             /* Supported Pages: List of supported VPD responses. */
729             buf[idx++] = 0x00; /* 0x00: Supported Pages, and: */
730             buf[idx++] = 0x83; /* 0x83: Device Identification. */
731             break;
732 
733         case 0x83:
734             /* Device Identification. Each entry is optional, but the entries
735              * included here are modeled after libata's VPD responses.
736              * If the response is given, at least one entry must be present. */
737 
738             /* Entry 1: Serial */
739             if (idx + 24 > max_len) {
740                 /* Not enough room for even the first entry: */
741                 /* 4 byte header + 20 byte string */
742                 ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
743                                     ASC_DATA_PHASE_ERROR);
744                 return;
745             }
746             buf[idx++] = 0x02; /* Ascii */
747             buf[idx++] = 0x00; /* Vendor Specific */
748             buf[idx++] = 0x00;
749             buf[idx++] = 20;   /* Remaining length */
750             padstr8(buf + idx, 20, s->drive_serial_str);
751             idx += 20;
752 
753             /* Entry 2: Drive Model and Serial */
754             if (idx + 72 > max_len) {
755                 /* 4 (header) + 8 (vendor) + 60 (model & serial) */
756                 goto out;
757             }
758             buf[idx++] = 0x02; /* Ascii */
759             buf[idx++] = 0x01; /* T10 Vendor */
760             buf[idx++] = 0x00;
761             buf[idx++] = 68;
762             padstr8(buf + idx, 8, "ATA"); /* Generic T10 vendor */
763             idx += 8;
764             padstr8(buf + idx, 40, s->drive_model_str);
765             idx += 40;
766             padstr8(buf + idx, 20, s->drive_serial_str);
767             idx += 20;
768 
769             /* Entry 3: WWN */
770             if (s->wwn && (idx + 12 <= max_len)) {
771                 /* 4 byte header + 8 byte wwn */
772                 buf[idx++] = 0x01; /* Binary */
773                 buf[idx++] = 0x03; /* NAA */
774                 buf[idx++] = 0x00;
775                 buf[idx++] = 0x08;
776                 stq_be_p(&buf[idx], s->wwn);
777                 idx += 8;
778             }
779             break;
780 
781         default:
782             /* SPC-3, revision 23 sec. 6.4 */
783             ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
784                                 ASC_INV_FIELD_IN_CMD_PACKET);
785             return;
786         }
787     } else {
788         preamble_len = 5;
789         size_idx = 4;
790 
791         buf[0] = 0x05; /* CD-ROM */
792         buf[1] = 0x80; /* removable */
793         buf[2] = 0x00; /* ISO */
794         buf[3] = 0x21; /* ATAPI-2 (XXX: put ATAPI-4 ?) */
795         /* buf[size_idx] set below. */
796         buf[5] = 0;    /* reserved */
797         buf[6] = 0;    /* reserved */
798         buf[7] = 0;    /* reserved */
799         padstr8(buf + 8, 8, "QEMU");
800         padstr8(buf + 16, 16, "QEMU DVD-ROM");
801         padstr8(buf + 32, 4, s->version);
802         idx = 36;
803     }
804 
805  out:
806     buf[size_idx] = idx - preamble_len;
807     ide_atapi_cmd_reply(s, idx, max_len);
808 }
809 
810 static void cmd_get_configuration(IDEState *s, uint8_t *buf)
811 {
812     uint32_t len;
813     uint8_t index = 0;
814     int max_len;
815 
816     /* only feature 0 is supported */
817     if (buf[2] != 0 || buf[3] != 0) {
818         ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
819                             ASC_INV_FIELD_IN_CMD_PACKET);
820         return;
821     }
822 
823     /* XXX: could result in alignment problems in some architectures */
824     max_len = lduw_be_p(buf + 7);
825 
826     /*
827      * XXX: avoid overflow for io_buffer if max_len is bigger than
828      *      the size of that buffer (dimensioned to max number of
829      *      sectors to transfer at once)
830      *
831      *      Only a problem if the feature/profiles grow.
832      */
833     if (max_len > BDRV_SECTOR_SIZE) {
834         /* XXX: assume 1 sector */
835         max_len = BDRV_SECTOR_SIZE;
836     }
837 
838     memset(buf, 0, max_len);
839     /*
840      * the number of sectors from the media tells us which profile
841      * to use as current.  0 means there is no media
842      */
843     if (media_is_dvd(s)) {
844         stw_be_p(buf + 6, MMC_PROFILE_DVD_ROM);
845     } else if (media_is_cd(s)) {
846         stw_be_p(buf + 6, MMC_PROFILE_CD_ROM);
847     }
848 
849     buf[10] = 0x02 | 0x01; /* persistent and current */
850     len = 12; /* headers: 8 + 4 */
851     len += ide_atapi_set_profile(buf, &index, MMC_PROFILE_DVD_ROM);
852     len += ide_atapi_set_profile(buf, &index, MMC_PROFILE_CD_ROM);
853     stl_be_p(buf, len - 4); /* data length */
854 
855     ide_atapi_cmd_reply(s, len, max_len);
856 }
857 
858 static void cmd_mode_sense(IDEState *s, uint8_t *buf)
859 {
860     int action, code;
861     int max_len;
862 
863     max_len = lduw_be_p(buf + 7);
864     action = buf[2] >> 6;
865     code = buf[2] & 0x3f;
866 
867     switch(action) {
868     case 0: /* current values */
869         switch(code) {
870         case MODE_PAGE_R_W_ERROR: /* error recovery */
871             stw_be_p(&buf[0], 16 - 2);
872             buf[2] = 0x70;
873             buf[3] = 0;
874             buf[4] = 0;
875             buf[5] = 0;
876             buf[6] = 0;
877             buf[7] = 0;
878 
879             buf[8] = MODE_PAGE_R_W_ERROR;
880             buf[9] = 16 - 10;
881             buf[10] = 0x00;
882             buf[11] = 0x05;
883             buf[12] = 0x00;
884             buf[13] = 0x00;
885             buf[14] = 0x00;
886             buf[15] = 0x00;
887             ide_atapi_cmd_reply(s, 16, max_len);
888             break;
889         case MODE_PAGE_AUDIO_CTL:
890             stw_be_p(&buf[0], 24 - 2);
891             buf[2] = 0x70;
892             buf[3] = 0;
893             buf[4] = 0;
894             buf[5] = 0;
895             buf[6] = 0;
896             buf[7] = 0;
897 
898             buf[8] = MODE_PAGE_AUDIO_CTL;
899             buf[9] = 24 - 10;
900             /* Fill with CDROM audio volume */
901             buf[17] = 0;
902             buf[19] = 0;
903             buf[21] = 0;
904             buf[23] = 0;
905 
906             ide_atapi_cmd_reply(s, 24, max_len);
907             break;
908         case MODE_PAGE_CAPABILITIES:
909             stw_be_p(&buf[0], 30 - 2);
910             buf[2] = 0x70;
911             buf[3] = 0;
912             buf[4] = 0;
913             buf[5] = 0;
914             buf[6] = 0;
915             buf[7] = 0;
916 
917             buf[8] = MODE_PAGE_CAPABILITIES;
918             buf[9] = 30 - 10;
919             buf[10] = 0x3b; /* read CDR/CDRW/DVDROM/DVDR/DVDRAM */
920             buf[11] = 0x00;
921 
922             /* Claim PLAY_AUDIO capability (0x01) since some Linux
923                code checks for this to automount media. */
924             buf[12] = 0x71;
925             buf[13] = 3 << 5;
926             buf[14] = (1 << 0) | (1 << 3) | (1 << 5);
927             if (s->tray_locked) {
928                 buf[14] |= 1 << 1;
929             }
930             buf[15] = 0x00; /* No volume & mute control, no changer */
931             stw_be_p(&buf[16], 704); /* 4x read speed */
932             buf[18] = 0; /* Two volume levels */
933             buf[19] = 2;
934             stw_be_p(&buf[20], 512); /* 512k buffer */
935             stw_be_p(&buf[22], 704); /* 4x read speed current */
936             buf[24] = 0;
937             buf[25] = 0;
938             buf[26] = 0;
939             buf[27] = 0;
940             buf[28] = 0;
941             buf[29] = 0;
942             ide_atapi_cmd_reply(s, 30, max_len);
943             break;
944         default:
945             goto error_cmd;
946         }
947         break;
948     case 1: /* changeable values */
949         goto error_cmd;
950     case 2: /* default values */
951         goto error_cmd;
952     default:
953     case 3: /* saved values */
954         ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
955                             ASC_SAVING_PARAMETERS_NOT_SUPPORTED);
956         break;
957     }
958     return;
959 
960 error_cmd:
961     ide_atapi_cmd_error(s, ILLEGAL_REQUEST, ASC_INV_FIELD_IN_CMD_PACKET);
962 }
963 
964 static void cmd_test_unit_ready(IDEState *s, uint8_t *buf)
965 {
966     /* Not Ready Conditions are already handled in ide_atapi_cmd(), so if we
967      * come here, we know that it's ready. */
968     ide_atapi_cmd_ok(s);
969 }
970 
971 static void cmd_prevent_allow_medium_removal(IDEState *s, uint8_t* buf)
972 {
973     s->tray_locked = buf[4] & 1;
974     blk_lock_medium(s->blk, buf[4] & 1);
975     ide_atapi_cmd_ok(s);
976 }
977 
978 static void cmd_read(IDEState *s, uint8_t* buf)
979 {
980     unsigned int nb_sectors, lba;
981 
982     /* Total logical sectors of ATAPI_SECTOR_SIZE(=2048) bytes */
983     uint64_t total_sectors = s->nb_sectors >> 2;
984 
985     if (buf[0] == GPCMD_READ_10) {
986         nb_sectors = lduw_be_p(buf + 7);
987     } else {
988         nb_sectors = ldl_be_p(buf + 6);
989     }
990     if (nb_sectors == 0) {
991         ide_atapi_cmd_ok(s);
992         return;
993     }
994 
995     lba = ldl_be_p(buf + 2);
996     if (lba >= total_sectors || lba + nb_sectors - 1 >= total_sectors) {
997         ide_atapi_cmd_error(s, ILLEGAL_REQUEST, ASC_LOGICAL_BLOCK_OOR);
998         return;
999     }
1000 
1001     ide_atapi_cmd_read(s, lba, nb_sectors, 2048);
1002 }
1003 
1004 static void cmd_read_cd(IDEState *s, uint8_t* buf)
1005 {
1006     unsigned int nb_sectors, lba, transfer_request;
1007 
1008     /* Total logical sectors of ATAPI_SECTOR_SIZE(=2048) bytes */
1009     uint64_t total_sectors = s->nb_sectors >> 2;
1010 
1011     nb_sectors = (buf[6] << 16) | (buf[7] << 8) | buf[8];
1012     if (nb_sectors == 0) {
1013         ide_atapi_cmd_ok(s);
1014         return;
1015     }
1016 
1017     lba = ldl_be_p(buf + 2);
1018     if (lba >= total_sectors || lba + nb_sectors - 1 >= total_sectors) {
1019         ide_atapi_cmd_error(s, ILLEGAL_REQUEST, ASC_LOGICAL_BLOCK_OOR);
1020         return;
1021     }
1022 
1023     transfer_request = buf[9] & 0xf8;
1024     if (transfer_request == 0x00) {
1025         /* nothing */
1026         ide_atapi_cmd_ok(s);
1027         return;
1028     }
1029 
1030     /* Check validity of BCL before transferring data */
1031     if (!validate_bcl(s)) {
1032         return;
1033     }
1034 
1035     switch (transfer_request) {
1036     case 0x10:
1037         /* normal read */
1038         ide_atapi_cmd_read(s, lba, nb_sectors, 2048);
1039         break;
1040     case 0xf8:
1041         /* read all data */
1042         ide_atapi_cmd_read(s, lba, nb_sectors, 2352);
1043         break;
1044     default:
1045         ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
1046                             ASC_INV_FIELD_IN_CMD_PACKET);
1047         break;
1048     }
1049 }
1050 
1051 static void cmd_seek(IDEState *s, uint8_t* buf)
1052 {
1053     unsigned int lba;
1054     uint64_t total_sectors = s->nb_sectors >> 2;
1055 
1056     lba = ldl_be_p(buf + 2);
1057     if (lba >= total_sectors) {
1058         ide_atapi_cmd_error(s, ILLEGAL_REQUEST, ASC_LOGICAL_BLOCK_OOR);
1059         return;
1060     }
1061 
1062     ide_atapi_cmd_ok(s);
1063 }
1064 
1065 static void cmd_start_stop_unit(IDEState *s, uint8_t* buf)
1066 {
1067     int sense;
1068     bool start = buf[4] & 1;
1069     bool loej = buf[4] & 2;     /* load on start, eject on !start */
1070     int pwrcnd = buf[4] & 0xf0;
1071 
1072     if (pwrcnd) {
1073         /* eject/load only happens for power condition == 0 */
1074         ide_atapi_cmd_ok(s);
1075         return;
1076     }
1077 
1078     if (loej) {
1079         if (!start && !s->tray_open && s->tray_locked) {
1080             sense = blk_is_inserted(s->blk)
1081                 ? NOT_READY : ILLEGAL_REQUEST;
1082             ide_atapi_cmd_error(s, sense, ASC_MEDIA_REMOVAL_PREVENTED);
1083             return;
1084         }
1085 
1086         if (s->tray_open != !start) {
1087             blk_eject(s->blk, !start);
1088             s->tray_open = !start;
1089         }
1090     }
1091 
1092     ide_atapi_cmd_ok(s);
1093 }
1094 
1095 static void cmd_mechanism_status(IDEState *s, uint8_t* buf)
1096 {
1097     int max_len = lduw_be_p(buf + 8);
1098 
1099     stw_be_p(buf, 0);
1100     /* no current LBA */
1101     buf[2] = 0;
1102     buf[3] = 0;
1103     buf[4] = 0;
1104     buf[5] = 1;
1105     stw_be_p(buf + 6, 0);
1106     ide_atapi_cmd_reply(s, 8, max_len);
1107 }
1108 
1109 static void cmd_read_toc_pma_atip(IDEState *s, uint8_t* buf)
1110 {
1111     int format, msf, start_track, len;
1112     int max_len;
1113     uint64_t total_sectors = s->nb_sectors >> 2;
1114 
1115     max_len = lduw_be_p(buf + 7);
1116     format = buf[9] >> 6;
1117     msf = (buf[1] >> 1) & 1;
1118     start_track = buf[6];
1119 
1120     switch(format) {
1121     case 0:
1122         len = cdrom_read_toc(total_sectors, buf, msf, start_track);
1123         if (len < 0)
1124             goto error_cmd;
1125         ide_atapi_cmd_reply(s, len, max_len);
1126         break;
1127     case 1:
1128         /* multi session : only a single session defined */
1129         memset(buf, 0, 12);
1130         buf[1] = 0x0a;
1131         buf[2] = 0x01;
1132         buf[3] = 0x01;
1133         ide_atapi_cmd_reply(s, 12, max_len);
1134         break;
1135     case 2:
1136         len = cdrom_read_toc_raw(total_sectors, buf, msf, start_track);
1137         if (len < 0)
1138             goto error_cmd;
1139         ide_atapi_cmd_reply(s, len, max_len);
1140         break;
1141     default:
1142     error_cmd:
1143         ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
1144                             ASC_INV_FIELD_IN_CMD_PACKET);
1145     }
1146 }
1147 
1148 static void cmd_read_cdvd_capacity(IDEState *s, uint8_t* buf)
1149 {
1150     uint64_t total_sectors = s->nb_sectors >> 2;
1151 
1152     /* NOTE: it is really the number of sectors minus 1 */
1153     stl_be_p(buf, total_sectors - 1);
1154     stl_be_p(buf + 4, 2048);
1155     ide_atapi_cmd_reply(s, 8, 8);
1156 }
1157 
1158 static void cmd_read_disc_information(IDEState *s, uint8_t* buf)
1159 {
1160     uint8_t type = buf[1] & 7;
1161     uint32_t max_len = lduw_be_p(buf + 7);
1162 
1163     /* Types 1/2 are only defined for Blu-Ray.  */
1164     if (type != 0) {
1165         ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
1166                             ASC_INV_FIELD_IN_CMD_PACKET);
1167         return;
1168     }
1169 
1170     memset(buf, 0, 34);
1171     buf[1] = 32;
1172     buf[2] = 0xe; /* last session complete, disc finalized */
1173     buf[3] = 1;   /* first track on disc */
1174     buf[4] = 1;   /* # of sessions */
1175     buf[5] = 1;   /* first track of last session */
1176     buf[6] = 1;   /* last track of last session */
1177     buf[7] = 0x20; /* unrestricted use */
1178     buf[8] = 0x00; /* CD-ROM or DVD-ROM */
1179     /* 9-10-11: most significant byte corresponding bytes 4-5-6 */
1180     /* 12-23: not meaningful for CD-ROM or DVD-ROM */
1181     /* 24-31: disc bar code */
1182     /* 32: disc application code */
1183     /* 33: number of OPC tables */
1184 
1185     ide_atapi_cmd_reply(s, 34, max_len);
1186 }
1187 
1188 static void cmd_read_dvd_structure(IDEState *s, uint8_t* buf)
1189 {
1190     int max_len;
1191     int media = buf[1];
1192     int format = buf[7];
1193     int ret;
1194 
1195     max_len = lduw_be_p(buf + 8);
1196 
1197     if (format < 0xff) {
1198         if (media_is_cd(s)) {
1199             ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
1200                                 ASC_INCOMPATIBLE_FORMAT);
1201             return;
1202         } else if (!media_present(s)) {
1203             ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
1204                                 ASC_INV_FIELD_IN_CMD_PACKET);
1205             return;
1206         }
1207     }
1208 
1209     memset(buf, 0, max_len > IDE_DMA_BUF_SECTORS * BDRV_SECTOR_SIZE + 4 ?
1210            IDE_DMA_BUF_SECTORS * BDRV_SECTOR_SIZE + 4 : max_len);
1211 
1212     switch (format) {
1213         case 0x00 ... 0x7f:
1214         case 0xff:
1215             if (media == 0) {
1216                 ret = ide_dvd_read_structure(s, format, buf, buf);
1217 
1218                 if (ret < 0) {
1219                     ide_atapi_cmd_error(s, ILLEGAL_REQUEST, -ret);
1220                 } else {
1221                     ide_atapi_cmd_reply(s, ret, max_len);
1222                 }
1223 
1224                 break;
1225             }
1226             /* TODO: BD support, fall through for now */
1227 
1228         /* Generic disk structures */
1229         case 0x80: /* TODO: AACS volume identifier */
1230         case 0x81: /* TODO: AACS media serial number */
1231         case 0x82: /* TODO: AACS media identifier */
1232         case 0x83: /* TODO: AACS media key block */
1233         case 0x90: /* TODO: List of recognized format layers */
1234         case 0xc0: /* TODO: Write protection status */
1235         default:
1236             ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
1237                                 ASC_INV_FIELD_IN_CMD_PACKET);
1238             break;
1239     }
1240 }
1241 
1242 static void cmd_set_speed(IDEState *s, uint8_t* buf)
1243 {
1244     ide_atapi_cmd_ok(s);
1245 }
1246 
1247 enum {
1248     /*
1249      * Only commands flagged as ALLOW_UA are allowed to run under a
1250      * unit attention condition. (See MMC-5, section 4.1.6.1)
1251      */
1252     ALLOW_UA = 0x01,
1253 
1254     /*
1255      * Commands flagged with CHECK_READY can only execute if a medium is present.
1256      * Otherwise they report the Not Ready Condition. (See MMC-5, section
1257      * 4.1.8)
1258      */
1259     CHECK_READY = 0x02,
1260 
1261     /*
1262      * Commands flagged with NONDATA do not in any circumstances return
1263      * any data via ide_atapi_cmd_reply. These commands are exempt from
1264      * the normal byte_count_limit constraints.
1265      * See ATA8-ACS3 "7.21.5 Byte Count Limit"
1266      */
1267     NONDATA = 0x04,
1268 
1269     /*
1270      * CONDDATA implies a command that transfers data only conditionally based
1271      * on the presence of suboptions. It should be exempt from the BCL check at
1272      * command validation time, but it needs to be checked at the command
1273      * handler level instead.
1274      */
1275     CONDDATA = 0x08,
1276 };
1277 
1278 static const struct AtapiCmd {
1279     void (*handler)(IDEState *s, uint8_t *buf);
1280     int flags;
1281 } atapi_cmd_table[0x100] = {
1282     [ 0x00 ] = { cmd_test_unit_ready,               CHECK_READY | NONDATA },
1283     [ 0x03 ] = { cmd_request_sense,                 ALLOW_UA },
1284     [ 0x12 ] = { cmd_inquiry,                       ALLOW_UA },
1285     [ 0x1b ] = { cmd_start_stop_unit,               NONDATA }, /* [1] */
1286     [ 0x1e ] = { cmd_prevent_allow_medium_removal,  NONDATA },
1287     [ 0x25 ] = { cmd_read_cdvd_capacity,            CHECK_READY },
1288     [ 0x28 ] = { cmd_read, /* (10) */               CHECK_READY },
1289     [ 0x2b ] = { cmd_seek,                          CHECK_READY | NONDATA },
1290     [ 0x43 ] = { cmd_read_toc_pma_atip,             CHECK_READY },
1291     [ 0x46 ] = { cmd_get_configuration,             ALLOW_UA },
1292     [ 0x4a ] = { cmd_get_event_status_notification, ALLOW_UA },
1293     [ 0x51 ] = { cmd_read_disc_information,         CHECK_READY },
1294     [ 0x5a ] = { cmd_mode_sense, /* (10) */         0 },
1295     [ 0xa8 ] = { cmd_read, /* (12) */               CHECK_READY },
1296     [ 0xad ] = { cmd_read_dvd_structure,            CHECK_READY },
1297     [ 0xbb ] = { cmd_set_speed,                     NONDATA },
1298     [ 0xbd ] = { cmd_mechanism_status,              0 },
1299     [ 0xbe ] = { cmd_read_cd,                       CHECK_READY | CONDDATA },
1300     /* [1] handler detects and reports not ready condition itself */
1301 };
1302 
1303 void ide_atapi_cmd(IDEState *s)
1304 {
1305     uint8_t *buf = s->io_buffer;
1306     const struct AtapiCmd *cmd = &atapi_cmd_table[s->io_buffer[0]];
1307 
1308     trace_ide_atapi_cmd(s, s->io_buffer[0]);
1309 
1310     if (trace_event_get_state_backends(TRACE_IDE_ATAPI_CMD_PACKET)) {
1311         /* Each pretty-printed byte needs two bytes and a space; */
1312         char *ppacket = g_malloc(ATAPI_PACKET_SIZE * 3 + 1);
1313         int i;
1314         for (i = 0; i < ATAPI_PACKET_SIZE; i++) {
1315             sprintf(ppacket + (i * 3), "%02x ", buf[i]);
1316         }
1317         trace_ide_atapi_cmd_packet(s, s->lcyl | (s->hcyl << 8), ppacket);
1318         g_free(ppacket);
1319     }
1320 
1321     /*
1322      * If there's a UNIT_ATTENTION condition pending, only command flagged with
1323      * ALLOW_UA are allowed to complete. with other commands getting a CHECK
1324      * condition response unless a higher priority status, defined by the drive
1325      * here, is pending.
1326      */
1327     if (s->sense_key == UNIT_ATTENTION && !(cmd->flags & ALLOW_UA)) {
1328         ide_atapi_cmd_check_status(s);
1329         return;
1330     }
1331     /*
1332      * When a CD gets changed, we have to report an ejected state and
1333      * then a loaded state to guests so that they detect tray
1334      * open/close and media change events.  Guests that do not use
1335      * GET_EVENT_STATUS_NOTIFICATION to detect such tray open/close
1336      * states rely on this behavior.
1337      */
1338     if (!(cmd->flags & ALLOW_UA) &&
1339         !s->tray_open && blk_is_inserted(s->blk) && s->cdrom_changed) {
1340 
1341         if (s->cdrom_changed == 1) {
1342             ide_atapi_cmd_error(s, NOT_READY, ASC_MEDIUM_NOT_PRESENT);
1343             s->cdrom_changed = 2;
1344         } else {
1345             ide_atapi_cmd_error(s, UNIT_ATTENTION, ASC_MEDIUM_MAY_HAVE_CHANGED);
1346             s->cdrom_changed = 0;
1347         }
1348 
1349         return;
1350     }
1351 
1352     /* Report a Not Ready condition if appropriate for the command */
1353     if ((cmd->flags & CHECK_READY) &&
1354         (!media_present(s) || !blk_is_inserted(s->blk)))
1355     {
1356         ide_atapi_cmd_error(s, NOT_READY, ASC_MEDIUM_NOT_PRESENT);
1357         return;
1358     }
1359 
1360     /* Commands that don't transfer DATA permit the byte_count_limit to be 0.
1361      * If this is a data-transferring PIO command and BCL is 0,
1362      * we abort at the /ATA/ level, not the ATAPI level.
1363      * See ATA8 ACS3 section 7.17.6.49 and 7.21.5 */
1364     if (cmd->handler && !(cmd->flags & (NONDATA | CONDDATA))) {
1365         if (!validate_bcl(s)) {
1366             return;
1367         }
1368     }
1369 
1370     /* Execute the command */
1371     if (cmd->handler) {
1372         cmd->handler(s, buf);
1373         return;
1374     }
1375 
1376     ide_atapi_cmd_error(s, ILLEGAL_REQUEST, ASC_ILLEGAL_OPCODE);
1377 }
1378