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