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