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