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