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