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