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