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