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