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