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