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