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