xref: /openbmc/qemu/hw/scsi/scsi-bus.c (revision 88f62c2b)
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 
509     req = g_malloc0(reqops->size);
510     req->refcount = 1;
511     req->bus = scsi_bus_from_device(d);
512     req->dev = d;
513     req->tag = tag;
514     req->lun = lun;
515     req->hba_private = hba_private;
516     req->status = -1;
517     req->sense_len = 0;
518     req->ops = reqops;
519     trace_scsi_req_alloc(req->dev->id, req->lun, req->tag);
520     return req;
521 }
522 
523 SCSIRequest *scsi_req_new(SCSIDevice *d, uint32_t tag, uint32_t lun,
524                           uint8_t *buf, void *hba_private)
525 {
526     SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, d->qdev.parent_bus);
527     SCSIRequest *req;
528     SCSICommand cmd;
529 
530     if (scsi_req_parse(&cmd, d, buf) != 0) {
531         trace_scsi_req_parse_bad(d->id, lun, tag, buf[0]);
532         req = scsi_req_alloc(&reqops_invalid_opcode, d, tag, lun, hba_private);
533     } else {
534         trace_scsi_req_parsed(d->id, lun, tag, buf[0],
535                               cmd.mode, cmd.xfer);
536         if (cmd.lba != -1) {
537             trace_scsi_req_parsed_lba(d->id, lun, tag, buf[0],
538                                       cmd.lba);
539         }
540 
541         if (cmd.xfer > INT32_MAX) {
542             req = scsi_req_alloc(&reqops_invalid_field, d, tag, lun, hba_private);
543         } else if ((d->unit_attention.key == UNIT_ATTENTION ||
544                    bus->unit_attention.key == UNIT_ATTENTION) &&
545                   (buf[0] != INQUIRY &&
546                    buf[0] != REPORT_LUNS &&
547                    buf[0] != GET_CONFIGURATION &&
548                    buf[0] != GET_EVENT_STATUS_NOTIFICATION &&
549 
550                    /*
551                     * If we already have a pending unit attention condition,
552                     * report this one before triggering another one.
553                     */
554                    !(buf[0] == REQUEST_SENSE && d->sense_is_ua))) {
555             req = scsi_req_alloc(&reqops_unit_attention, d, tag, lun,
556                                  hba_private);
557         } else if (lun != d->lun ||
558                    buf[0] == REPORT_LUNS ||
559                    (buf[0] == REQUEST_SENSE && d->sense_len)) {
560             req = scsi_req_alloc(&reqops_target_command, d, tag, lun,
561                                  hba_private);
562         } else {
563             req = scsi_device_alloc_req(d, tag, lun, buf, hba_private);
564         }
565     }
566 
567     req->cmd = cmd;
568     req->resid = req->cmd.xfer;
569 
570     switch (buf[0]) {
571     case INQUIRY:
572         trace_scsi_inquiry(d->id, lun, tag, cmd.buf[1], cmd.buf[2]);
573         break;
574     case TEST_UNIT_READY:
575         trace_scsi_test_unit_ready(d->id, lun, tag);
576         break;
577     case REPORT_LUNS:
578         trace_scsi_report_luns(d->id, lun, tag);
579         break;
580     case REQUEST_SENSE:
581         trace_scsi_request_sense(d->id, lun, tag);
582         break;
583     default:
584         break;
585     }
586 
587     return req;
588 }
589 
590 uint8_t *scsi_req_get_buf(SCSIRequest *req)
591 {
592     return req->ops->get_buf(req);
593 }
594 
595 static void scsi_clear_unit_attention(SCSIRequest *req)
596 {
597     SCSISense *ua;
598     if (req->dev->unit_attention.key != UNIT_ATTENTION &&
599         req->bus->unit_attention.key != UNIT_ATTENTION) {
600         return;
601     }
602 
603     /*
604      * If an INQUIRY command enters the enabled command state,
605      * the device server shall [not] clear any unit attention condition;
606      * See also MMC-6, paragraphs 6.5 and 6.6.2.
607      */
608     if (req->cmd.buf[0] == INQUIRY ||
609         req->cmd.buf[0] == GET_CONFIGURATION ||
610         req->cmd.buf[0] == GET_EVENT_STATUS_NOTIFICATION) {
611         return;
612     }
613 
614     if (req->dev->unit_attention.key == UNIT_ATTENTION) {
615         ua = &req->dev->unit_attention;
616     } else {
617         ua = &req->bus->unit_attention;
618     }
619 
620     /*
621      * If a REPORT LUNS command enters the enabled command state, [...]
622      * the device server shall clear any pending unit attention condition
623      * with an additional sense code of REPORTED LUNS DATA HAS CHANGED.
624      */
625     if (req->cmd.buf[0] == REPORT_LUNS &&
626         !(ua->asc == SENSE_CODE(REPORTED_LUNS_CHANGED).asc &&
627           ua->ascq == SENSE_CODE(REPORTED_LUNS_CHANGED).ascq)) {
628         return;
629     }
630 
631     *ua = SENSE_CODE(NO_SENSE);
632 }
633 
634 int scsi_req_get_sense(SCSIRequest *req, uint8_t *buf, int len)
635 {
636     int ret;
637 
638     assert(len >= 14);
639     if (!req->sense_len) {
640         return 0;
641     }
642 
643     ret = scsi_build_sense(req->sense, req->sense_len, buf, len, true);
644 
645     /*
646      * FIXME: clearing unit attention conditions upon autosense should be done
647      * only if the UA_INTLCK_CTRL field in the Control mode page is set to 00b
648      * (SAM-5, 5.14).
649      *
650      * We assume UA_INTLCK_CTRL to be 00b for HBAs that support autosense, and
651      * 10b for HBAs that do not support it (do not call scsi_req_get_sense).
652      * Here we handle unit attention clearing for UA_INTLCK_CTRL == 00b.
653      */
654     if (req->dev->sense_is_ua) {
655         scsi_device_unit_attention_reported(req->dev);
656         req->dev->sense_len = 0;
657         req->dev->sense_is_ua = false;
658     }
659     return ret;
660 }
661 
662 int scsi_device_get_sense(SCSIDevice *dev, uint8_t *buf, int len, bool fixed)
663 {
664     return scsi_build_sense(dev->sense, dev->sense_len, buf, len, fixed);
665 }
666 
667 void scsi_req_build_sense(SCSIRequest *req, SCSISense sense)
668 {
669     trace_scsi_req_build_sense(req->dev->id, req->lun, req->tag,
670                                sense.key, sense.asc, sense.ascq);
671     memset(req->sense, 0, 18);
672     req->sense[0] = 0x70;
673     req->sense[2] = sense.key;
674     req->sense[7] = 10;
675     req->sense[12] = sense.asc;
676     req->sense[13] = sense.ascq;
677     req->sense_len = 18;
678 }
679 
680 static void scsi_req_enqueue_internal(SCSIRequest *req)
681 {
682     assert(!req->enqueued);
683     scsi_req_ref(req);
684     if (req->bus->info->get_sg_list) {
685         req->sg = req->bus->info->get_sg_list(req);
686     } else {
687         req->sg = NULL;
688     }
689     req->enqueued = true;
690     QTAILQ_INSERT_TAIL(&req->dev->requests, req, next);
691 }
692 
693 int32_t scsi_req_enqueue(SCSIRequest *req)
694 {
695     int32_t rc;
696 
697     assert(!req->retry);
698     scsi_req_enqueue_internal(req);
699     scsi_req_ref(req);
700     rc = req->ops->send_command(req, req->cmd.buf);
701     scsi_req_unref(req);
702     return rc;
703 }
704 
705 static void scsi_req_dequeue(SCSIRequest *req)
706 {
707     trace_scsi_req_dequeue(req->dev->id, req->lun, req->tag);
708     req->retry = false;
709     if (req->enqueued) {
710         QTAILQ_REMOVE(&req->dev->requests, req, next);
711         req->enqueued = false;
712         scsi_req_unref(req);
713     }
714 }
715 
716 static int scsi_get_performance_length(int num_desc, int type, int data_type)
717 {
718     /* MMC-6, paragraph 6.7.  */
719     switch (type) {
720     case 0:
721         if ((data_type & 3) == 0) {
722             /* Each descriptor is as in Table 295 - Nominal performance.  */
723             return 16 * num_desc + 8;
724         } else {
725             /* Each descriptor is as in Table 296 - Exceptions.  */
726             return 6 * num_desc + 8;
727         }
728     case 1:
729     case 4:
730     case 5:
731         return 8 * num_desc + 8;
732     case 2:
733         return 2048 * num_desc + 8;
734     case 3:
735         return 16 * num_desc + 8;
736     default:
737         return 8;
738     }
739 }
740 
741 static int ata_passthrough_xfer_unit(SCSIDevice *dev, uint8_t *buf)
742 {
743     int byte_block = (buf[2] >> 2) & 0x1;
744     int type = (buf[2] >> 4) & 0x1;
745     int xfer_unit;
746 
747     if (byte_block) {
748         if (type) {
749             xfer_unit = dev->blocksize;
750         } else {
751             xfer_unit = 512;
752         }
753     } else {
754         xfer_unit = 1;
755     }
756 
757     return xfer_unit;
758 }
759 
760 static int ata_passthrough_12_xfer_size(SCSIDevice *dev, uint8_t *buf)
761 {
762     int length = buf[2] & 0x3;
763     int xfer;
764     int unit = ata_passthrough_xfer_unit(dev, buf);
765 
766     switch (length) {
767     case 0:
768     case 3: /* USB-specific.  */
769     default:
770         xfer = 0;
771         break;
772     case 1:
773         xfer = buf[3];
774         break;
775     case 2:
776         xfer = buf[4];
777         break;
778     }
779 
780     return xfer * unit;
781 }
782 
783 static int ata_passthrough_16_xfer_size(SCSIDevice *dev, uint8_t *buf)
784 {
785     int extend = buf[1] & 0x1;
786     int length = buf[2] & 0x3;
787     int xfer;
788     int unit = ata_passthrough_xfer_unit(dev, buf);
789 
790     switch (length) {
791     case 0:
792     case 3: /* USB-specific.  */
793     default:
794         xfer = 0;
795         break;
796     case 1:
797         xfer = buf[4];
798         xfer |= (extend ? buf[3] << 8 : 0);
799         break;
800     case 2:
801         xfer = buf[6];
802         xfer |= (extend ? buf[5] << 8 : 0);
803         break;
804     }
805 
806     return xfer * unit;
807 }
808 
809 uint32_t scsi_data_cdb_length(uint8_t *buf)
810 {
811     if ((buf[0] >> 5) == 0 && buf[4] == 0) {
812         return 256;
813     } else {
814         return scsi_cdb_length(buf);
815     }
816 }
817 
818 uint32_t scsi_cdb_length(uint8_t *buf)
819 {
820     switch (buf[0] >> 5) {
821     case 0:
822         return buf[4];
823         break;
824     case 1:
825     case 2:
826         return lduw_be_p(&buf[7]);
827         break;
828     case 4:
829         return ldl_be_p(&buf[10]) & 0xffffffffULL;
830         break;
831     case 5:
832         return ldl_be_p(&buf[6]) & 0xffffffffULL;
833         break;
834     default:
835         return -1;
836     }
837 }
838 
839 static int scsi_req_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
840 {
841     cmd->xfer = scsi_cdb_length(buf);
842     switch (buf[0]) {
843     case TEST_UNIT_READY:
844     case REWIND:
845     case START_STOP:
846     case SET_CAPACITY:
847     case WRITE_FILEMARKS:
848     case WRITE_FILEMARKS_16:
849     case SPACE:
850     case RESERVE:
851     case RELEASE:
852     case ERASE:
853     case ALLOW_MEDIUM_REMOVAL:
854     case VERIFY_10:
855     case SEEK_10:
856     case SYNCHRONIZE_CACHE:
857     case SYNCHRONIZE_CACHE_16:
858     case LOCATE_16:
859     case LOCK_UNLOCK_CACHE:
860     case SET_CD_SPEED:
861     case SET_LIMITS:
862     case WRITE_LONG_10:
863     case UPDATE_BLOCK:
864     case RESERVE_TRACK:
865     case SET_READ_AHEAD:
866     case PRE_FETCH:
867     case PRE_FETCH_16:
868     case ALLOW_OVERWRITE:
869         cmd->xfer = 0;
870         break;
871     case MODE_SENSE:
872         break;
873     case WRITE_SAME_10:
874     case WRITE_SAME_16:
875         cmd->xfer = dev->blocksize;
876         break;
877     case READ_CAPACITY_10:
878         cmd->xfer = 8;
879         break;
880     case READ_BLOCK_LIMITS:
881         cmd->xfer = 6;
882         break;
883     case SEND_VOLUME_TAG:
884         /* GPCMD_SET_STREAMING from multimedia commands.  */
885         if (dev->type == TYPE_ROM) {
886             cmd->xfer = buf[10] | (buf[9] << 8);
887         } else {
888             cmd->xfer = buf[9] | (buf[8] << 8);
889         }
890         break;
891     case WRITE_6:
892         /* length 0 means 256 blocks */
893         if (cmd->xfer == 0) {
894             cmd->xfer = 256;
895         }
896     case WRITE_10:
897     case WRITE_VERIFY_10:
898     case WRITE_12:
899     case WRITE_VERIFY_12:
900     case WRITE_16:
901     case WRITE_VERIFY_16:
902         cmd->xfer *= dev->blocksize;
903         break;
904     case READ_6:
905     case READ_REVERSE:
906         /* length 0 means 256 blocks */
907         if (cmd->xfer == 0) {
908             cmd->xfer = 256;
909         }
910     case READ_10:
911     case RECOVER_BUFFERED_DATA:
912     case READ_12:
913     case READ_16:
914         cmd->xfer *= dev->blocksize;
915         break;
916     case FORMAT_UNIT:
917         /* MMC mandates the parameter list to be 12-bytes long.  Parameters
918          * for block devices are restricted to the header right now.  */
919         if (dev->type == TYPE_ROM && (buf[1] & 16)) {
920             cmd->xfer = 12;
921         } else {
922             cmd->xfer = (buf[1] & 16) == 0 ? 0 : (buf[1] & 32 ? 8 : 4);
923         }
924         break;
925     case INQUIRY:
926     case RECEIVE_DIAGNOSTIC:
927     case SEND_DIAGNOSTIC:
928         cmd->xfer = buf[4] | (buf[3] << 8);
929         break;
930     case READ_CD:
931     case READ_BUFFER:
932     case WRITE_BUFFER:
933     case SEND_CUE_SHEET:
934         cmd->xfer = buf[8] | (buf[7] << 8) | (buf[6] << 16);
935         break;
936     case PERSISTENT_RESERVE_OUT:
937         cmd->xfer = ldl_be_p(&buf[5]) & 0xffffffffULL;
938         break;
939     case ERASE_12:
940         if (dev->type == TYPE_ROM) {
941             /* MMC command GET PERFORMANCE.  */
942             cmd->xfer = scsi_get_performance_length(buf[9] | (buf[8] << 8),
943                                                     buf[10], buf[1] & 0x1f);
944         }
945         break;
946     case MECHANISM_STATUS:
947     case READ_DVD_STRUCTURE:
948     case SEND_DVD_STRUCTURE:
949     case MAINTENANCE_OUT:
950     case MAINTENANCE_IN:
951         if (dev->type == TYPE_ROM) {
952             /* GPCMD_REPORT_KEY and GPCMD_SEND_KEY from multi media commands */
953             cmd->xfer = buf[9] | (buf[8] << 8);
954         }
955         break;
956     case ATA_PASSTHROUGH_12:
957         if (dev->type == TYPE_ROM) {
958             /* BLANK command of MMC */
959             cmd->xfer = 0;
960         } else {
961             cmd->xfer = ata_passthrough_12_xfer_size(dev, buf);
962         }
963         break;
964     case ATA_PASSTHROUGH_16:
965         cmd->xfer = ata_passthrough_16_xfer_size(dev, buf);
966         break;
967     }
968     return 0;
969 }
970 
971 static int scsi_req_stream_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
972 {
973     switch (buf[0]) {
974     /* stream commands */
975     case ERASE_12:
976     case ERASE_16:
977         cmd->xfer = 0;
978         break;
979     case READ_6:
980     case READ_REVERSE:
981     case RECOVER_BUFFERED_DATA:
982     case WRITE_6:
983         cmd->xfer = buf[4] | (buf[3] << 8) | (buf[2] << 16);
984         if (buf[1] & 0x01) { /* fixed */
985             cmd->xfer *= dev->blocksize;
986         }
987         break;
988     case READ_16:
989     case READ_REVERSE_16:
990     case VERIFY_16:
991     case WRITE_16:
992         cmd->xfer = buf[14] | (buf[13] << 8) | (buf[12] << 16);
993         if (buf[1] & 0x01) { /* fixed */
994             cmd->xfer *= dev->blocksize;
995         }
996         break;
997     case REWIND:
998     case LOAD_UNLOAD:
999         cmd->xfer = 0;
1000         break;
1001     case SPACE_16:
1002         cmd->xfer = buf[13] | (buf[12] << 8);
1003         break;
1004     case READ_POSITION:
1005         switch (buf[1] & 0x1f) /* operation code */ {
1006         case SHORT_FORM_BLOCK_ID:
1007         case SHORT_FORM_VENDOR_SPECIFIC:
1008             cmd->xfer = 20;
1009             break;
1010         case LONG_FORM:
1011             cmd->xfer = 32;
1012             break;
1013         case EXTENDED_FORM:
1014             cmd->xfer = buf[8] | (buf[7] << 8);
1015             break;
1016         default:
1017             return -1;
1018         }
1019 
1020         break;
1021     case FORMAT_UNIT:
1022         cmd->xfer = buf[4] | (buf[3] << 8);
1023         break;
1024     /* generic commands */
1025     default:
1026         return scsi_req_length(cmd, dev, buf);
1027     }
1028     return 0;
1029 }
1030 
1031 static int scsi_req_medium_changer_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
1032 {
1033     switch (buf[0]) {
1034     /* medium changer commands */
1035     case EXCHANGE_MEDIUM:
1036     case INITIALIZE_ELEMENT_STATUS:
1037     case INITIALIZE_ELEMENT_STATUS_WITH_RANGE:
1038     case MOVE_MEDIUM:
1039     case POSITION_TO_ELEMENT:
1040         cmd->xfer = 0;
1041         break;
1042     case READ_ELEMENT_STATUS:
1043         cmd->xfer = buf[9] | (buf[8] << 8) | (buf[7] << 16);
1044         break;
1045 
1046     /* generic commands */
1047     default:
1048         return scsi_req_length(cmd, dev, buf);
1049     }
1050     return 0;
1051 }
1052 
1053 
1054 static void scsi_cmd_xfer_mode(SCSICommand *cmd)
1055 {
1056     if (!cmd->xfer) {
1057         cmd->mode = SCSI_XFER_NONE;
1058         return;
1059     }
1060     switch (cmd->buf[0]) {
1061     case WRITE_6:
1062     case WRITE_10:
1063     case WRITE_VERIFY_10:
1064     case WRITE_12:
1065     case WRITE_VERIFY_12:
1066     case WRITE_16:
1067     case WRITE_VERIFY_16:
1068     case COPY:
1069     case COPY_VERIFY:
1070     case COMPARE:
1071     case CHANGE_DEFINITION:
1072     case LOG_SELECT:
1073     case MODE_SELECT:
1074     case MODE_SELECT_10:
1075     case SEND_DIAGNOSTIC:
1076     case WRITE_BUFFER:
1077     case FORMAT_UNIT:
1078     case REASSIGN_BLOCKS:
1079     case SEARCH_EQUAL:
1080     case SEARCH_HIGH:
1081     case SEARCH_LOW:
1082     case UPDATE_BLOCK:
1083     case WRITE_LONG_10:
1084     case WRITE_SAME_10:
1085     case WRITE_SAME_16:
1086     case UNMAP:
1087     case SEARCH_HIGH_12:
1088     case SEARCH_EQUAL_12:
1089     case SEARCH_LOW_12:
1090     case MEDIUM_SCAN:
1091     case SEND_VOLUME_TAG:
1092     case SEND_CUE_SHEET:
1093     case SEND_DVD_STRUCTURE:
1094     case PERSISTENT_RESERVE_OUT:
1095     case MAINTENANCE_OUT:
1096         cmd->mode = SCSI_XFER_TO_DEV;
1097         break;
1098     case ATA_PASSTHROUGH_12:
1099     case ATA_PASSTHROUGH_16:
1100         /* T_DIR */
1101         cmd->mode = (cmd->buf[2] & 0x8) ?
1102                    SCSI_XFER_FROM_DEV : SCSI_XFER_TO_DEV;
1103         break;
1104     default:
1105         cmd->mode = SCSI_XFER_FROM_DEV;
1106         break;
1107     }
1108 }
1109 
1110 static uint64_t scsi_cmd_lba(SCSICommand *cmd)
1111 {
1112     uint8_t *buf = cmd->buf;
1113     uint64_t lba;
1114 
1115     switch (buf[0] >> 5) {
1116     case 0:
1117         lba = ldl_be_p(&buf[0]) & 0x1fffff;
1118         break;
1119     case 1:
1120     case 2:
1121     case 5:
1122         lba = ldl_be_p(&buf[2]) & 0xffffffffULL;
1123         break;
1124     case 4:
1125         lba = ldq_be_p(&buf[2]);
1126         break;
1127     default:
1128         lba = -1;
1129 
1130     }
1131     return lba;
1132 }
1133 
1134 int scsi_req_parse(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
1135 {
1136     int rc;
1137 
1138     switch (buf[0] >> 5) {
1139     case 0:
1140         cmd->len = 6;
1141         break;
1142     case 1:
1143     case 2:
1144         cmd->len = 10;
1145         break;
1146     case 4:
1147         cmd->len = 16;
1148         break;
1149     case 5:
1150         cmd->len = 12;
1151         break;
1152     default:
1153         return -1;
1154     }
1155 
1156     switch (dev->type) {
1157     case TYPE_TAPE:
1158         rc = scsi_req_stream_length(cmd, dev, buf);
1159         break;
1160     case TYPE_MEDIUM_CHANGER:
1161         rc = scsi_req_medium_changer_length(cmd, dev, buf);
1162         break;
1163     default:
1164         rc = scsi_req_length(cmd, dev, buf);
1165         break;
1166     }
1167 
1168     if (rc != 0)
1169         return rc;
1170 
1171     memcpy(cmd->buf, buf, cmd->len);
1172     scsi_cmd_xfer_mode(cmd);
1173     cmd->lba = scsi_cmd_lba(cmd);
1174     return 0;
1175 }
1176 
1177 void scsi_device_report_change(SCSIDevice *dev, SCSISense sense)
1178 {
1179     SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus);
1180 
1181     scsi_device_set_ua(dev, sense);
1182     if (bus->info->change) {
1183         bus->info->change(bus, dev, sense);
1184     }
1185 }
1186 
1187 /*
1188  * Predefined sense codes
1189  */
1190 
1191 /* No sense data available */
1192 const struct SCSISense sense_code_NO_SENSE = {
1193     .key = NO_SENSE , .asc = 0x00 , .ascq = 0x00
1194 };
1195 
1196 /* LUN not ready, Manual intervention required */
1197 const struct SCSISense sense_code_LUN_NOT_READY = {
1198     .key = NOT_READY, .asc = 0x04, .ascq = 0x03
1199 };
1200 
1201 /* LUN not ready, Medium not present */
1202 const struct SCSISense sense_code_NO_MEDIUM = {
1203     .key = NOT_READY, .asc = 0x3a, .ascq = 0x00
1204 };
1205 
1206 /* LUN not ready, medium removal prevented */
1207 const struct SCSISense sense_code_NOT_READY_REMOVAL_PREVENTED = {
1208     .key = NOT_READY, .asc = 0x53, .ascq = 0x02
1209 };
1210 
1211 /* Hardware error, internal target failure */
1212 const struct SCSISense sense_code_TARGET_FAILURE = {
1213     .key = HARDWARE_ERROR, .asc = 0x44, .ascq = 0x00
1214 };
1215 
1216 /* Illegal request, invalid command operation code */
1217 const struct SCSISense sense_code_INVALID_OPCODE = {
1218     .key = ILLEGAL_REQUEST, .asc = 0x20, .ascq = 0x00
1219 };
1220 
1221 /* Illegal request, LBA out of range */
1222 const struct SCSISense sense_code_LBA_OUT_OF_RANGE = {
1223     .key = ILLEGAL_REQUEST, .asc = 0x21, .ascq = 0x00
1224 };
1225 
1226 /* Illegal request, Invalid field in CDB */
1227 const struct SCSISense sense_code_INVALID_FIELD = {
1228     .key = ILLEGAL_REQUEST, .asc = 0x24, .ascq = 0x00
1229 };
1230 
1231 /* Illegal request, Invalid field in parameter list */
1232 const struct SCSISense sense_code_INVALID_PARAM = {
1233     .key = ILLEGAL_REQUEST, .asc = 0x26, .ascq = 0x00
1234 };
1235 
1236 /* Illegal request, Parameter list length error */
1237 const struct SCSISense sense_code_INVALID_PARAM_LEN = {
1238     .key = ILLEGAL_REQUEST, .asc = 0x1a, .ascq = 0x00
1239 };
1240 
1241 /* Illegal request, LUN not supported */
1242 const struct SCSISense sense_code_LUN_NOT_SUPPORTED = {
1243     .key = ILLEGAL_REQUEST, .asc = 0x25, .ascq = 0x00
1244 };
1245 
1246 /* Illegal request, Saving parameters not supported */
1247 const struct SCSISense sense_code_SAVING_PARAMS_NOT_SUPPORTED = {
1248     .key = ILLEGAL_REQUEST, .asc = 0x39, .ascq = 0x00
1249 };
1250 
1251 /* Illegal request, Incompatible medium installed */
1252 const struct SCSISense sense_code_INCOMPATIBLE_FORMAT = {
1253     .key = ILLEGAL_REQUEST, .asc = 0x30, .ascq = 0x00
1254 };
1255 
1256 /* Illegal request, medium removal prevented */
1257 const struct SCSISense sense_code_ILLEGAL_REQ_REMOVAL_PREVENTED = {
1258     .key = ILLEGAL_REQUEST, .asc = 0x53, .ascq = 0x02
1259 };
1260 
1261 /* Command aborted, I/O process terminated */
1262 const struct SCSISense sense_code_IO_ERROR = {
1263     .key = ABORTED_COMMAND, .asc = 0x00, .ascq = 0x06
1264 };
1265 
1266 /* Command aborted, I_T Nexus loss occurred */
1267 const struct SCSISense sense_code_I_T_NEXUS_LOSS = {
1268     .key = ABORTED_COMMAND, .asc = 0x29, .ascq = 0x07
1269 };
1270 
1271 /* Command aborted, Logical Unit failure */
1272 const struct SCSISense sense_code_LUN_FAILURE = {
1273     .key = ABORTED_COMMAND, .asc = 0x3e, .ascq = 0x01
1274 };
1275 
1276 /* Unit attention, Capacity data has changed */
1277 const struct SCSISense sense_code_CAPACITY_CHANGED = {
1278     .key = UNIT_ATTENTION, .asc = 0x2a, .ascq = 0x09
1279 };
1280 
1281 /* Unit attention, Power on, reset or bus device reset occurred */
1282 const struct SCSISense sense_code_RESET = {
1283     .key = UNIT_ATTENTION, .asc = 0x29, .ascq = 0x00
1284 };
1285 
1286 /* Unit attention, No medium */
1287 const struct SCSISense sense_code_UNIT_ATTENTION_NO_MEDIUM = {
1288     .key = UNIT_ATTENTION, .asc = 0x3a, .ascq = 0x00
1289 };
1290 
1291 /* Unit attention, Medium may have changed */
1292 const struct SCSISense sense_code_MEDIUM_CHANGED = {
1293     .key = UNIT_ATTENTION, .asc = 0x28, .ascq = 0x00
1294 };
1295 
1296 /* Unit attention, Reported LUNs data has changed */
1297 const struct SCSISense sense_code_REPORTED_LUNS_CHANGED = {
1298     .key = UNIT_ATTENTION, .asc = 0x3f, .ascq = 0x0e
1299 };
1300 
1301 /* Unit attention, Device internal reset */
1302 const struct SCSISense sense_code_DEVICE_INTERNAL_RESET = {
1303     .key = UNIT_ATTENTION, .asc = 0x29, .ascq = 0x04
1304 };
1305 
1306 /* Data Protection, Write Protected */
1307 const struct SCSISense sense_code_WRITE_PROTECTED = {
1308     .key = DATA_PROTECT, .asc = 0x27, .ascq = 0x00
1309 };
1310 
1311 /*
1312  * scsi_build_sense
1313  *
1314  * Convert between fixed and descriptor sense buffers
1315  */
1316 int scsi_build_sense(uint8_t *in_buf, int in_len,
1317                      uint8_t *buf, int len, bool fixed)
1318 {
1319     bool fixed_in;
1320     SCSISense sense;
1321     if (!fixed && len < 8) {
1322         return 0;
1323     }
1324 
1325     if (in_len == 0) {
1326         sense.key = NO_SENSE;
1327         sense.asc = 0;
1328         sense.ascq = 0;
1329     } else {
1330         fixed_in = (in_buf[0] & 2) == 0;
1331 
1332         if (fixed == fixed_in) {
1333             memcpy(buf, in_buf, MIN(len, in_len));
1334             return MIN(len, in_len);
1335         }
1336 
1337         if (fixed_in) {
1338             sense.key = in_buf[2];
1339             sense.asc = in_buf[12];
1340             sense.ascq = in_buf[13];
1341         } else {
1342             sense.key = in_buf[1];
1343             sense.asc = in_buf[2];
1344             sense.ascq = in_buf[3];
1345         }
1346     }
1347 
1348     memset(buf, 0, len);
1349     if (fixed) {
1350         /* Return fixed format sense buffer */
1351         buf[0] = 0x70;
1352         buf[2] = sense.key;
1353         buf[7] = 10;
1354         buf[12] = sense.asc;
1355         buf[13] = sense.ascq;
1356         return MIN(len, 18);
1357     } else {
1358         /* Return descriptor format sense buffer */
1359         buf[0] = 0x72;
1360         buf[1] = sense.key;
1361         buf[2] = sense.asc;
1362         buf[3] = sense.ascq;
1363         return 8;
1364     }
1365 }
1366 
1367 static const char *scsi_command_name(uint8_t cmd)
1368 {
1369     static const char *names[] = {
1370         [ TEST_UNIT_READY          ] = "TEST_UNIT_READY",
1371         [ REWIND                   ] = "REWIND",
1372         [ REQUEST_SENSE            ] = "REQUEST_SENSE",
1373         [ FORMAT_UNIT              ] = "FORMAT_UNIT",
1374         [ READ_BLOCK_LIMITS        ] = "READ_BLOCK_LIMITS",
1375         [ REASSIGN_BLOCKS          ] = "REASSIGN_BLOCKS/INITIALIZE ELEMENT STATUS",
1376         /* LOAD_UNLOAD and INITIALIZE_ELEMENT_STATUS use the same operation code */
1377         [ READ_6                   ] = "READ_6",
1378         [ WRITE_6                  ] = "WRITE_6",
1379         [ SET_CAPACITY             ] = "SET_CAPACITY",
1380         [ READ_REVERSE             ] = "READ_REVERSE",
1381         [ WRITE_FILEMARKS          ] = "WRITE_FILEMARKS",
1382         [ SPACE                    ] = "SPACE",
1383         [ INQUIRY                  ] = "INQUIRY",
1384         [ RECOVER_BUFFERED_DATA    ] = "RECOVER_BUFFERED_DATA",
1385         [ MAINTENANCE_IN           ] = "MAINTENANCE_IN",
1386         [ MAINTENANCE_OUT          ] = "MAINTENANCE_OUT",
1387         [ MODE_SELECT              ] = "MODE_SELECT",
1388         [ RESERVE                  ] = "RESERVE",
1389         [ RELEASE                  ] = "RELEASE",
1390         [ COPY                     ] = "COPY",
1391         [ ERASE                    ] = "ERASE",
1392         [ MODE_SENSE               ] = "MODE_SENSE",
1393         [ START_STOP               ] = "START_STOP/LOAD_UNLOAD",
1394         /* LOAD_UNLOAD and START_STOP use the same operation code */
1395         [ RECEIVE_DIAGNOSTIC       ] = "RECEIVE_DIAGNOSTIC",
1396         [ SEND_DIAGNOSTIC          ] = "SEND_DIAGNOSTIC",
1397         [ ALLOW_MEDIUM_REMOVAL     ] = "ALLOW_MEDIUM_REMOVAL",
1398         [ READ_CAPACITY_10         ] = "READ_CAPACITY_10",
1399         [ READ_10                  ] = "READ_10",
1400         [ WRITE_10                 ] = "WRITE_10",
1401         [ SEEK_10                  ] = "SEEK_10/POSITION_TO_ELEMENT",
1402         /* SEEK_10 and POSITION_TO_ELEMENT use the same operation code */
1403         [ WRITE_VERIFY_10          ] = "WRITE_VERIFY_10",
1404         [ VERIFY_10                ] = "VERIFY_10",
1405         [ SEARCH_HIGH              ] = "SEARCH_HIGH",
1406         [ SEARCH_EQUAL             ] = "SEARCH_EQUAL",
1407         [ SEARCH_LOW               ] = "SEARCH_LOW",
1408         [ SET_LIMITS               ] = "SET_LIMITS",
1409         [ PRE_FETCH                ] = "PRE_FETCH/READ_POSITION",
1410         /* READ_POSITION and PRE_FETCH use the same operation code */
1411         [ SYNCHRONIZE_CACHE        ] = "SYNCHRONIZE_CACHE",
1412         [ LOCK_UNLOCK_CACHE        ] = "LOCK_UNLOCK_CACHE",
1413         [ READ_DEFECT_DATA         ] = "READ_DEFECT_DATA/INITIALIZE_ELEMENT_STATUS_WITH_RANGE",
1414         /* READ_DEFECT_DATA and INITIALIZE_ELEMENT_STATUS_WITH_RANGE use the same operation code */
1415         [ MEDIUM_SCAN              ] = "MEDIUM_SCAN",
1416         [ COMPARE                  ] = "COMPARE",
1417         [ COPY_VERIFY              ] = "COPY_VERIFY",
1418         [ WRITE_BUFFER             ] = "WRITE_BUFFER",
1419         [ READ_BUFFER              ] = "READ_BUFFER",
1420         [ UPDATE_BLOCK             ] = "UPDATE_BLOCK",
1421         [ READ_LONG_10             ] = "READ_LONG_10",
1422         [ WRITE_LONG_10            ] = "WRITE_LONG_10",
1423         [ CHANGE_DEFINITION        ] = "CHANGE_DEFINITION",
1424         [ WRITE_SAME_10            ] = "WRITE_SAME_10",
1425         [ UNMAP                    ] = "UNMAP",
1426         [ READ_TOC                 ] = "READ_TOC",
1427         [ REPORT_DENSITY_SUPPORT   ] = "REPORT_DENSITY_SUPPORT",
1428         [ SANITIZE                 ] = "SANITIZE",
1429         [ GET_CONFIGURATION        ] = "GET_CONFIGURATION",
1430         [ LOG_SELECT               ] = "LOG_SELECT",
1431         [ LOG_SENSE                ] = "LOG_SENSE",
1432         [ MODE_SELECT_10           ] = "MODE_SELECT_10",
1433         [ RESERVE_10               ] = "RESERVE_10",
1434         [ RELEASE_10               ] = "RELEASE_10",
1435         [ MODE_SENSE_10            ] = "MODE_SENSE_10",
1436         [ PERSISTENT_RESERVE_IN    ] = "PERSISTENT_RESERVE_IN",
1437         [ PERSISTENT_RESERVE_OUT   ] = "PERSISTENT_RESERVE_OUT",
1438         [ WRITE_FILEMARKS_16       ] = "WRITE_FILEMARKS_16",
1439         [ EXTENDED_COPY            ] = "EXTENDED_COPY",
1440         [ ATA_PASSTHROUGH_16       ] = "ATA_PASSTHROUGH_16",
1441         [ ACCESS_CONTROL_IN        ] = "ACCESS_CONTROL_IN",
1442         [ ACCESS_CONTROL_OUT       ] = "ACCESS_CONTROL_OUT",
1443         [ READ_16                  ] = "READ_16",
1444         [ COMPARE_AND_WRITE        ] = "COMPARE_AND_WRITE",
1445         [ WRITE_16                 ] = "WRITE_16",
1446         [ WRITE_VERIFY_16          ] = "WRITE_VERIFY_16",
1447         [ VERIFY_16                ] = "VERIFY_16",
1448         [ PRE_FETCH_16             ] = "PRE_FETCH_16",
1449         [ SYNCHRONIZE_CACHE_16     ] = "SPACE_16/SYNCHRONIZE_CACHE_16",
1450         /* SPACE_16 and SYNCHRONIZE_CACHE_16 use the same operation code */
1451         [ LOCATE_16                ] = "LOCATE_16",
1452         [ WRITE_SAME_16            ] = "ERASE_16/WRITE_SAME_16",
1453         /* ERASE_16 and WRITE_SAME_16 use the same operation code */
1454         [ SERVICE_ACTION_IN_16     ] = "SERVICE_ACTION_IN_16",
1455         [ WRITE_LONG_16            ] = "WRITE_LONG_16",
1456         [ REPORT_LUNS              ] = "REPORT_LUNS",
1457         [ ATA_PASSTHROUGH_12       ] = "BLANK/ATA_PASSTHROUGH_12",
1458         [ MOVE_MEDIUM              ] = "MOVE_MEDIUM",
1459         [ EXCHANGE_MEDIUM          ] = "EXCHANGE MEDIUM",
1460         [ READ_12                  ] = "READ_12",
1461         [ WRITE_12                 ] = "WRITE_12",
1462         [ ERASE_12                 ] = "ERASE_12/GET_PERFORMANCE",
1463         /* ERASE_12 and GET_PERFORMANCE use the same operation code */
1464         [ SERVICE_ACTION_IN_12     ] = "SERVICE_ACTION_IN_12",
1465         [ WRITE_VERIFY_12          ] = "WRITE_VERIFY_12",
1466         [ VERIFY_12                ] = "VERIFY_12",
1467         [ SEARCH_HIGH_12           ] = "SEARCH_HIGH_12",
1468         [ SEARCH_EQUAL_12          ] = "SEARCH_EQUAL_12",
1469         [ SEARCH_LOW_12            ] = "SEARCH_LOW_12",
1470         [ READ_ELEMENT_STATUS      ] = "READ_ELEMENT_STATUS",
1471         [ SEND_VOLUME_TAG          ] = "SEND_VOLUME_TAG/SET_STREAMING",
1472         /* SEND_VOLUME_TAG and SET_STREAMING use the same operation code */
1473         [ READ_CD                  ] = "READ_CD",
1474         [ READ_DEFECT_DATA_12      ] = "READ_DEFECT_DATA_12",
1475         [ READ_DVD_STRUCTURE       ] = "READ_DVD_STRUCTURE",
1476         [ RESERVE_TRACK            ] = "RESERVE_TRACK",
1477         [ SEND_CUE_SHEET           ] = "SEND_CUE_SHEET",
1478         [ SEND_DVD_STRUCTURE       ] = "SEND_DVD_STRUCTURE",
1479         [ SET_CD_SPEED             ] = "SET_CD_SPEED",
1480         [ SET_READ_AHEAD           ] = "SET_READ_AHEAD",
1481         [ ALLOW_OVERWRITE          ] = "ALLOW_OVERWRITE",
1482         [ MECHANISM_STATUS         ] = "MECHANISM_STATUS",
1483     };
1484 
1485     if (cmd >= ARRAY_SIZE(names) || names[cmd] == NULL)
1486         return "*UNKNOWN*";
1487     return names[cmd];
1488 }
1489 
1490 SCSIRequest *scsi_req_ref(SCSIRequest *req)
1491 {
1492     assert(req->refcount > 0);
1493     req->refcount++;
1494     return req;
1495 }
1496 
1497 void scsi_req_unref(SCSIRequest *req)
1498 {
1499     assert(req->refcount > 0);
1500     if (--req->refcount == 0) {
1501         SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, req->dev->qdev.parent_bus);
1502         if (bus->info->free_request && req->hba_private) {
1503             bus->info->free_request(bus, req->hba_private);
1504         }
1505         if (req->ops->free_req) {
1506             req->ops->free_req(req);
1507         }
1508         g_free(req);
1509     }
1510 }
1511 
1512 /* Tell the device that we finished processing this chunk of I/O.  It
1513    will start the next chunk or complete the command.  */
1514 void scsi_req_continue(SCSIRequest *req)
1515 {
1516     if (req->io_canceled) {
1517         trace_scsi_req_continue_canceled(req->dev->id, req->lun, req->tag);
1518         return;
1519     }
1520     trace_scsi_req_continue(req->dev->id, req->lun, req->tag);
1521     if (req->cmd.mode == SCSI_XFER_TO_DEV) {
1522         req->ops->write_data(req);
1523     } else {
1524         req->ops->read_data(req);
1525     }
1526 }
1527 
1528 /* Called by the devices when data is ready for the HBA.  The HBA should
1529    start a DMA operation to read or fill the device's data buffer.
1530    Once it completes, calling scsi_req_continue will restart I/O.  */
1531 void scsi_req_data(SCSIRequest *req, int len)
1532 {
1533     uint8_t *buf;
1534     if (req->io_canceled) {
1535         trace_scsi_req_data_canceled(req->dev->id, req->lun, req->tag, len);
1536         return;
1537     }
1538     trace_scsi_req_data(req->dev->id, req->lun, req->tag, len);
1539     assert(req->cmd.mode != SCSI_XFER_NONE);
1540     if (!req->sg) {
1541         req->resid -= len;
1542         req->bus->info->transfer_data(req, len);
1543         return;
1544     }
1545 
1546     /* If the device calls scsi_req_data and the HBA specified a
1547      * scatter/gather list, the transfer has to happen in a single
1548      * step.  */
1549     assert(!req->dma_started);
1550     req->dma_started = true;
1551 
1552     buf = scsi_req_get_buf(req);
1553     if (req->cmd.mode == SCSI_XFER_FROM_DEV) {
1554         req->resid = dma_buf_read(buf, len, req->sg);
1555     } else {
1556         req->resid = dma_buf_write(buf, len, req->sg);
1557     }
1558     scsi_req_continue(req);
1559 }
1560 
1561 void scsi_req_print(SCSIRequest *req)
1562 {
1563     FILE *fp = stderr;
1564     int i;
1565 
1566     fprintf(fp, "[%s id=%d] %s",
1567             req->dev->qdev.parent_bus->name,
1568             req->dev->id,
1569             scsi_command_name(req->cmd.buf[0]));
1570     for (i = 1; i < req->cmd.len; i++) {
1571         fprintf(fp, " 0x%02x", req->cmd.buf[i]);
1572     }
1573     switch (req->cmd.mode) {
1574     case SCSI_XFER_NONE:
1575         fprintf(fp, " - none\n");
1576         break;
1577     case SCSI_XFER_FROM_DEV:
1578         fprintf(fp, " - from-dev len=%zd\n", req->cmd.xfer);
1579         break;
1580     case SCSI_XFER_TO_DEV:
1581         fprintf(fp, " - to-dev len=%zd\n", req->cmd.xfer);
1582         break;
1583     default:
1584         fprintf(fp, " - Oops\n");
1585         break;
1586     }
1587 }
1588 
1589 void scsi_req_complete(SCSIRequest *req, int status)
1590 {
1591     assert(req->status == -1);
1592     req->status = status;
1593 
1594     assert(req->sense_len <= sizeof(req->sense));
1595     if (status == GOOD) {
1596         req->sense_len = 0;
1597     }
1598 
1599     if (req->sense_len) {
1600         memcpy(req->dev->sense, req->sense, req->sense_len);
1601         req->dev->sense_len = req->sense_len;
1602         req->dev->sense_is_ua = (req->ops == &reqops_unit_attention);
1603     } else {
1604         req->dev->sense_len = 0;
1605         req->dev->sense_is_ua = false;
1606     }
1607 
1608     /*
1609      * Unit attention state is now stored in the device's sense buffer
1610      * if the HBA didn't do autosense.  Clear the pending unit attention
1611      * flags.
1612      */
1613     scsi_clear_unit_attention(req);
1614 
1615     scsi_req_ref(req);
1616     scsi_req_dequeue(req);
1617     req->bus->info->complete(req, req->status, req->resid);
1618     scsi_req_unref(req);
1619 }
1620 
1621 void scsi_req_cancel(SCSIRequest *req)
1622 {
1623     trace_scsi_req_cancel(req->dev->id, req->lun, req->tag);
1624     if (!req->enqueued) {
1625         return;
1626     }
1627     scsi_req_ref(req);
1628     scsi_req_dequeue(req);
1629     req->io_canceled = true;
1630     if (req->ops->cancel_io) {
1631         req->ops->cancel_io(req);
1632     }
1633     if (req->bus->info->cancel) {
1634         req->bus->info->cancel(req);
1635     }
1636     scsi_req_unref(req);
1637 }
1638 
1639 void scsi_req_abort(SCSIRequest *req, int status)
1640 {
1641     if (!req->enqueued) {
1642         return;
1643     }
1644     scsi_req_ref(req);
1645     scsi_req_dequeue(req);
1646     req->io_canceled = true;
1647     if (req->ops->cancel_io) {
1648         req->ops->cancel_io(req);
1649     }
1650     scsi_req_complete(req, status);
1651     scsi_req_unref(req);
1652 }
1653 
1654 static int scsi_ua_precedence(SCSISense sense)
1655 {
1656     if (sense.key != UNIT_ATTENTION) {
1657         return INT_MAX;
1658     }
1659     if (sense.asc == 0x29 && sense.ascq == 0x04) {
1660         /* DEVICE INTERNAL RESET goes with POWER ON OCCURRED */
1661         return 1;
1662     } else if (sense.asc == 0x3F && sense.ascq == 0x01) {
1663         /* MICROCODE HAS BEEN CHANGED goes with SCSI BUS RESET OCCURRED */
1664         return 2;
1665     } else if (sense.asc == 0x29 && (sense.ascq == 0x05 || sense.ascq == 0x06)) {
1666         /* These two go with "all others". */
1667         ;
1668     } else if (sense.asc == 0x29 && sense.ascq <= 0x07) {
1669         /* POWER ON, RESET OR BUS DEVICE RESET OCCURRED = 0
1670          * POWER ON OCCURRED = 1
1671          * SCSI BUS RESET OCCURRED = 2
1672          * BUS DEVICE RESET FUNCTION OCCURRED = 3
1673          * I_T NEXUS LOSS OCCURRED = 7
1674          */
1675         return sense.ascq;
1676     } else if (sense.asc == 0x2F && sense.ascq == 0x01) {
1677         /* COMMANDS CLEARED BY POWER LOSS NOTIFICATION  */
1678         return 8;
1679     }
1680     return (sense.asc << 8) | sense.ascq;
1681 }
1682 
1683 void scsi_device_set_ua(SCSIDevice *sdev, SCSISense sense)
1684 {
1685     int prec1, prec2;
1686     if (sense.key != UNIT_ATTENTION) {
1687         return;
1688     }
1689     trace_scsi_device_set_ua(sdev->id, sdev->lun, sense.key,
1690                              sense.asc, sense.ascq);
1691 
1692     /*
1693      * Override a pre-existing unit attention condition, except for a more
1694      * important reset condition.
1695     */
1696     prec1 = scsi_ua_precedence(sdev->unit_attention);
1697     prec2 = scsi_ua_precedence(sense);
1698     if (prec2 < prec1) {
1699         sdev->unit_attention = sense;
1700     }
1701 }
1702 
1703 void scsi_device_purge_requests(SCSIDevice *sdev, SCSISense sense)
1704 {
1705     SCSIRequest *req;
1706 
1707     while (!QTAILQ_EMPTY(&sdev->requests)) {
1708         req = QTAILQ_FIRST(&sdev->requests);
1709         scsi_req_cancel(req);
1710     }
1711 
1712     scsi_device_set_ua(sdev, sense);
1713 }
1714 
1715 static char *scsibus_get_dev_path(DeviceState *dev)
1716 {
1717     SCSIDevice *d = DO_UPCAST(SCSIDevice, qdev, dev);
1718     DeviceState *hba = dev->parent_bus->parent;
1719     char *id;
1720     char *path;
1721 
1722     id = qdev_get_dev_path(hba);
1723     if (id) {
1724         path = g_strdup_printf("%s/%d:%d:%d", id, d->channel, d->id, d->lun);
1725     } else {
1726         path = g_strdup_printf("%d:%d:%d", d->channel, d->id, d->lun);
1727     }
1728     g_free(id);
1729     return path;
1730 }
1731 
1732 static char *scsibus_get_fw_dev_path(DeviceState *dev)
1733 {
1734     SCSIDevice *d = SCSI_DEVICE(dev);
1735     return g_strdup_printf("channel@%x/%s@%x,%x", d->channel,
1736                            qdev_fw_name(dev), d->id, d->lun);
1737 }
1738 
1739 SCSIDevice *scsi_device_find(SCSIBus *bus, int channel, int id, int lun)
1740 {
1741     BusChild *kid;
1742     SCSIDevice *target_dev = NULL;
1743 
1744     QTAILQ_FOREACH_REVERSE(kid, &bus->qbus.children, ChildrenHead, sibling) {
1745         DeviceState *qdev = kid->child;
1746         SCSIDevice *dev = SCSI_DEVICE(qdev);
1747 
1748         if (dev->channel == channel && dev->id == id) {
1749             if (dev->lun == lun) {
1750                 return dev;
1751             }
1752             target_dev = dev;
1753         }
1754     }
1755     return target_dev;
1756 }
1757 
1758 /* SCSI request list.  For simplicity, pv points to the whole device */
1759 
1760 static void put_scsi_requests(QEMUFile *f, void *pv, size_t size)
1761 {
1762     SCSIDevice *s = pv;
1763     SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, s->qdev.parent_bus);
1764     SCSIRequest *req;
1765 
1766     QTAILQ_FOREACH(req, &s->requests, next) {
1767         assert(!req->io_canceled);
1768         assert(req->status == -1);
1769         assert(req->enqueued);
1770 
1771         qemu_put_sbyte(f, req->retry ? 1 : 2);
1772         qemu_put_buffer(f, req->cmd.buf, sizeof(req->cmd.buf));
1773         qemu_put_be32s(f, &req->tag);
1774         qemu_put_be32s(f, &req->lun);
1775         if (bus->info->save_request) {
1776             bus->info->save_request(f, req);
1777         }
1778         if (req->ops->save_request) {
1779             req->ops->save_request(f, req);
1780         }
1781     }
1782     qemu_put_sbyte(f, 0);
1783 }
1784 
1785 static int get_scsi_requests(QEMUFile *f, void *pv, size_t size)
1786 {
1787     SCSIDevice *s = pv;
1788     SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, s->qdev.parent_bus);
1789     int8_t sbyte;
1790 
1791     while ((sbyte = qemu_get_sbyte(f)) > 0) {
1792         uint8_t buf[SCSI_CMD_BUF_SIZE];
1793         uint32_t tag;
1794         uint32_t lun;
1795         SCSIRequest *req;
1796 
1797         qemu_get_buffer(f, buf, sizeof(buf));
1798         qemu_get_be32s(f, &tag);
1799         qemu_get_be32s(f, &lun);
1800         req = scsi_req_new(s, tag, lun, buf, NULL);
1801         req->retry = (sbyte == 1);
1802         if (bus->info->load_request) {
1803             req->hba_private = bus->info->load_request(f, req);
1804         }
1805         if (req->ops->load_request) {
1806             req->ops->load_request(f, req);
1807         }
1808 
1809         /* Just restart it later.  */
1810         scsi_req_enqueue_internal(req);
1811 
1812         /* At this point, the request will be kept alive by the reference
1813          * added by scsi_req_enqueue_internal, so we can release our reference.
1814          * The HBA of course will add its own reference in the load_request
1815          * callback if it needs to hold on the SCSIRequest.
1816          */
1817         scsi_req_unref(req);
1818     }
1819 
1820     return 0;
1821 }
1822 
1823 static int scsi_qdev_unplug(DeviceState *qdev)
1824 {
1825     SCSIDevice *dev = SCSI_DEVICE(qdev);
1826     SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus);
1827 
1828     if (bus->info->hot_unplug) {
1829         bus->info->hot_unplug(bus, dev);
1830     }
1831     return qdev_simple_unplug_cb(qdev);
1832 }
1833 
1834 static const VMStateInfo vmstate_info_scsi_requests = {
1835     .name = "scsi-requests",
1836     .get  = get_scsi_requests,
1837     .put  = put_scsi_requests,
1838 };
1839 
1840 const VMStateDescription vmstate_scsi_device = {
1841     .name = "SCSIDevice",
1842     .version_id = 1,
1843     .minimum_version_id = 1,
1844     .minimum_version_id_old = 1,
1845     .fields = (VMStateField[]) {
1846         VMSTATE_UINT8(unit_attention.key, SCSIDevice),
1847         VMSTATE_UINT8(unit_attention.asc, SCSIDevice),
1848         VMSTATE_UINT8(unit_attention.ascq, SCSIDevice),
1849         VMSTATE_BOOL(sense_is_ua, SCSIDevice),
1850         VMSTATE_UINT8_ARRAY(sense, SCSIDevice, SCSI_SENSE_BUF_SIZE),
1851         VMSTATE_UINT32(sense_len, SCSIDevice),
1852         {
1853             .name         = "requests",
1854             .version_id   = 0,
1855             .field_exists = NULL,
1856             .size         = 0,   /* ouch */
1857             .info         = &vmstate_info_scsi_requests,
1858             .flags        = VMS_SINGLE,
1859             .offset       = 0,
1860         },
1861         VMSTATE_END_OF_LIST()
1862     }
1863 };
1864 
1865 static void scsi_device_class_init(ObjectClass *klass, void *data)
1866 {
1867     DeviceClass *k = DEVICE_CLASS(klass);
1868     k->bus_type = TYPE_SCSI_BUS;
1869     k->init     = scsi_qdev_init;
1870     k->unplug   = scsi_qdev_unplug;
1871     k->exit     = scsi_qdev_exit;
1872     k->props    = scsi_props;
1873 }
1874 
1875 static const TypeInfo scsi_device_type_info = {
1876     .name = TYPE_SCSI_DEVICE,
1877     .parent = TYPE_DEVICE,
1878     .instance_size = sizeof(SCSIDevice),
1879     .abstract = true,
1880     .class_size = sizeof(SCSIDeviceClass),
1881     .class_init = scsi_device_class_init,
1882 };
1883 
1884 static void scsi_register_types(void)
1885 {
1886     type_register_static(&scsi_bus_info);
1887     type_register_static(&scsi_device_type_info);
1888 }
1889 
1890 type_init(scsi_register_types)
1891