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