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