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