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