xref: /openbmc/qemu/hw/scsi/scsi-bus.c (revision 2993683b)
1 #include "hw/hw.h"
2 #include "qemu/error-report.h"
3 #include "hw/scsi/scsi.h"
4 #include "block/scsi.h"
5 #include "hw/qdev.h"
6 #include "sysemu/blockdev.h"
7 #include "trace.h"
8 #include "sysemu/dma.h"
9 
10 static char *scsibus_get_dev_path(DeviceState *dev);
11 static char *scsibus_get_fw_dev_path(DeviceState *dev);
12 static int scsi_req_parse(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf);
13 static void scsi_req_dequeue(SCSIRequest *req);
14 
15 static Property scsi_props[] = {
16     DEFINE_PROP_UINT32("channel", SCSIDevice, channel, 0),
17     DEFINE_PROP_UINT32("scsi-id", SCSIDevice, id, -1),
18     DEFINE_PROP_UINT32("lun", SCSIDevice, lun, -1),
19     DEFINE_PROP_END_OF_LIST(),
20 };
21 
22 static void scsi_bus_class_init(ObjectClass *klass, void *data)
23 {
24     BusClass *k = BUS_CLASS(klass);
25 
26     k->get_dev_path = scsibus_get_dev_path;
27     k->get_fw_dev_path = scsibus_get_fw_dev_path;
28 }
29 
30 static const TypeInfo scsi_bus_info = {
31     .name = TYPE_SCSI_BUS,
32     .parent = TYPE_BUS,
33     .instance_size = sizeof(SCSIBus),
34     .class_init = scsi_bus_class_init,
35 };
36 static int next_scsi_bus;
37 
38 static int scsi_device_init(SCSIDevice *s)
39 {
40     SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(s);
41     if (sc->init) {
42         return sc->init(s);
43     }
44     return 0;
45 }
46 
47 static void scsi_device_destroy(SCSIDevice *s)
48 {
49     SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(s);
50     if (sc->destroy) {
51         sc->destroy(s);
52     }
53 }
54 
55 static SCSIRequest *scsi_device_alloc_req(SCSIDevice *s, uint32_t tag, uint32_t lun,
56                                           uint8_t *buf, void *hba_private)
57 {
58     SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(s);
59     if (sc->alloc_req) {
60         return sc->alloc_req(s, tag, lun, buf, hba_private);
61     }
62 
63     return NULL;
64 }
65 
66 static void scsi_device_unit_attention_reported(SCSIDevice *s)
67 {
68     SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(s);
69     if (sc->unit_attention_reported) {
70         sc->unit_attention_reported(s);
71     }
72 }
73 
74 /* Create a scsi bus, and attach devices to it.  */
75 void scsi_bus_new(SCSIBus *bus, DeviceState *host, const SCSIBusInfo *info)
76 {
77     qbus_create_inplace(&bus->qbus, TYPE_SCSI_BUS, host, NULL);
78     bus->busnr = next_scsi_bus++;
79     bus->info = info;
80     bus->qbus.allow_hotplug = 1;
81 }
82 
83 static void scsi_dma_restart_bh(void *opaque)
84 {
85     SCSIDevice *s = opaque;
86     SCSIRequest *req, *next;
87 
88     qemu_bh_delete(s->bh);
89     s->bh = NULL;
90 
91     QTAILQ_FOREACH_SAFE(req, &s->requests, next, next) {
92         scsi_req_ref(req);
93         if (req->retry) {
94             req->retry = false;
95             switch (req->cmd.mode) {
96             case SCSI_XFER_FROM_DEV:
97             case SCSI_XFER_TO_DEV:
98                 scsi_req_continue(req);
99                 break;
100             case SCSI_XFER_NONE:
101                 assert(!req->sg);
102                 scsi_req_dequeue(req);
103                 scsi_req_enqueue(req);
104                 break;
105             }
106         }
107         scsi_req_unref(req);
108     }
109 }
110 
111 void scsi_req_retry(SCSIRequest *req)
112 {
113     /* No need to save a reference, because scsi_dma_restart_bh just
114      * looks at the request list.  */
115     req->retry = true;
116 }
117 
118 static void scsi_dma_restart_cb(void *opaque, int running, RunState state)
119 {
120     SCSIDevice *s = opaque;
121 
122     if (!running) {
123         return;
124     }
125     if (!s->bh) {
126         s->bh = qemu_bh_new(scsi_dma_restart_bh, s);
127         qemu_bh_schedule(s->bh);
128     }
129 }
130 
131 static int scsi_qdev_init(DeviceState *qdev)
132 {
133     SCSIDevice *dev = SCSI_DEVICE(qdev);
134     SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus);
135     SCSIDevice *d;
136     int rc = -1;
137 
138     if (dev->channel > bus->info->max_channel) {
139         error_report("bad scsi channel id: %d", dev->channel);
140         goto err;
141     }
142     if (dev->id != -1 && dev->id > bus->info->max_target) {
143         error_report("bad scsi device id: %d", dev->id);
144         goto err;
145     }
146     if (dev->lun != -1 && dev->lun > bus->info->max_lun) {
147         error_report("bad scsi device lun: %d", dev->lun);
148         goto err;
149     }
150 
151     if (dev->id == -1) {
152         int id = -1;
153         if (dev->lun == -1) {
154             dev->lun = 0;
155         }
156         do {
157             d = scsi_device_find(bus, dev->channel, ++id, dev->lun);
158         } while (d && d->lun == dev->lun && id < bus->info->max_target);
159         if (d && d->lun == dev->lun) {
160             error_report("no free target");
161             goto err;
162         }
163         dev->id = id;
164     } else if (dev->lun == -1) {
165         int lun = -1;
166         do {
167             d = scsi_device_find(bus, dev->channel, dev->id, ++lun);
168         } while (d && d->lun == lun && lun < bus->info->max_lun);
169         if (d && d->lun == lun) {
170             error_report("no free lun");
171             goto err;
172         }
173         dev->lun = lun;
174     } else {
175         d = scsi_device_find(bus, dev->channel, dev->id, dev->lun);
176         assert(d);
177         if (d->lun == dev->lun && dev != d) {
178             qdev_free(&d->qdev);
179         }
180     }
181 
182     QTAILQ_INIT(&dev->requests);
183     rc = scsi_device_init(dev);
184     if (rc == 0) {
185         dev->vmsentry = qemu_add_vm_change_state_handler(scsi_dma_restart_cb,
186                                                          dev);
187     }
188 
189     if (bus->info->hotplug) {
190         bus->info->hotplug(bus, dev);
191     }
192 
193 err:
194     return rc;
195 }
196 
197 static int scsi_qdev_exit(DeviceState *qdev)
198 {
199     SCSIDevice *dev = SCSI_DEVICE(qdev);
200 
201     if (dev->vmsentry) {
202         qemu_del_vm_change_state_handler(dev->vmsentry);
203     }
204     scsi_device_destroy(dev);
205     return 0;
206 }
207 
208 /* handle legacy '-drive if=scsi,...' cmd line args */
209 SCSIDevice *scsi_bus_legacy_add_drive(SCSIBus *bus, BlockDriverState *bdrv,
210                                       int unit, bool removable, int bootindex,
211                                       const char *serial)
212 {
213     const char *driver;
214     DeviceState *dev;
215 
216     driver = bdrv_is_sg(bdrv) ? "scsi-generic" : "scsi-disk";
217     dev = qdev_create(&bus->qbus, driver);
218     qdev_prop_set_uint32(dev, "scsi-id", unit);
219     if (bootindex >= 0) {
220         qdev_prop_set_int32(dev, "bootindex", bootindex);
221     }
222     if (object_property_find(OBJECT(dev), "removable", NULL)) {
223         qdev_prop_set_bit(dev, "removable", removable);
224     }
225     if (serial) {
226         qdev_prop_set_string(dev, "serial", serial);
227     }
228     if (qdev_prop_set_drive(dev, "drive", bdrv) < 0) {
229         qdev_free(dev);
230         return NULL;
231     }
232     if (qdev_init(dev) < 0)
233         return NULL;
234     return SCSI_DEVICE(dev);
235 }
236 
237 int scsi_bus_legacy_handle_cmdline(SCSIBus *bus)
238 {
239     Location loc;
240     DriveInfo *dinfo;
241     int res = 0, unit;
242 
243     loc_push_none(&loc);
244     for (unit = 0; unit <= bus->info->max_target; unit++) {
245         dinfo = drive_get(IF_SCSI, bus->busnr, unit);
246         if (dinfo == NULL) {
247             continue;
248         }
249         qemu_opts_loc_restore(dinfo->opts);
250         if (!scsi_bus_legacy_add_drive(bus, dinfo->bdrv, unit, false, -1, NULL)) {
251             res = -1;
252             break;
253         }
254     }
255     loc_pop(&loc);
256     return res;
257 }
258 
259 static int32_t scsi_invalid_field(SCSIRequest *req, uint8_t *buf)
260 {
261     scsi_req_build_sense(req, SENSE_CODE(INVALID_FIELD));
262     scsi_req_complete(req, CHECK_CONDITION);
263     return 0;
264 }
265 
266 static const struct SCSIReqOps reqops_invalid_field = {
267     .size         = sizeof(SCSIRequest),
268     .send_command = scsi_invalid_field
269 };
270 
271 /* SCSIReqOps implementation for invalid commands.  */
272 
273 static int32_t scsi_invalid_command(SCSIRequest *req, uint8_t *buf)
274 {
275     scsi_req_build_sense(req, SENSE_CODE(INVALID_OPCODE));
276     scsi_req_complete(req, CHECK_CONDITION);
277     return 0;
278 }
279 
280 static const struct SCSIReqOps reqops_invalid_opcode = {
281     .size         = sizeof(SCSIRequest),
282     .send_command = scsi_invalid_command
283 };
284 
285 /* SCSIReqOps implementation for unit attention conditions.  */
286 
287 static int32_t scsi_unit_attention(SCSIRequest *req, uint8_t *buf)
288 {
289     if (req->dev->unit_attention.key == UNIT_ATTENTION) {
290         scsi_req_build_sense(req, req->dev->unit_attention);
291     } else if (req->bus->unit_attention.key == UNIT_ATTENTION) {
292         scsi_req_build_sense(req, req->bus->unit_attention);
293     }
294     scsi_req_complete(req, CHECK_CONDITION);
295     return 0;
296 }
297 
298 static const struct SCSIReqOps reqops_unit_attention = {
299     .size         = sizeof(SCSIRequest),
300     .send_command = scsi_unit_attention
301 };
302 
303 /* SCSIReqOps implementation for REPORT LUNS and for commands sent to
304    an invalid LUN.  */
305 
306 typedef struct SCSITargetReq SCSITargetReq;
307 
308 struct SCSITargetReq {
309     SCSIRequest req;
310     int len;
311     uint8_t buf[2056];
312 };
313 
314 static void store_lun(uint8_t *outbuf, int lun)
315 {
316     if (lun < 256) {
317         outbuf[1] = lun;
318         return;
319     }
320     outbuf[1] = (lun & 255);
321     outbuf[0] = (lun >> 8) | 0x40;
322 }
323 
324 static bool scsi_target_emulate_report_luns(SCSITargetReq *r)
325 {
326     BusChild *kid;
327     int i, len, n;
328     int channel, id;
329     bool found_lun0;
330 
331     if (r->req.cmd.xfer < 16) {
332         return false;
333     }
334     if (r->req.cmd.buf[2] > 2) {
335         return false;
336     }
337     channel = r->req.dev->channel;
338     id = r->req.dev->id;
339     found_lun0 = false;
340     n = 0;
341     QTAILQ_FOREACH(kid, &r->req.bus->qbus.children, sibling) {
342         DeviceState *qdev = kid->child;
343         SCSIDevice *dev = SCSI_DEVICE(qdev);
344 
345         if (dev->channel == channel && dev->id == id) {
346             if (dev->lun == 0) {
347                 found_lun0 = true;
348             }
349             n += 8;
350         }
351     }
352     if (!found_lun0) {
353         n += 8;
354     }
355     len = MIN(n + 8, r->req.cmd.xfer & ~7);
356     if (len > sizeof(r->buf)) {
357         /* TODO: > 256 LUNs? */
358         return false;
359     }
360 
361     memset(r->buf, 0, len);
362     stl_be_p(&r->buf, n);
363     i = found_lun0 ? 8 : 16;
364     QTAILQ_FOREACH(kid, &r->req.bus->qbus.children, sibling) {
365         DeviceState *qdev = kid->child;
366         SCSIDevice *dev = SCSI_DEVICE(qdev);
367 
368         if (dev->channel == channel && dev->id == id) {
369             store_lun(&r->buf[i], dev->lun);
370             i += 8;
371         }
372     }
373     assert(i == n + 8);
374     r->len = len;
375     return true;
376 }
377 
378 static bool scsi_target_emulate_inquiry(SCSITargetReq *r)
379 {
380     assert(r->req.dev->lun != r->req.lun);
381     if (r->req.cmd.buf[1] & 0x2) {
382         /* Command support data - optional, not implemented */
383         return false;
384     }
385 
386     if (r->req.cmd.buf[1] & 0x1) {
387         /* Vital product data */
388         uint8_t page_code = r->req.cmd.buf[2];
389         r->buf[r->len++] = page_code ; /* this page */
390         r->buf[r->len++] = 0x00;
391 
392         switch (page_code) {
393         case 0x00: /* Supported page codes, mandatory */
394         {
395             int pages;
396             pages = r->len++;
397             r->buf[r->len++] = 0x00; /* list of supported pages (this page) */
398             r->buf[pages] = r->len - pages - 1; /* number of pages */
399             break;
400         }
401         default:
402             return false;
403         }
404         /* done with EVPD */
405         assert(r->len < sizeof(r->buf));
406         r->len = MIN(r->req.cmd.xfer, r->len);
407         return true;
408     }
409 
410     /* Standard INQUIRY data */
411     if (r->req.cmd.buf[2] != 0) {
412         return false;
413     }
414 
415     /* PAGE CODE == 0 */
416     r->len = MIN(r->req.cmd.xfer, 36);
417     memset(r->buf, 0, r->len);
418     if (r->req.lun != 0) {
419         r->buf[0] = TYPE_NO_LUN;
420     } else {
421         r->buf[0] = TYPE_NOT_PRESENT | TYPE_INACTIVE;
422         r->buf[2] = 5; /* Version */
423         r->buf[3] = 2 | 0x10; /* HiSup, response data format */
424         r->buf[4] = r->len - 5; /* Additional Length = (Len - 1) - 4 */
425         r->buf[7] = 0x10 | (r->req.bus->info->tcq ? 0x02 : 0); /* Sync, TCQ.  */
426         memcpy(&r->buf[8], "QEMU    ", 8);
427         memcpy(&r->buf[16], "QEMU TARGET     ", 16);
428         pstrcpy((char *) &r->buf[32], 4, qemu_get_version());
429     }
430     return true;
431 }
432 
433 static int32_t scsi_target_send_command(SCSIRequest *req, uint8_t *buf)
434 {
435     SCSITargetReq *r = DO_UPCAST(SCSITargetReq, req, req);
436 
437     switch (buf[0]) {
438     case REPORT_LUNS:
439         if (!scsi_target_emulate_report_luns(r)) {
440             goto illegal_request;
441         }
442         break;
443     case INQUIRY:
444         if (!scsi_target_emulate_inquiry(r)) {
445             goto illegal_request;
446         }
447         break;
448     case REQUEST_SENSE:
449         r->len = scsi_device_get_sense(r->req.dev, r->buf,
450                                        MIN(req->cmd.xfer, sizeof r->buf),
451                                        (req->cmd.buf[1] & 1) == 0);
452         if (r->req.dev->sense_is_ua) {
453             scsi_device_unit_attention_reported(req->dev);
454             r->req.dev->sense_len = 0;
455             r->req.dev->sense_is_ua = false;
456         }
457         break;
458     default:
459         scsi_req_build_sense(req, SENSE_CODE(LUN_NOT_SUPPORTED));
460         scsi_req_complete(req, CHECK_CONDITION);
461         return 0;
462     illegal_request:
463         scsi_req_build_sense(req, SENSE_CODE(INVALID_FIELD));
464         scsi_req_complete(req, CHECK_CONDITION);
465         return 0;
466     }
467 
468     if (!r->len) {
469         scsi_req_complete(req, GOOD);
470     }
471     return r->len;
472 }
473 
474 static void scsi_target_read_data(SCSIRequest *req)
475 {
476     SCSITargetReq *r = DO_UPCAST(SCSITargetReq, req, req);
477     uint32_t n;
478 
479     n = r->len;
480     if (n > 0) {
481         r->len = 0;
482         scsi_req_data(&r->req, n);
483     } else {
484         scsi_req_complete(&r->req, GOOD);
485     }
486 }
487 
488 static uint8_t *scsi_target_get_buf(SCSIRequest *req)
489 {
490     SCSITargetReq *r = DO_UPCAST(SCSITargetReq, req, req);
491 
492     return r->buf;
493 }
494 
495 static const struct SCSIReqOps reqops_target_command = {
496     .size         = sizeof(SCSITargetReq),
497     .send_command = scsi_target_send_command,
498     .read_data    = scsi_target_read_data,
499     .get_buf      = scsi_target_get_buf,
500 };
501 
502 
503 SCSIRequest *scsi_req_alloc(const SCSIReqOps *reqops, SCSIDevice *d,
504                             uint32_t tag, uint32_t lun, void *hba_private)
505 {
506     SCSIRequest *req;
507 
508     req = g_malloc0(reqops->size);
509     req->refcount = 1;
510     req->bus = scsi_bus_from_device(d);
511     req->dev = d;
512     req->tag = tag;
513     req->lun = lun;
514     req->hba_private = hba_private;
515     req->status = -1;
516     req->sense_len = 0;
517     req->ops = reqops;
518     trace_scsi_req_alloc(req->dev->id, req->lun, req->tag);
519     return req;
520 }
521 
522 SCSIRequest *scsi_req_new(SCSIDevice *d, uint32_t tag, uint32_t lun,
523                           uint8_t *buf, void *hba_private)
524 {
525     SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, d->qdev.parent_bus);
526     SCSIRequest *req;
527     SCSICommand cmd;
528 
529     if (scsi_req_parse(&cmd, d, buf) != 0) {
530         trace_scsi_req_parse_bad(d->id, lun, tag, buf[0]);
531         req = scsi_req_alloc(&reqops_invalid_opcode, d, tag, lun, hba_private);
532     } else {
533         trace_scsi_req_parsed(d->id, lun, tag, buf[0],
534                               cmd.mode, cmd.xfer);
535         if (cmd.lba != -1) {
536             trace_scsi_req_parsed_lba(d->id, lun, tag, buf[0],
537                                       cmd.lba);
538         }
539 
540         if (cmd.xfer > INT32_MAX) {
541             req = scsi_req_alloc(&reqops_invalid_field, d, tag, lun, hba_private);
542         } else if ((d->unit_attention.key == UNIT_ATTENTION ||
543                    bus->unit_attention.key == UNIT_ATTENTION) &&
544                   (buf[0] != INQUIRY &&
545                    buf[0] != REPORT_LUNS &&
546                    buf[0] != GET_CONFIGURATION &&
547                    buf[0] != GET_EVENT_STATUS_NOTIFICATION &&
548 
549                    /*
550                     * If we already have a pending unit attention condition,
551                     * report this one before triggering another one.
552                     */
553                    !(buf[0] == REQUEST_SENSE && d->sense_is_ua))) {
554             req = scsi_req_alloc(&reqops_unit_attention, d, tag, lun,
555                                  hba_private);
556         } else if (lun != d->lun ||
557                    buf[0] == REPORT_LUNS ||
558                    (buf[0] == REQUEST_SENSE && d->sense_len)) {
559             req = scsi_req_alloc(&reqops_target_command, d, tag, lun,
560                                  hba_private);
561         } else {
562             req = scsi_device_alloc_req(d, tag, lun, buf, hba_private);
563         }
564     }
565 
566     req->cmd = cmd;
567     req->resid = req->cmd.xfer;
568 
569     switch (buf[0]) {
570     case INQUIRY:
571         trace_scsi_inquiry(d->id, lun, tag, cmd.buf[1], cmd.buf[2]);
572         break;
573     case TEST_UNIT_READY:
574         trace_scsi_test_unit_ready(d->id, lun, tag);
575         break;
576     case REPORT_LUNS:
577         trace_scsi_report_luns(d->id, lun, tag);
578         break;
579     case REQUEST_SENSE:
580         trace_scsi_request_sense(d->id, lun, tag);
581         break;
582     default:
583         break;
584     }
585 
586     return req;
587 }
588 
589 uint8_t *scsi_req_get_buf(SCSIRequest *req)
590 {
591     return req->ops->get_buf(req);
592 }
593 
594 static void scsi_clear_unit_attention(SCSIRequest *req)
595 {
596     SCSISense *ua;
597     if (req->dev->unit_attention.key != UNIT_ATTENTION &&
598         req->bus->unit_attention.key != UNIT_ATTENTION) {
599         return;
600     }
601 
602     /*
603      * If an INQUIRY command enters the enabled command state,
604      * the device server shall [not] clear any unit attention condition;
605      * See also MMC-6, paragraphs 6.5 and 6.6.2.
606      */
607     if (req->cmd.buf[0] == INQUIRY ||
608         req->cmd.buf[0] == GET_CONFIGURATION ||
609         req->cmd.buf[0] == GET_EVENT_STATUS_NOTIFICATION) {
610         return;
611     }
612 
613     if (req->dev->unit_attention.key == UNIT_ATTENTION) {
614         ua = &req->dev->unit_attention;
615     } else {
616         ua = &req->bus->unit_attention;
617     }
618 
619     /*
620      * If a REPORT LUNS command enters the enabled command state, [...]
621      * the device server shall clear any pending unit attention condition
622      * with an additional sense code of REPORTED LUNS DATA HAS CHANGED.
623      */
624     if (req->cmd.buf[0] == REPORT_LUNS &&
625         !(ua->asc == SENSE_CODE(REPORTED_LUNS_CHANGED).asc &&
626           ua->ascq == SENSE_CODE(REPORTED_LUNS_CHANGED).ascq)) {
627         return;
628     }
629 
630     *ua = SENSE_CODE(NO_SENSE);
631 }
632 
633 int scsi_req_get_sense(SCSIRequest *req, uint8_t *buf, int len)
634 {
635     int ret;
636 
637     assert(len >= 14);
638     if (!req->sense_len) {
639         return 0;
640     }
641 
642     ret = scsi_build_sense(req->sense, req->sense_len, buf, len, true);
643 
644     /*
645      * FIXME: clearing unit attention conditions upon autosense should be done
646      * only if the UA_INTLCK_CTRL field in the Control mode page is set to 00b
647      * (SAM-5, 5.14).
648      *
649      * We assume UA_INTLCK_CTRL to be 00b for HBAs that support autosense, and
650      * 10b for HBAs that do not support it (do not call scsi_req_get_sense).
651      * Here we handle unit attention clearing for UA_INTLCK_CTRL == 00b.
652      */
653     if (req->dev->sense_is_ua) {
654         scsi_device_unit_attention_reported(req->dev);
655         req->dev->sense_len = 0;
656         req->dev->sense_is_ua = false;
657     }
658     return ret;
659 }
660 
661 int scsi_device_get_sense(SCSIDevice *dev, uint8_t *buf, int len, bool fixed)
662 {
663     return scsi_build_sense(dev->sense, dev->sense_len, buf, len, fixed);
664 }
665 
666 void scsi_req_build_sense(SCSIRequest *req, SCSISense sense)
667 {
668     trace_scsi_req_build_sense(req->dev->id, req->lun, req->tag,
669                                sense.key, sense.asc, sense.ascq);
670     memset(req->sense, 0, 18);
671     req->sense[0] = 0x70;
672     req->sense[2] = sense.key;
673     req->sense[7] = 10;
674     req->sense[12] = sense.asc;
675     req->sense[13] = sense.ascq;
676     req->sense_len = 18;
677 }
678 
679 static void scsi_req_enqueue_internal(SCSIRequest *req)
680 {
681     assert(!req->enqueued);
682     scsi_req_ref(req);
683     if (req->bus->info->get_sg_list) {
684         req->sg = req->bus->info->get_sg_list(req);
685     } else {
686         req->sg = NULL;
687     }
688     req->enqueued = true;
689     QTAILQ_INSERT_TAIL(&req->dev->requests, req, next);
690 }
691 
692 int32_t scsi_req_enqueue(SCSIRequest *req)
693 {
694     int32_t rc;
695 
696     assert(!req->retry);
697     scsi_req_enqueue_internal(req);
698     scsi_req_ref(req);
699     rc = req->ops->send_command(req, req->cmd.buf);
700     scsi_req_unref(req);
701     return rc;
702 }
703 
704 static void scsi_req_dequeue(SCSIRequest *req)
705 {
706     trace_scsi_req_dequeue(req->dev->id, req->lun, req->tag);
707     req->retry = false;
708     if (req->enqueued) {
709         QTAILQ_REMOVE(&req->dev->requests, req, next);
710         req->enqueued = false;
711         scsi_req_unref(req);
712     }
713 }
714 
715 static int scsi_get_performance_length(int num_desc, int type, int data_type)
716 {
717     /* MMC-6, paragraph 6.7.  */
718     switch (type) {
719     case 0:
720         if ((data_type & 3) == 0) {
721             /* Each descriptor is as in Table 295 - Nominal performance.  */
722             return 16 * num_desc + 8;
723         } else {
724             /* Each descriptor is as in Table 296 - Exceptions.  */
725             return 6 * num_desc + 8;
726         }
727     case 1:
728     case 4:
729     case 5:
730         return 8 * num_desc + 8;
731     case 2:
732         return 2048 * num_desc + 8;
733     case 3:
734         return 16 * num_desc + 8;
735     default:
736         return 8;
737     }
738 }
739 
740 static int ata_passthrough_xfer_unit(SCSIDevice *dev, uint8_t *buf)
741 {
742     int byte_block = (buf[2] >> 2) & 0x1;
743     int type = (buf[2] >> 4) & 0x1;
744     int xfer_unit;
745 
746     if (byte_block) {
747         if (type) {
748             xfer_unit = dev->blocksize;
749         } else {
750             xfer_unit = 512;
751         }
752     } else {
753         xfer_unit = 1;
754     }
755 
756     return xfer_unit;
757 }
758 
759 static int ata_passthrough_12_xfer_size(SCSIDevice *dev, uint8_t *buf)
760 {
761     int length = buf[2] & 0x3;
762     int xfer;
763     int unit = ata_passthrough_xfer_unit(dev, buf);
764 
765     switch (length) {
766     case 0:
767     case 3: /* USB-specific.  */
768     default:
769         xfer = 0;
770         break;
771     case 1:
772         xfer = buf[3];
773         break;
774     case 2:
775         xfer = buf[4];
776         break;
777     }
778 
779     return xfer * unit;
780 }
781 
782 static int ata_passthrough_16_xfer_size(SCSIDevice *dev, uint8_t *buf)
783 {
784     int extend = buf[1] & 0x1;
785     int length = buf[2] & 0x3;
786     int xfer;
787     int unit = ata_passthrough_xfer_unit(dev, buf);
788 
789     switch (length) {
790     case 0:
791     case 3: /* USB-specific.  */
792     default:
793         xfer = 0;
794         break;
795     case 1:
796         xfer = buf[4];
797         xfer |= (extend ? buf[3] << 8 : 0);
798         break;
799     case 2:
800         xfer = buf[6];
801         xfer |= (extend ? buf[5] << 8 : 0);
802         break;
803     }
804 
805     return xfer * unit;
806 }
807 
808 uint32_t scsi_data_cdb_length(uint8_t *buf)
809 {
810     if ((buf[0] >> 5) == 0 && buf[4] == 0) {
811         return 256;
812     } else {
813         return scsi_cdb_length(buf);
814     }
815 }
816 
817 uint32_t scsi_cdb_length(uint8_t *buf)
818 {
819     switch (buf[0] >> 5) {
820     case 0:
821         return buf[4];
822         break;
823     case 1:
824     case 2:
825         return lduw_be_p(&buf[7]);
826         break;
827     case 4:
828         return ldl_be_p(&buf[10]) & 0xffffffffULL;
829         break;
830     case 5:
831         return ldl_be_p(&buf[6]) & 0xffffffffULL;
832         break;
833     default:
834         return -1;
835     }
836 }
837 
838 static int scsi_req_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
839 {
840     cmd->xfer = scsi_cdb_length(buf);
841     switch (buf[0]) {
842     case TEST_UNIT_READY:
843     case REWIND:
844     case START_STOP:
845     case SET_CAPACITY:
846     case WRITE_FILEMARKS:
847     case WRITE_FILEMARKS_16:
848     case SPACE:
849     case RESERVE:
850     case RELEASE:
851     case ERASE:
852     case ALLOW_MEDIUM_REMOVAL:
853     case VERIFY_10:
854     case SEEK_10:
855     case SYNCHRONIZE_CACHE:
856     case SYNCHRONIZE_CACHE_16:
857     case LOCATE_16:
858     case LOCK_UNLOCK_CACHE:
859     case SET_CD_SPEED:
860     case SET_LIMITS:
861     case WRITE_LONG_10:
862     case UPDATE_BLOCK:
863     case RESERVE_TRACK:
864     case SET_READ_AHEAD:
865     case PRE_FETCH:
866     case PRE_FETCH_16:
867     case ALLOW_OVERWRITE:
868         cmd->xfer = 0;
869         break;
870     case MODE_SENSE:
871         break;
872     case WRITE_SAME_10:
873     case WRITE_SAME_16:
874         cmd->xfer = dev->blocksize;
875         break;
876     case READ_CAPACITY_10:
877         cmd->xfer = 8;
878         break;
879     case READ_BLOCK_LIMITS:
880         cmd->xfer = 6;
881         break;
882     case SEND_VOLUME_TAG:
883         /* GPCMD_SET_STREAMING from multimedia commands.  */
884         if (dev->type == TYPE_ROM) {
885             cmd->xfer = buf[10] | (buf[9] << 8);
886         } else {
887             cmd->xfer = buf[9] | (buf[8] << 8);
888         }
889         break;
890     case WRITE_6:
891         /* length 0 means 256 blocks */
892         if (cmd->xfer == 0) {
893             cmd->xfer = 256;
894         }
895     case WRITE_10:
896     case WRITE_VERIFY_10:
897     case WRITE_12:
898     case WRITE_VERIFY_12:
899     case WRITE_16:
900     case WRITE_VERIFY_16:
901         cmd->xfer *= dev->blocksize;
902         break;
903     case READ_6:
904     case READ_REVERSE:
905         /* length 0 means 256 blocks */
906         if (cmd->xfer == 0) {
907             cmd->xfer = 256;
908         }
909     case READ_10:
910     case RECOVER_BUFFERED_DATA:
911     case READ_12:
912     case READ_16:
913         cmd->xfer *= dev->blocksize;
914         break;
915     case FORMAT_UNIT:
916         /* MMC mandates the parameter list to be 12-bytes long.  Parameters
917          * for block devices are restricted to the header right now.  */
918         if (dev->type == TYPE_ROM && (buf[1] & 16)) {
919             cmd->xfer = 12;
920         } else {
921             cmd->xfer = (buf[1] & 16) == 0 ? 0 : (buf[1] & 32 ? 8 : 4);
922         }
923         break;
924     case INQUIRY:
925     case RECEIVE_DIAGNOSTIC:
926     case SEND_DIAGNOSTIC:
927         cmd->xfer = buf[4] | (buf[3] << 8);
928         break;
929     case READ_CD:
930     case READ_BUFFER:
931     case WRITE_BUFFER:
932     case SEND_CUE_SHEET:
933         cmd->xfer = buf[8] | (buf[7] << 8) | (buf[6] << 16);
934         break;
935     case PERSISTENT_RESERVE_OUT:
936         cmd->xfer = ldl_be_p(&buf[5]) & 0xffffffffULL;
937         break;
938     case ERASE_12:
939         if (dev->type == TYPE_ROM) {
940             /* MMC command GET PERFORMANCE.  */
941             cmd->xfer = scsi_get_performance_length(buf[9] | (buf[8] << 8),
942                                                     buf[10], buf[1] & 0x1f);
943         }
944         break;
945     case MECHANISM_STATUS:
946     case READ_DVD_STRUCTURE:
947     case SEND_DVD_STRUCTURE:
948     case MAINTENANCE_OUT:
949     case MAINTENANCE_IN:
950         if (dev->type == TYPE_ROM) {
951             /* GPCMD_REPORT_KEY and GPCMD_SEND_KEY from multi media commands */
952             cmd->xfer = buf[9] | (buf[8] << 8);
953         }
954         break;
955     case ATA_PASSTHROUGH_12:
956         if (dev->type == TYPE_ROM) {
957             /* BLANK command of MMC */
958             cmd->xfer = 0;
959         } else {
960             cmd->xfer = ata_passthrough_12_xfer_size(dev, buf);
961         }
962         break;
963     case ATA_PASSTHROUGH_16:
964         cmd->xfer = ata_passthrough_16_xfer_size(dev, buf);
965         break;
966     }
967     return 0;
968 }
969 
970 static int scsi_req_stream_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
971 {
972     switch (buf[0]) {
973     /* stream commands */
974     case ERASE_12:
975     case ERASE_16:
976         cmd->xfer = 0;
977         break;
978     case READ_6:
979     case READ_REVERSE:
980     case RECOVER_BUFFERED_DATA:
981     case WRITE_6:
982         cmd->xfer = buf[4] | (buf[3] << 8) | (buf[2] << 16);
983         if (buf[1] & 0x01) { /* fixed */
984             cmd->xfer *= dev->blocksize;
985         }
986         break;
987     case READ_16:
988     case READ_REVERSE_16:
989     case VERIFY_16:
990     case WRITE_16:
991         cmd->xfer = buf[14] | (buf[13] << 8) | (buf[12] << 16);
992         if (buf[1] & 0x01) { /* fixed */
993             cmd->xfer *= dev->blocksize;
994         }
995         break;
996     case REWIND:
997     case LOAD_UNLOAD:
998         cmd->xfer = 0;
999         break;
1000     case SPACE_16:
1001         cmd->xfer = buf[13] | (buf[12] << 8);
1002         break;
1003     case READ_POSITION:
1004         switch (buf[1] & 0x1f) /* operation code */ {
1005         case SHORT_FORM_BLOCK_ID:
1006         case SHORT_FORM_VENDOR_SPECIFIC:
1007             cmd->xfer = 20;
1008             break;
1009         case LONG_FORM:
1010             cmd->xfer = 32;
1011             break;
1012         case EXTENDED_FORM:
1013             cmd->xfer = buf[8] | (buf[7] << 8);
1014             break;
1015         default:
1016             return -1;
1017         }
1018 
1019         break;
1020     case FORMAT_UNIT:
1021         cmd->xfer = buf[4] | (buf[3] << 8);
1022         break;
1023     /* generic commands */
1024     default:
1025         return scsi_req_length(cmd, dev, buf);
1026     }
1027     return 0;
1028 }
1029 
1030 static int scsi_req_medium_changer_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
1031 {
1032     switch (buf[0]) {
1033     /* medium changer commands */
1034     case EXCHANGE_MEDIUM:
1035     case INITIALIZE_ELEMENT_STATUS:
1036     case INITIALIZE_ELEMENT_STATUS_WITH_RANGE:
1037     case MOVE_MEDIUM:
1038     case POSITION_TO_ELEMENT:
1039         cmd->xfer = 0;
1040         break;
1041     case READ_ELEMENT_STATUS:
1042         cmd->xfer = buf[9] | (buf[8] << 8) | (buf[7] << 16);
1043         break;
1044 
1045     /* generic commands */
1046     default:
1047         return scsi_req_length(cmd, dev, buf);
1048     }
1049     return 0;
1050 }
1051 
1052 
1053 static void scsi_cmd_xfer_mode(SCSICommand *cmd)
1054 {
1055     if (!cmd->xfer) {
1056         cmd->mode = SCSI_XFER_NONE;
1057         return;
1058     }
1059     switch (cmd->buf[0]) {
1060     case WRITE_6:
1061     case WRITE_10:
1062     case WRITE_VERIFY_10:
1063     case WRITE_12:
1064     case WRITE_VERIFY_12:
1065     case WRITE_16:
1066     case WRITE_VERIFY_16:
1067     case COPY:
1068     case COPY_VERIFY:
1069     case COMPARE:
1070     case CHANGE_DEFINITION:
1071     case LOG_SELECT:
1072     case MODE_SELECT:
1073     case MODE_SELECT_10:
1074     case SEND_DIAGNOSTIC:
1075     case WRITE_BUFFER:
1076     case FORMAT_UNIT:
1077     case REASSIGN_BLOCKS:
1078     case SEARCH_EQUAL:
1079     case SEARCH_HIGH:
1080     case SEARCH_LOW:
1081     case UPDATE_BLOCK:
1082     case WRITE_LONG_10:
1083     case WRITE_SAME_10:
1084     case WRITE_SAME_16:
1085     case UNMAP:
1086     case SEARCH_HIGH_12:
1087     case SEARCH_EQUAL_12:
1088     case SEARCH_LOW_12:
1089     case MEDIUM_SCAN:
1090     case SEND_VOLUME_TAG:
1091     case SEND_CUE_SHEET:
1092     case SEND_DVD_STRUCTURE:
1093     case PERSISTENT_RESERVE_OUT:
1094     case MAINTENANCE_OUT:
1095         cmd->mode = SCSI_XFER_TO_DEV;
1096         break;
1097     case ATA_PASSTHROUGH_12:
1098     case ATA_PASSTHROUGH_16:
1099         /* T_DIR */
1100         cmd->mode = (cmd->buf[2] & 0x8) ?
1101                    SCSI_XFER_FROM_DEV : SCSI_XFER_TO_DEV;
1102         break;
1103     default:
1104         cmd->mode = SCSI_XFER_FROM_DEV;
1105         break;
1106     }
1107 }
1108 
1109 static uint64_t scsi_cmd_lba(SCSICommand *cmd)
1110 {
1111     uint8_t *buf = cmd->buf;
1112     uint64_t lba;
1113 
1114     switch (buf[0] >> 5) {
1115     case 0:
1116         lba = ldl_be_p(&buf[0]) & 0x1fffff;
1117         break;
1118     case 1:
1119     case 2:
1120     case 5:
1121         lba = ldl_be_p(&buf[2]) & 0xffffffffULL;
1122         break;
1123     case 4:
1124         lba = ldq_be_p(&buf[2]);
1125         break;
1126     default:
1127         lba = -1;
1128 
1129     }
1130     return lba;
1131 }
1132 
1133 int scsi_req_parse(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
1134 {
1135     int rc;
1136 
1137     switch (buf[0] >> 5) {
1138     case 0:
1139         cmd->len = 6;
1140         break;
1141     case 1:
1142     case 2:
1143         cmd->len = 10;
1144         break;
1145     case 4:
1146         cmd->len = 16;
1147         break;
1148     case 5:
1149         cmd->len = 12;
1150         break;
1151     default:
1152         return -1;
1153     }
1154 
1155     switch (dev->type) {
1156     case TYPE_TAPE:
1157         rc = scsi_req_stream_length(cmd, dev, buf);
1158         break;
1159     case TYPE_MEDIUM_CHANGER:
1160         rc = scsi_req_medium_changer_length(cmd, dev, buf);
1161         break;
1162     default:
1163         rc = scsi_req_length(cmd, dev, buf);
1164         break;
1165     }
1166 
1167     if (rc != 0)
1168         return rc;
1169 
1170     memcpy(cmd->buf, buf, cmd->len);
1171     scsi_cmd_xfer_mode(cmd);
1172     cmd->lba = scsi_cmd_lba(cmd);
1173     return 0;
1174 }
1175 
1176 void scsi_device_report_change(SCSIDevice *dev, SCSISense sense)
1177 {
1178     SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus);
1179 
1180     scsi_device_set_ua(dev, sense);
1181     if (bus->info->change) {
1182         bus->info->change(bus, dev, sense);
1183     }
1184 }
1185 
1186 /*
1187  * Predefined sense codes
1188  */
1189 
1190 /* No sense data available */
1191 const struct SCSISense sense_code_NO_SENSE = {
1192     .key = NO_SENSE , .asc = 0x00 , .ascq = 0x00
1193 };
1194 
1195 /* LUN not ready, Manual intervention required */
1196 const struct SCSISense sense_code_LUN_NOT_READY = {
1197     .key = NOT_READY, .asc = 0x04, .ascq = 0x03
1198 };
1199 
1200 /* LUN not ready, Medium not present */
1201 const struct SCSISense sense_code_NO_MEDIUM = {
1202     .key = NOT_READY, .asc = 0x3a, .ascq = 0x00
1203 };
1204 
1205 /* LUN not ready, medium removal prevented */
1206 const struct SCSISense sense_code_NOT_READY_REMOVAL_PREVENTED = {
1207     .key = NOT_READY, .asc = 0x53, .ascq = 0x02
1208 };
1209 
1210 /* Hardware error, internal target failure */
1211 const struct SCSISense sense_code_TARGET_FAILURE = {
1212     .key = HARDWARE_ERROR, .asc = 0x44, .ascq = 0x00
1213 };
1214 
1215 /* Illegal request, invalid command operation code */
1216 const struct SCSISense sense_code_INVALID_OPCODE = {
1217     .key = ILLEGAL_REQUEST, .asc = 0x20, .ascq = 0x00
1218 };
1219 
1220 /* Illegal request, LBA out of range */
1221 const struct SCSISense sense_code_LBA_OUT_OF_RANGE = {
1222     .key = ILLEGAL_REQUEST, .asc = 0x21, .ascq = 0x00
1223 };
1224 
1225 /* Illegal request, Invalid field in CDB */
1226 const struct SCSISense sense_code_INVALID_FIELD = {
1227     .key = ILLEGAL_REQUEST, .asc = 0x24, .ascq = 0x00
1228 };
1229 
1230 /* Illegal request, Invalid field in parameter list */
1231 const struct SCSISense sense_code_INVALID_PARAM = {
1232     .key = ILLEGAL_REQUEST, .asc = 0x26, .ascq = 0x00
1233 };
1234 
1235 /* Illegal request, Parameter list length error */
1236 const struct SCSISense sense_code_INVALID_PARAM_LEN = {
1237     .key = ILLEGAL_REQUEST, .asc = 0x1a, .ascq = 0x00
1238 };
1239 
1240 /* Illegal request, LUN not supported */
1241 const struct SCSISense sense_code_LUN_NOT_SUPPORTED = {
1242     .key = ILLEGAL_REQUEST, .asc = 0x25, .ascq = 0x00
1243 };
1244 
1245 /* Illegal request, Saving parameters not supported */
1246 const struct SCSISense sense_code_SAVING_PARAMS_NOT_SUPPORTED = {
1247     .key = ILLEGAL_REQUEST, .asc = 0x39, .ascq = 0x00
1248 };
1249 
1250 /* Illegal request, Incompatible medium installed */
1251 const struct SCSISense sense_code_INCOMPATIBLE_FORMAT = {
1252     .key = ILLEGAL_REQUEST, .asc = 0x30, .ascq = 0x00
1253 };
1254 
1255 /* Illegal request, medium removal prevented */
1256 const struct SCSISense sense_code_ILLEGAL_REQ_REMOVAL_PREVENTED = {
1257     .key = ILLEGAL_REQUEST, .asc = 0x53, .ascq = 0x02
1258 };
1259 
1260 /* Command aborted, I/O process terminated */
1261 const struct SCSISense sense_code_IO_ERROR = {
1262     .key = ABORTED_COMMAND, .asc = 0x00, .ascq = 0x06
1263 };
1264 
1265 /* Command aborted, I_T Nexus loss occurred */
1266 const struct SCSISense sense_code_I_T_NEXUS_LOSS = {
1267     .key = ABORTED_COMMAND, .asc = 0x29, .ascq = 0x07
1268 };
1269 
1270 /* Command aborted, Logical Unit failure */
1271 const struct SCSISense sense_code_LUN_FAILURE = {
1272     .key = ABORTED_COMMAND, .asc = 0x3e, .ascq = 0x01
1273 };
1274 
1275 /* Unit attention, Capacity data has changed */
1276 const struct SCSISense sense_code_CAPACITY_CHANGED = {
1277     .key = UNIT_ATTENTION, .asc = 0x2a, .ascq = 0x09
1278 };
1279 
1280 /* Unit attention, Power on, reset or bus device reset occurred */
1281 const struct SCSISense sense_code_RESET = {
1282     .key = UNIT_ATTENTION, .asc = 0x29, .ascq = 0x00
1283 };
1284 
1285 /* Unit attention, No medium */
1286 const struct SCSISense sense_code_UNIT_ATTENTION_NO_MEDIUM = {
1287     .key = UNIT_ATTENTION, .asc = 0x3a, .ascq = 0x00
1288 };
1289 
1290 /* Unit attention, Medium may have changed */
1291 const struct SCSISense sense_code_MEDIUM_CHANGED = {
1292     .key = UNIT_ATTENTION, .asc = 0x28, .ascq = 0x00
1293 };
1294 
1295 /* Unit attention, Reported LUNs data has changed */
1296 const struct SCSISense sense_code_REPORTED_LUNS_CHANGED = {
1297     .key = UNIT_ATTENTION, .asc = 0x3f, .ascq = 0x0e
1298 };
1299 
1300 /* Unit attention, Device internal reset */
1301 const struct SCSISense sense_code_DEVICE_INTERNAL_RESET = {
1302     .key = UNIT_ATTENTION, .asc = 0x29, .ascq = 0x04
1303 };
1304 
1305 /* Data Protection, Write Protected */
1306 const struct SCSISense sense_code_WRITE_PROTECTED = {
1307     .key = DATA_PROTECT, .asc = 0x27, .ascq = 0x00
1308 };
1309 
1310 /*
1311  * scsi_build_sense
1312  *
1313  * Convert between fixed and descriptor sense buffers
1314  */
1315 int scsi_build_sense(uint8_t *in_buf, int in_len,
1316                      uint8_t *buf, int len, bool fixed)
1317 {
1318     bool fixed_in;
1319     SCSISense sense;
1320     if (!fixed && len < 8) {
1321         return 0;
1322     }
1323 
1324     if (in_len == 0) {
1325         sense.key = NO_SENSE;
1326         sense.asc = 0;
1327         sense.ascq = 0;
1328     } else {
1329         fixed_in = (in_buf[0] & 2) == 0;
1330 
1331         if (fixed == fixed_in) {
1332             memcpy(buf, in_buf, MIN(len, in_len));
1333             return MIN(len, in_len);
1334         }
1335 
1336         if (fixed_in) {
1337             sense.key = in_buf[2];
1338             sense.asc = in_buf[12];
1339             sense.ascq = in_buf[13];
1340         } else {
1341             sense.key = in_buf[1];
1342             sense.asc = in_buf[2];
1343             sense.ascq = in_buf[3];
1344         }
1345     }
1346 
1347     memset(buf, 0, len);
1348     if (fixed) {
1349         /* Return fixed format sense buffer */
1350         buf[0] = 0x70;
1351         buf[2] = sense.key;
1352         buf[7] = 10;
1353         buf[12] = sense.asc;
1354         buf[13] = sense.ascq;
1355         return MIN(len, 18);
1356     } else {
1357         /* Return descriptor format sense buffer */
1358         buf[0] = 0x72;
1359         buf[1] = sense.key;
1360         buf[2] = sense.asc;
1361         buf[3] = sense.ascq;
1362         return 8;
1363     }
1364 }
1365 
1366 static const char *scsi_command_name(uint8_t cmd)
1367 {
1368     static const char *names[] = {
1369         [ TEST_UNIT_READY          ] = "TEST_UNIT_READY",
1370         [ REWIND                   ] = "REWIND",
1371         [ REQUEST_SENSE            ] = "REQUEST_SENSE",
1372         [ FORMAT_UNIT              ] = "FORMAT_UNIT",
1373         [ READ_BLOCK_LIMITS        ] = "READ_BLOCK_LIMITS",
1374         [ REASSIGN_BLOCKS          ] = "REASSIGN_BLOCKS/INITIALIZE ELEMENT STATUS",
1375         /* LOAD_UNLOAD and INITIALIZE_ELEMENT_STATUS use the same operation code */
1376         [ READ_6                   ] = "READ_6",
1377         [ WRITE_6                  ] = "WRITE_6",
1378         [ SET_CAPACITY             ] = "SET_CAPACITY",
1379         [ READ_REVERSE             ] = "READ_REVERSE",
1380         [ WRITE_FILEMARKS          ] = "WRITE_FILEMARKS",
1381         [ SPACE                    ] = "SPACE",
1382         [ INQUIRY                  ] = "INQUIRY",
1383         [ RECOVER_BUFFERED_DATA    ] = "RECOVER_BUFFERED_DATA",
1384         [ MAINTENANCE_IN           ] = "MAINTENANCE_IN",
1385         [ MAINTENANCE_OUT          ] = "MAINTENANCE_OUT",
1386         [ MODE_SELECT              ] = "MODE_SELECT",
1387         [ RESERVE                  ] = "RESERVE",
1388         [ RELEASE                  ] = "RELEASE",
1389         [ COPY                     ] = "COPY",
1390         [ ERASE                    ] = "ERASE",
1391         [ MODE_SENSE               ] = "MODE_SENSE",
1392         [ START_STOP               ] = "START_STOP/LOAD_UNLOAD",
1393         /* LOAD_UNLOAD and START_STOP use the same operation code */
1394         [ RECEIVE_DIAGNOSTIC       ] = "RECEIVE_DIAGNOSTIC",
1395         [ SEND_DIAGNOSTIC          ] = "SEND_DIAGNOSTIC",
1396         [ ALLOW_MEDIUM_REMOVAL     ] = "ALLOW_MEDIUM_REMOVAL",
1397         [ READ_CAPACITY_10         ] = "READ_CAPACITY_10",
1398         [ READ_10                  ] = "READ_10",
1399         [ WRITE_10                 ] = "WRITE_10",
1400         [ SEEK_10                  ] = "SEEK_10/POSITION_TO_ELEMENT",
1401         /* SEEK_10 and POSITION_TO_ELEMENT use the same operation code */
1402         [ WRITE_VERIFY_10          ] = "WRITE_VERIFY_10",
1403         [ VERIFY_10                ] = "VERIFY_10",
1404         [ SEARCH_HIGH              ] = "SEARCH_HIGH",
1405         [ SEARCH_EQUAL             ] = "SEARCH_EQUAL",
1406         [ SEARCH_LOW               ] = "SEARCH_LOW",
1407         [ SET_LIMITS               ] = "SET_LIMITS",
1408         [ PRE_FETCH                ] = "PRE_FETCH/READ_POSITION",
1409         /* READ_POSITION and PRE_FETCH use the same operation code */
1410         [ SYNCHRONIZE_CACHE        ] = "SYNCHRONIZE_CACHE",
1411         [ LOCK_UNLOCK_CACHE        ] = "LOCK_UNLOCK_CACHE",
1412         [ READ_DEFECT_DATA         ] = "READ_DEFECT_DATA/INITIALIZE_ELEMENT_STATUS_WITH_RANGE",
1413         /* READ_DEFECT_DATA and INITIALIZE_ELEMENT_STATUS_WITH_RANGE use the same operation code */
1414         [ MEDIUM_SCAN              ] = "MEDIUM_SCAN",
1415         [ COMPARE                  ] = "COMPARE",
1416         [ COPY_VERIFY              ] = "COPY_VERIFY",
1417         [ WRITE_BUFFER             ] = "WRITE_BUFFER",
1418         [ READ_BUFFER              ] = "READ_BUFFER",
1419         [ UPDATE_BLOCK             ] = "UPDATE_BLOCK",
1420         [ READ_LONG_10             ] = "READ_LONG_10",
1421         [ WRITE_LONG_10            ] = "WRITE_LONG_10",
1422         [ CHANGE_DEFINITION        ] = "CHANGE_DEFINITION",
1423         [ WRITE_SAME_10            ] = "WRITE_SAME_10",
1424         [ UNMAP                    ] = "UNMAP",
1425         [ READ_TOC                 ] = "READ_TOC",
1426         [ REPORT_DENSITY_SUPPORT   ] = "REPORT_DENSITY_SUPPORT",
1427         [ SANITIZE                 ] = "SANITIZE",
1428         [ GET_CONFIGURATION        ] = "GET_CONFIGURATION",
1429         [ LOG_SELECT               ] = "LOG_SELECT",
1430         [ LOG_SENSE                ] = "LOG_SENSE",
1431         [ MODE_SELECT_10           ] = "MODE_SELECT_10",
1432         [ RESERVE_10               ] = "RESERVE_10",
1433         [ RELEASE_10               ] = "RELEASE_10",
1434         [ MODE_SENSE_10            ] = "MODE_SENSE_10",
1435         [ PERSISTENT_RESERVE_IN    ] = "PERSISTENT_RESERVE_IN",
1436         [ PERSISTENT_RESERVE_OUT   ] = "PERSISTENT_RESERVE_OUT",
1437         [ WRITE_FILEMARKS_16       ] = "WRITE_FILEMARKS_16",
1438         [ EXTENDED_COPY            ] = "EXTENDED_COPY",
1439         [ ATA_PASSTHROUGH_16       ] = "ATA_PASSTHROUGH_16",
1440         [ ACCESS_CONTROL_IN        ] = "ACCESS_CONTROL_IN",
1441         [ ACCESS_CONTROL_OUT       ] = "ACCESS_CONTROL_OUT",
1442         [ READ_16                  ] = "READ_16",
1443         [ COMPARE_AND_WRITE        ] = "COMPARE_AND_WRITE",
1444         [ WRITE_16                 ] = "WRITE_16",
1445         [ WRITE_VERIFY_16          ] = "WRITE_VERIFY_16",
1446         [ VERIFY_16                ] = "VERIFY_16",
1447         [ PRE_FETCH_16             ] = "PRE_FETCH_16",
1448         [ SYNCHRONIZE_CACHE_16     ] = "SPACE_16/SYNCHRONIZE_CACHE_16",
1449         /* SPACE_16 and SYNCHRONIZE_CACHE_16 use the same operation code */
1450         [ LOCATE_16                ] = "LOCATE_16",
1451         [ WRITE_SAME_16            ] = "ERASE_16/WRITE_SAME_16",
1452         /* ERASE_16 and WRITE_SAME_16 use the same operation code */
1453         [ SERVICE_ACTION_IN_16     ] = "SERVICE_ACTION_IN_16",
1454         [ WRITE_LONG_16            ] = "WRITE_LONG_16",
1455         [ REPORT_LUNS              ] = "REPORT_LUNS",
1456         [ ATA_PASSTHROUGH_12       ] = "BLANK/ATA_PASSTHROUGH_12",
1457         [ MOVE_MEDIUM              ] = "MOVE_MEDIUM",
1458         [ EXCHANGE_MEDIUM          ] = "EXCHANGE MEDIUM",
1459         [ READ_12                  ] = "READ_12",
1460         [ WRITE_12                 ] = "WRITE_12",
1461         [ ERASE_12                 ] = "ERASE_12/GET_PERFORMANCE",
1462         /* ERASE_12 and GET_PERFORMANCE use the same operation code */
1463         [ SERVICE_ACTION_IN_12     ] = "SERVICE_ACTION_IN_12",
1464         [ WRITE_VERIFY_12          ] = "WRITE_VERIFY_12",
1465         [ VERIFY_12                ] = "VERIFY_12",
1466         [ SEARCH_HIGH_12           ] = "SEARCH_HIGH_12",
1467         [ SEARCH_EQUAL_12          ] = "SEARCH_EQUAL_12",
1468         [ SEARCH_LOW_12            ] = "SEARCH_LOW_12",
1469         [ READ_ELEMENT_STATUS      ] = "READ_ELEMENT_STATUS",
1470         [ SEND_VOLUME_TAG          ] = "SEND_VOLUME_TAG/SET_STREAMING",
1471         /* SEND_VOLUME_TAG and SET_STREAMING use the same operation code */
1472         [ READ_CD                  ] = "READ_CD",
1473         [ READ_DEFECT_DATA_12      ] = "READ_DEFECT_DATA_12",
1474         [ READ_DVD_STRUCTURE       ] = "READ_DVD_STRUCTURE",
1475         [ RESERVE_TRACK            ] = "RESERVE_TRACK",
1476         [ SEND_CUE_SHEET           ] = "SEND_CUE_SHEET",
1477         [ SEND_DVD_STRUCTURE       ] = "SEND_DVD_STRUCTURE",
1478         [ SET_CD_SPEED             ] = "SET_CD_SPEED",
1479         [ SET_READ_AHEAD           ] = "SET_READ_AHEAD",
1480         [ ALLOW_OVERWRITE          ] = "ALLOW_OVERWRITE",
1481         [ MECHANISM_STATUS         ] = "MECHANISM_STATUS",
1482     };
1483 
1484     if (cmd >= ARRAY_SIZE(names) || names[cmd] == NULL)
1485         return "*UNKNOWN*";
1486     return names[cmd];
1487 }
1488 
1489 SCSIRequest *scsi_req_ref(SCSIRequest *req)
1490 {
1491     assert(req->refcount > 0);
1492     req->refcount++;
1493     return req;
1494 }
1495 
1496 void scsi_req_unref(SCSIRequest *req)
1497 {
1498     assert(req->refcount > 0);
1499     if (--req->refcount == 0) {
1500         SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, req->dev->qdev.parent_bus);
1501         if (bus->info->free_request && req->hba_private) {
1502             bus->info->free_request(bus, req->hba_private);
1503         }
1504         if (req->ops->free_req) {
1505             req->ops->free_req(req);
1506         }
1507         g_free(req);
1508     }
1509 }
1510 
1511 /* Tell the device that we finished processing this chunk of I/O.  It
1512    will start the next chunk or complete the command.  */
1513 void scsi_req_continue(SCSIRequest *req)
1514 {
1515     if (req->io_canceled) {
1516         trace_scsi_req_continue_canceled(req->dev->id, req->lun, req->tag);
1517         return;
1518     }
1519     trace_scsi_req_continue(req->dev->id, req->lun, req->tag);
1520     if (req->cmd.mode == SCSI_XFER_TO_DEV) {
1521         req->ops->write_data(req);
1522     } else {
1523         req->ops->read_data(req);
1524     }
1525 }
1526 
1527 /* Called by the devices when data is ready for the HBA.  The HBA should
1528    start a DMA operation to read or fill the device's data buffer.
1529    Once it completes, calling scsi_req_continue will restart I/O.  */
1530 void scsi_req_data(SCSIRequest *req, int len)
1531 {
1532     uint8_t *buf;
1533     if (req->io_canceled) {
1534         trace_scsi_req_data_canceled(req->dev->id, req->lun, req->tag, len);
1535         return;
1536     }
1537     trace_scsi_req_data(req->dev->id, req->lun, req->tag, len);
1538     assert(req->cmd.mode != SCSI_XFER_NONE);
1539     if (!req->sg) {
1540         req->resid -= len;
1541         req->bus->info->transfer_data(req, len);
1542         return;
1543     }
1544 
1545     /* If the device calls scsi_req_data and the HBA specified a
1546      * scatter/gather list, the transfer has to happen in a single
1547      * step.  */
1548     assert(!req->dma_started);
1549     req->dma_started = true;
1550 
1551     buf = scsi_req_get_buf(req);
1552     if (req->cmd.mode == SCSI_XFER_FROM_DEV) {
1553         req->resid = dma_buf_read(buf, len, req->sg);
1554     } else {
1555         req->resid = dma_buf_write(buf, len, req->sg);
1556     }
1557     scsi_req_continue(req);
1558 }
1559 
1560 void scsi_req_print(SCSIRequest *req)
1561 {
1562     FILE *fp = stderr;
1563     int i;
1564 
1565     fprintf(fp, "[%s id=%d] %s",
1566             req->dev->qdev.parent_bus->name,
1567             req->dev->id,
1568             scsi_command_name(req->cmd.buf[0]));
1569     for (i = 1; i < req->cmd.len; i++) {
1570         fprintf(fp, " 0x%02x", req->cmd.buf[i]);
1571     }
1572     switch (req->cmd.mode) {
1573     case SCSI_XFER_NONE:
1574         fprintf(fp, " - none\n");
1575         break;
1576     case SCSI_XFER_FROM_DEV:
1577         fprintf(fp, " - from-dev len=%zd\n", req->cmd.xfer);
1578         break;
1579     case SCSI_XFER_TO_DEV:
1580         fprintf(fp, " - to-dev len=%zd\n", req->cmd.xfer);
1581         break;
1582     default:
1583         fprintf(fp, " - Oops\n");
1584         break;
1585     }
1586 }
1587 
1588 void scsi_req_complete(SCSIRequest *req, int status)
1589 {
1590     assert(req->status == -1);
1591     req->status = status;
1592 
1593     assert(req->sense_len <= sizeof(req->sense));
1594     if (status == GOOD) {
1595         req->sense_len = 0;
1596     }
1597 
1598     if (req->sense_len) {
1599         memcpy(req->dev->sense, req->sense, req->sense_len);
1600         req->dev->sense_len = req->sense_len;
1601         req->dev->sense_is_ua = (req->ops == &reqops_unit_attention);
1602     } else {
1603         req->dev->sense_len = 0;
1604         req->dev->sense_is_ua = false;
1605     }
1606 
1607     /*
1608      * Unit attention state is now stored in the device's sense buffer
1609      * if the HBA didn't do autosense.  Clear the pending unit attention
1610      * flags.
1611      */
1612     scsi_clear_unit_attention(req);
1613 
1614     scsi_req_ref(req);
1615     scsi_req_dequeue(req);
1616     req->bus->info->complete(req, req->status, req->resid);
1617     scsi_req_unref(req);
1618 }
1619 
1620 void scsi_req_cancel(SCSIRequest *req)
1621 {
1622     trace_scsi_req_cancel(req->dev->id, req->lun, req->tag);
1623     if (!req->enqueued) {
1624         return;
1625     }
1626     scsi_req_ref(req);
1627     scsi_req_dequeue(req);
1628     req->io_canceled = true;
1629     if (req->ops->cancel_io) {
1630         req->ops->cancel_io(req);
1631     }
1632     if (req->bus->info->cancel) {
1633         req->bus->info->cancel(req);
1634     }
1635     scsi_req_unref(req);
1636 }
1637 
1638 void scsi_req_abort(SCSIRequest *req, int status)
1639 {
1640     if (!req->enqueued) {
1641         return;
1642     }
1643     scsi_req_ref(req);
1644     scsi_req_dequeue(req);
1645     req->io_canceled = true;
1646     if (req->ops->cancel_io) {
1647         req->ops->cancel_io(req);
1648     }
1649     scsi_req_complete(req, status);
1650     scsi_req_unref(req);
1651 }
1652 
1653 static int scsi_ua_precedence(SCSISense sense)
1654 {
1655     if (sense.key != UNIT_ATTENTION) {
1656         return INT_MAX;
1657     }
1658     if (sense.asc == 0x29 && sense.ascq == 0x04) {
1659         /* DEVICE INTERNAL RESET goes with POWER ON OCCURRED */
1660         return 1;
1661     } else if (sense.asc == 0x3F && sense.ascq == 0x01) {
1662         /* MICROCODE HAS BEEN CHANGED goes with SCSI BUS RESET OCCURRED */
1663         return 2;
1664     } else if (sense.asc == 0x29 && (sense.ascq == 0x05 || sense.ascq == 0x06)) {
1665         /* These two go with "all others". */
1666         ;
1667     } else if (sense.asc == 0x29 && sense.ascq <= 0x07) {
1668         /* POWER ON, RESET OR BUS DEVICE RESET OCCURRED = 0
1669          * POWER ON OCCURRED = 1
1670          * SCSI BUS RESET OCCURRED = 2
1671          * BUS DEVICE RESET FUNCTION OCCURRED = 3
1672          * I_T NEXUS LOSS OCCURRED = 7
1673          */
1674         return sense.ascq;
1675     } else if (sense.asc == 0x2F && sense.ascq == 0x01) {
1676         /* COMMANDS CLEARED BY POWER LOSS NOTIFICATION  */
1677         return 8;
1678     }
1679     return (sense.asc << 8) | sense.ascq;
1680 }
1681 
1682 void scsi_device_set_ua(SCSIDevice *sdev, SCSISense sense)
1683 {
1684     int prec1, prec2;
1685     if (sense.key != UNIT_ATTENTION) {
1686         return;
1687     }
1688     trace_scsi_device_set_ua(sdev->id, sdev->lun, sense.key,
1689                              sense.asc, sense.ascq);
1690 
1691     /*
1692      * Override a pre-existing unit attention condition, except for a more
1693      * important reset condition.
1694     */
1695     prec1 = scsi_ua_precedence(sdev->unit_attention);
1696     prec2 = scsi_ua_precedence(sense);
1697     if (prec2 < prec1) {
1698         sdev->unit_attention = sense;
1699     }
1700 }
1701 
1702 void scsi_device_purge_requests(SCSIDevice *sdev, SCSISense sense)
1703 {
1704     SCSIRequest *req;
1705 
1706     while (!QTAILQ_EMPTY(&sdev->requests)) {
1707         req = QTAILQ_FIRST(&sdev->requests);
1708         scsi_req_cancel(req);
1709     }
1710 
1711     scsi_device_set_ua(sdev, sense);
1712 }
1713 
1714 static char *scsibus_get_dev_path(DeviceState *dev)
1715 {
1716     SCSIDevice *d = DO_UPCAST(SCSIDevice, qdev, dev);
1717     DeviceState *hba = dev->parent_bus->parent;
1718     char *id;
1719     char *path;
1720 
1721     id = qdev_get_dev_path(hba);
1722     if (id) {
1723         path = g_strdup_printf("%s/%d:%d:%d", id, d->channel, d->id, d->lun);
1724     } else {
1725         path = g_strdup_printf("%d:%d:%d", d->channel, d->id, d->lun);
1726     }
1727     g_free(id);
1728     return path;
1729 }
1730 
1731 static char *scsibus_get_fw_dev_path(DeviceState *dev)
1732 {
1733     SCSIDevice *d = SCSI_DEVICE(dev);
1734     return g_strdup_printf("channel@%x/%s@%x,%x", d->channel,
1735                            qdev_fw_name(dev), d->id, d->lun);
1736 }
1737 
1738 SCSIDevice *scsi_device_find(SCSIBus *bus, int channel, int id, int lun)
1739 {
1740     BusChild *kid;
1741     SCSIDevice *target_dev = NULL;
1742 
1743     QTAILQ_FOREACH_REVERSE(kid, &bus->qbus.children, ChildrenHead, sibling) {
1744         DeviceState *qdev = kid->child;
1745         SCSIDevice *dev = SCSI_DEVICE(qdev);
1746 
1747         if (dev->channel == channel && dev->id == id) {
1748             if (dev->lun == lun) {
1749                 return dev;
1750             }
1751             target_dev = dev;
1752         }
1753     }
1754     return target_dev;
1755 }
1756 
1757 /* SCSI request list.  For simplicity, pv points to the whole device */
1758 
1759 static void put_scsi_requests(QEMUFile *f, void *pv, size_t size)
1760 {
1761     SCSIDevice *s = pv;
1762     SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, s->qdev.parent_bus);
1763     SCSIRequest *req;
1764 
1765     QTAILQ_FOREACH(req, &s->requests, next) {
1766         assert(!req->io_canceled);
1767         assert(req->status == -1);
1768         assert(req->enqueued);
1769 
1770         qemu_put_sbyte(f, req->retry ? 1 : 2);
1771         qemu_put_buffer(f, req->cmd.buf, sizeof(req->cmd.buf));
1772         qemu_put_be32s(f, &req->tag);
1773         qemu_put_be32s(f, &req->lun);
1774         if (bus->info->save_request) {
1775             bus->info->save_request(f, req);
1776         }
1777         if (req->ops->save_request) {
1778             req->ops->save_request(f, req);
1779         }
1780     }
1781     qemu_put_sbyte(f, 0);
1782 }
1783 
1784 static int get_scsi_requests(QEMUFile *f, void *pv, size_t size)
1785 {
1786     SCSIDevice *s = pv;
1787     SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, s->qdev.parent_bus);
1788     int8_t sbyte;
1789 
1790     while ((sbyte = qemu_get_sbyte(f)) > 0) {
1791         uint8_t buf[SCSI_CMD_BUF_SIZE];
1792         uint32_t tag;
1793         uint32_t lun;
1794         SCSIRequest *req;
1795 
1796         qemu_get_buffer(f, buf, sizeof(buf));
1797         qemu_get_be32s(f, &tag);
1798         qemu_get_be32s(f, &lun);
1799         req = scsi_req_new(s, tag, lun, buf, NULL);
1800         req->retry = (sbyte == 1);
1801         if (bus->info->load_request) {
1802             req->hba_private = bus->info->load_request(f, req);
1803         }
1804         if (req->ops->load_request) {
1805             req->ops->load_request(f, req);
1806         }
1807 
1808         /* Just restart it later.  */
1809         scsi_req_enqueue_internal(req);
1810 
1811         /* At this point, the request will be kept alive by the reference
1812          * added by scsi_req_enqueue_internal, so we can release our reference.
1813          * The HBA of course will add its own reference in the load_request
1814          * callback if it needs to hold on the SCSIRequest.
1815          */
1816         scsi_req_unref(req);
1817     }
1818 
1819     return 0;
1820 }
1821 
1822 static int scsi_qdev_unplug(DeviceState *qdev)
1823 {
1824     SCSIDevice *dev = SCSI_DEVICE(qdev);
1825     SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus);
1826 
1827     if (bus->info->hot_unplug) {
1828         bus->info->hot_unplug(bus, dev);
1829     }
1830     return qdev_simple_unplug_cb(qdev);
1831 }
1832 
1833 static const VMStateInfo vmstate_info_scsi_requests = {
1834     .name = "scsi-requests",
1835     .get  = get_scsi_requests,
1836     .put  = put_scsi_requests,
1837 };
1838 
1839 const VMStateDescription vmstate_scsi_device = {
1840     .name = "SCSIDevice",
1841     .version_id = 1,
1842     .minimum_version_id = 1,
1843     .minimum_version_id_old = 1,
1844     .fields = (VMStateField[]) {
1845         VMSTATE_UINT8(unit_attention.key, SCSIDevice),
1846         VMSTATE_UINT8(unit_attention.asc, SCSIDevice),
1847         VMSTATE_UINT8(unit_attention.ascq, SCSIDevice),
1848         VMSTATE_BOOL(sense_is_ua, SCSIDevice),
1849         VMSTATE_UINT8_ARRAY(sense, SCSIDevice, SCSI_SENSE_BUF_SIZE),
1850         VMSTATE_UINT32(sense_len, SCSIDevice),
1851         {
1852             .name         = "requests",
1853             .version_id   = 0,
1854             .field_exists = NULL,
1855             .size         = 0,   /* ouch */
1856             .info         = &vmstate_info_scsi_requests,
1857             .flags        = VMS_SINGLE,
1858             .offset       = 0,
1859         },
1860         VMSTATE_END_OF_LIST()
1861     }
1862 };
1863 
1864 static void scsi_device_class_init(ObjectClass *klass, void *data)
1865 {
1866     DeviceClass *k = DEVICE_CLASS(klass);
1867     k->bus_type = TYPE_SCSI_BUS;
1868     k->init     = scsi_qdev_init;
1869     k->unplug   = scsi_qdev_unplug;
1870     k->exit     = scsi_qdev_exit;
1871     k->props    = scsi_props;
1872 }
1873 
1874 static const TypeInfo scsi_device_type_info = {
1875     .name = TYPE_SCSI_DEVICE,
1876     .parent = TYPE_DEVICE,
1877     .instance_size = sizeof(SCSIDevice),
1878     .abstract = true,
1879     .class_size = sizeof(SCSIDeviceClass),
1880     .class_init = scsi_device_class_init,
1881 };
1882 
1883 static void scsi_register_types(void)
1884 {
1885     type_register_static(&scsi_bus_info);
1886     type_register_static(&scsi_device_type_info);
1887 }
1888 
1889 type_init(scsi_register_types)
1890