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