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