xref: /openbmc/qemu/hw/usb/dev-storage.c (revision 489653b5)
1 /*
2  * USB Mass Storage Device emulation
3  *
4  * Copyright (c) 2006 CodeSourcery.
5  * Written by Paul Brook
6  *
7  * This code is licensed under the LGPL.
8  */
9 
10 #include "qemu-common.h"
11 #include "qemu/option.h"
12 #include "qemu/config-file.h"
13 #include "hw/usb.h"
14 #include "hw/usb/desc.h"
15 #include "hw/scsi/scsi.h"
16 #include "ui/console.h"
17 #include "monitor/monitor.h"
18 #include "sysemu/sysemu.h"
19 #include "sysemu/block-backend.h"
20 #include "sysemu/blockdev.h"
21 #include "qapi/visitor.h"
22 
23 //#define DEBUG_MSD
24 
25 #ifdef DEBUG_MSD
26 #define DPRINTF(fmt, ...) \
27 do { printf("usb-msd: " fmt , ## __VA_ARGS__); } while (0)
28 #else
29 #define DPRINTF(fmt, ...) do {} while(0)
30 #endif
31 
32 /* USB requests.  */
33 #define MassStorageReset  0xff
34 #define GetMaxLun         0xfe
35 
36 enum USBMSDMode {
37     USB_MSDM_CBW, /* Command Block.  */
38     USB_MSDM_DATAOUT, /* Transfer data to device.  */
39     USB_MSDM_DATAIN, /* Transfer data from device.  */
40     USB_MSDM_CSW /* Command Status.  */
41 };
42 
43 struct usb_msd_csw {
44     uint32_t sig;
45     uint32_t tag;
46     uint32_t residue;
47     uint8_t status;
48 };
49 
50 typedef struct {
51     USBDevice dev;
52     enum USBMSDMode mode;
53     uint32_t scsi_off;
54     uint32_t scsi_len;
55     uint32_t data_len;
56     struct usb_msd_csw csw;
57     SCSIRequest *req;
58     SCSIBus bus;
59     /* For async completion.  */
60     USBPacket *packet;
61     /* usb-storage only */
62     BlockConf conf;
63     uint32_t removable;
64     SCSIDevice *scsi_dev;
65 } MSDState;
66 
67 #define TYPE_USB_STORAGE "usb-storage-dev"
68 #define USB_STORAGE_DEV(obj) OBJECT_CHECK(MSDState, (obj), TYPE_USB_STORAGE)
69 
70 struct usb_msd_cbw {
71     uint32_t sig;
72     uint32_t tag;
73     uint32_t data_len;
74     uint8_t flags;
75     uint8_t lun;
76     uint8_t cmd_len;
77     uint8_t cmd[16];
78 };
79 
80 enum {
81     STR_MANUFACTURER = 1,
82     STR_PRODUCT,
83     STR_SERIALNUMBER,
84     STR_CONFIG_FULL,
85     STR_CONFIG_HIGH,
86     STR_CONFIG_SUPER,
87 };
88 
89 static const USBDescStrings desc_strings = {
90     [STR_MANUFACTURER] = "QEMU",
91     [STR_PRODUCT]      = "QEMU USB HARDDRIVE",
92     [STR_SERIALNUMBER] = "1",
93     [STR_CONFIG_FULL]  = "Full speed config (usb 1.1)",
94     [STR_CONFIG_HIGH]  = "High speed config (usb 2.0)",
95     [STR_CONFIG_SUPER] = "Super speed config (usb 3.0)",
96 };
97 
98 static const USBDescIface desc_iface_full = {
99     .bInterfaceNumber              = 0,
100     .bNumEndpoints                 = 2,
101     .bInterfaceClass               = USB_CLASS_MASS_STORAGE,
102     .bInterfaceSubClass            = 0x06, /* SCSI */
103     .bInterfaceProtocol            = 0x50, /* Bulk */
104     .eps = (USBDescEndpoint[]) {
105         {
106             .bEndpointAddress      = USB_DIR_IN | 0x01,
107             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
108             .wMaxPacketSize        = 64,
109         },{
110             .bEndpointAddress      = USB_DIR_OUT | 0x02,
111             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
112             .wMaxPacketSize        = 64,
113         },
114     }
115 };
116 
117 static const USBDescDevice desc_device_full = {
118     .bcdUSB                        = 0x0200,
119     .bMaxPacketSize0               = 8,
120     .bNumConfigurations            = 1,
121     .confs = (USBDescConfig[]) {
122         {
123             .bNumInterfaces        = 1,
124             .bConfigurationValue   = 1,
125             .iConfiguration        = STR_CONFIG_FULL,
126             .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_SELFPOWER,
127             .nif = 1,
128             .ifs = &desc_iface_full,
129         },
130     },
131 };
132 
133 static const USBDescIface desc_iface_high = {
134     .bInterfaceNumber              = 0,
135     .bNumEndpoints                 = 2,
136     .bInterfaceClass               = USB_CLASS_MASS_STORAGE,
137     .bInterfaceSubClass            = 0x06, /* SCSI */
138     .bInterfaceProtocol            = 0x50, /* Bulk */
139     .eps = (USBDescEndpoint[]) {
140         {
141             .bEndpointAddress      = USB_DIR_IN | 0x01,
142             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
143             .wMaxPacketSize        = 512,
144         },{
145             .bEndpointAddress      = USB_DIR_OUT | 0x02,
146             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
147             .wMaxPacketSize        = 512,
148         },
149     }
150 };
151 
152 static const USBDescDevice desc_device_high = {
153     .bcdUSB                        = 0x0200,
154     .bMaxPacketSize0               = 64,
155     .bNumConfigurations            = 1,
156     .confs = (USBDescConfig[]) {
157         {
158             .bNumInterfaces        = 1,
159             .bConfigurationValue   = 1,
160             .iConfiguration        = STR_CONFIG_HIGH,
161             .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_SELFPOWER,
162             .nif = 1,
163             .ifs = &desc_iface_high,
164         },
165     },
166 };
167 
168 static const USBDescIface desc_iface_super = {
169     .bInterfaceNumber              = 0,
170     .bNumEndpoints                 = 2,
171     .bInterfaceClass               = USB_CLASS_MASS_STORAGE,
172     .bInterfaceSubClass            = 0x06, /* SCSI */
173     .bInterfaceProtocol            = 0x50, /* Bulk */
174     .eps = (USBDescEndpoint[]) {
175         {
176             .bEndpointAddress      = USB_DIR_IN | 0x01,
177             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
178             .wMaxPacketSize        = 1024,
179             .bMaxBurst             = 15,
180         },{
181             .bEndpointAddress      = USB_DIR_OUT | 0x02,
182             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
183             .wMaxPacketSize        = 1024,
184             .bMaxBurst             = 15,
185         },
186     }
187 };
188 
189 static const USBDescDevice desc_device_super = {
190     .bcdUSB                        = 0x0300,
191     .bMaxPacketSize0               = 9,
192     .bNumConfigurations            = 1,
193     .confs = (USBDescConfig[]) {
194         {
195             .bNumInterfaces        = 1,
196             .bConfigurationValue   = 1,
197             .iConfiguration        = STR_CONFIG_SUPER,
198             .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_SELFPOWER,
199             .nif = 1,
200             .ifs = &desc_iface_super,
201         },
202     },
203 };
204 
205 static const USBDesc desc = {
206     .id = {
207         .idVendor          = 0x46f4, /* CRC16() of "QEMU" */
208         .idProduct         = 0x0001,
209         .bcdDevice         = 0,
210         .iManufacturer     = STR_MANUFACTURER,
211         .iProduct          = STR_PRODUCT,
212         .iSerialNumber     = STR_SERIALNUMBER,
213     },
214     .full  = &desc_device_full,
215     .high  = &desc_device_high,
216     .super = &desc_device_super,
217     .str   = desc_strings,
218 };
219 
220 static void usb_msd_copy_data(MSDState *s, USBPacket *p)
221 {
222     uint32_t len;
223     len = p->iov.size - p->actual_length;
224     if (len > s->scsi_len)
225         len = s->scsi_len;
226     usb_packet_copy(p, scsi_req_get_buf(s->req) + s->scsi_off, len);
227     s->scsi_len -= len;
228     s->scsi_off += len;
229     s->data_len -= len;
230     if (s->scsi_len == 0 || s->data_len == 0) {
231         scsi_req_continue(s->req);
232     }
233 }
234 
235 static void usb_msd_send_status(MSDState *s, USBPacket *p)
236 {
237     int len;
238 
239     DPRINTF("Command status %d tag 0x%x, len %zd\n",
240             s->csw.status, le32_to_cpu(s->csw.tag), p->iov.size);
241 
242     assert(s->csw.sig == cpu_to_le32(0x53425355));
243     len = MIN(sizeof(s->csw), p->iov.size);
244     usb_packet_copy(p, &s->csw, len);
245     memset(&s->csw, 0, sizeof(s->csw));
246 }
247 
248 static void usb_msd_packet_complete(MSDState *s)
249 {
250     USBPacket *p = s->packet;
251 
252     /* Set s->packet to NULL before calling usb_packet_complete
253        because another request may be issued before
254        usb_packet_complete returns.  */
255     DPRINTF("Packet complete %p\n", p);
256     s->packet = NULL;
257     usb_packet_complete(&s->dev, p);
258 }
259 
260 static void usb_msd_transfer_data(SCSIRequest *req, uint32_t len)
261 {
262     MSDState *s = DO_UPCAST(MSDState, dev.qdev, req->bus->qbus.parent);
263     USBPacket *p = s->packet;
264 
265     assert((s->mode == USB_MSDM_DATAOUT) == (req->cmd.mode == SCSI_XFER_TO_DEV));
266     s->scsi_len = len;
267     s->scsi_off = 0;
268     if (p) {
269         usb_msd_copy_data(s, p);
270         p = s->packet;
271         if (p && p->actual_length == p->iov.size) {
272             p->status = USB_RET_SUCCESS; /* Clear previous ASYNC status */
273             usb_msd_packet_complete(s);
274         }
275     }
276 }
277 
278 static void usb_msd_command_complete(SCSIRequest *req, uint32_t status, size_t resid)
279 {
280     MSDState *s = DO_UPCAST(MSDState, dev.qdev, req->bus->qbus.parent);
281     USBPacket *p = s->packet;
282 
283     DPRINTF("Command complete %d tag 0x%x\n", status, req->tag);
284 
285     s->csw.sig = cpu_to_le32(0x53425355);
286     s->csw.tag = cpu_to_le32(req->tag);
287     s->csw.residue = cpu_to_le32(s->data_len);
288     s->csw.status = status != 0;
289 
290     if (s->packet) {
291         if (s->data_len == 0 && s->mode == USB_MSDM_DATAOUT) {
292             /* A deferred packet with no write data remaining must be
293                the status read packet.  */
294             usb_msd_send_status(s, p);
295             s->mode = USB_MSDM_CBW;
296         } else if (s->mode == USB_MSDM_CSW) {
297             usb_msd_send_status(s, p);
298             s->mode = USB_MSDM_CBW;
299         } else {
300             if (s->data_len) {
301                 int len = (p->iov.size - p->actual_length);
302                 usb_packet_skip(p, len);
303                 s->data_len -= len;
304             }
305             if (s->data_len == 0) {
306                 s->mode = USB_MSDM_CSW;
307             }
308         }
309         p->status = USB_RET_SUCCESS; /* Clear previous ASYNC status */
310         usb_msd_packet_complete(s);
311     } else if (s->data_len == 0) {
312         s->mode = USB_MSDM_CSW;
313     }
314     scsi_req_unref(req);
315     s->req = NULL;
316 }
317 
318 static void usb_msd_request_cancelled(SCSIRequest *req)
319 {
320     MSDState *s = DO_UPCAST(MSDState, dev.qdev, req->bus->qbus.parent);
321 
322     if (req == s->req) {
323         scsi_req_unref(s->req);
324         s->req = NULL;
325         s->scsi_len = 0;
326     }
327 }
328 
329 static void usb_msd_handle_reset(USBDevice *dev)
330 {
331     MSDState *s = (MSDState *)dev;
332 
333     DPRINTF("Reset\n");
334     if (s->req) {
335         scsi_req_cancel(s->req);
336     }
337     assert(s->req == NULL);
338 
339     if (s->packet) {
340         s->packet->status = USB_RET_STALL;
341         usb_msd_packet_complete(s);
342     }
343 
344     s->mode = USB_MSDM_CBW;
345 }
346 
347 static void usb_msd_handle_control(USBDevice *dev, USBPacket *p,
348                int request, int value, int index, int length, uint8_t *data)
349 {
350     MSDState *s = (MSDState *)dev;
351     SCSIDevice *scsi_dev;
352     int ret, maxlun;
353 
354     ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
355     if (ret >= 0) {
356         return;
357     }
358 
359     switch (request) {
360     case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
361         break;
362         /* Class specific requests.  */
363     case ClassInterfaceOutRequest | MassStorageReset:
364         /* Reset state ready for the next CBW.  */
365         s->mode = USB_MSDM_CBW;
366         break;
367     case ClassInterfaceRequest | GetMaxLun:
368         maxlun = 0;
369         for (;;) {
370             scsi_dev = scsi_device_find(&s->bus, 0, 0, maxlun+1);
371             if (scsi_dev == NULL) {
372                 break;
373             }
374             if (scsi_dev->lun != maxlun+1) {
375                 break;
376             }
377             maxlun++;
378         }
379         DPRINTF("MaxLun %d\n", maxlun);
380         data[0] = maxlun;
381         p->actual_length = 1;
382         break;
383     default:
384         p->status = USB_RET_STALL;
385         break;
386     }
387 }
388 
389 static void usb_msd_cancel_io(USBDevice *dev, USBPacket *p)
390 {
391     MSDState *s = USB_STORAGE_DEV(dev);
392 
393     assert(s->packet == p);
394     s->packet = NULL;
395 
396     if (s->req) {
397         scsi_req_cancel(s->req);
398     }
399 }
400 
401 static void usb_msd_handle_data(USBDevice *dev, USBPacket *p)
402 {
403     MSDState *s = (MSDState *)dev;
404     uint32_t tag;
405     struct usb_msd_cbw cbw;
406     uint8_t devep = p->ep->nr;
407     SCSIDevice *scsi_dev;
408     uint32_t len;
409 
410     switch (p->pid) {
411     case USB_TOKEN_OUT:
412         if (devep != 2)
413             goto fail;
414 
415         switch (s->mode) {
416         case USB_MSDM_CBW:
417             if (p->iov.size != 31) {
418                 error_report("usb-msd: Bad CBW size");
419                 goto fail;
420             }
421             usb_packet_copy(p, &cbw, 31);
422             if (le32_to_cpu(cbw.sig) != 0x43425355) {
423                 error_report("usb-msd: Bad signature %08x",
424                              le32_to_cpu(cbw.sig));
425                 goto fail;
426             }
427             DPRINTF("Command on LUN %d\n", cbw.lun);
428             scsi_dev = scsi_device_find(&s->bus, 0, 0, cbw.lun);
429             if (scsi_dev == NULL) {
430                 error_report("usb-msd: Bad LUN %d", cbw.lun);
431                 goto fail;
432             }
433             tag = le32_to_cpu(cbw.tag);
434             s->data_len = le32_to_cpu(cbw.data_len);
435             if (s->data_len == 0) {
436                 s->mode = USB_MSDM_CSW;
437             } else if (cbw.flags & 0x80) {
438                 s->mode = USB_MSDM_DATAIN;
439             } else {
440                 s->mode = USB_MSDM_DATAOUT;
441             }
442             DPRINTF("Command tag 0x%x flags %08x len %d data %d\n",
443                     tag, cbw.flags, cbw.cmd_len, s->data_len);
444             assert(le32_to_cpu(s->csw.residue) == 0);
445             s->scsi_len = 0;
446             s->req = scsi_req_new(scsi_dev, tag, cbw.lun, cbw.cmd, NULL);
447 #ifdef DEBUG_MSD
448             scsi_req_print(s->req);
449 #endif
450             len = scsi_req_enqueue(s->req);
451             if (len) {
452                 scsi_req_continue(s->req);
453             }
454             break;
455 
456         case USB_MSDM_DATAOUT:
457             DPRINTF("Data out %zd/%d\n", p->iov.size, s->data_len);
458             if (p->iov.size > s->data_len) {
459                 goto fail;
460             }
461 
462             if (s->scsi_len) {
463                 usb_msd_copy_data(s, p);
464             }
465             if (le32_to_cpu(s->csw.residue)) {
466                 int len = p->iov.size - p->actual_length;
467                 if (len) {
468                     usb_packet_skip(p, len);
469                     s->data_len -= len;
470                     if (s->data_len == 0) {
471                         s->mode = USB_MSDM_CSW;
472                     }
473                 }
474             }
475             if (p->actual_length < p->iov.size) {
476                 DPRINTF("Deferring packet %p [wait data-out]\n", p);
477                 s->packet = p;
478                 p->status = USB_RET_ASYNC;
479             }
480             break;
481 
482         default:
483             DPRINTF("Unexpected write (len %zd)\n", p->iov.size);
484             goto fail;
485         }
486         break;
487 
488     case USB_TOKEN_IN:
489         if (devep != 1)
490             goto fail;
491 
492         switch (s->mode) {
493         case USB_MSDM_DATAOUT:
494             if (s->data_len != 0 || p->iov.size < 13) {
495                 goto fail;
496             }
497             /* Waiting for SCSI write to complete.  */
498             s->packet = p;
499             p->status = USB_RET_ASYNC;
500             break;
501 
502         case USB_MSDM_CSW:
503             if (p->iov.size < 13) {
504                 goto fail;
505             }
506 
507             if (s->req) {
508                 /* still in flight */
509                 DPRINTF("Deferring packet %p [wait status]\n", p);
510                 s->packet = p;
511                 p->status = USB_RET_ASYNC;
512             } else {
513                 usb_msd_send_status(s, p);
514                 s->mode = USB_MSDM_CBW;
515             }
516             break;
517 
518         case USB_MSDM_DATAIN:
519             DPRINTF("Data in %zd/%d, scsi_len %d\n",
520                     p->iov.size, s->data_len, s->scsi_len);
521             if (s->scsi_len) {
522                 usb_msd_copy_data(s, p);
523             }
524             if (le32_to_cpu(s->csw.residue)) {
525                 int len = p->iov.size - p->actual_length;
526                 if (len) {
527                     usb_packet_skip(p, len);
528                     s->data_len -= len;
529                     if (s->data_len == 0) {
530                         s->mode = USB_MSDM_CSW;
531                     }
532                 }
533             }
534             if (p->actual_length < p->iov.size) {
535                 DPRINTF("Deferring packet %p [wait data-in]\n", p);
536                 s->packet = p;
537                 p->status = USB_RET_ASYNC;
538             }
539             break;
540 
541         default:
542             DPRINTF("Unexpected read (len %zd)\n", p->iov.size);
543             goto fail;
544         }
545         break;
546 
547     default:
548         DPRINTF("Bad token\n");
549     fail:
550         p->status = USB_RET_STALL;
551         break;
552     }
553 }
554 
555 static void usb_msd_password_cb(void *opaque, int err)
556 {
557     MSDState *s = opaque;
558     Error *local_err = NULL;
559 
560     if (!err) {
561         usb_device_attach(&s->dev, &local_err);
562     }
563 
564     if (local_err) {
565         error_report_err(local_err);
566         qdev_unplug(&s->dev.qdev, NULL);
567     }
568 }
569 
570 static void *usb_msd_load_request(QEMUFile *f, SCSIRequest *req)
571 {
572     MSDState *s = DO_UPCAST(MSDState, dev.qdev, req->bus->qbus.parent);
573 
574     /* nothing to load, just store req in our state struct */
575     assert(s->req == NULL);
576     scsi_req_ref(req);
577     s->req = req;
578     return NULL;
579 }
580 
581 static const struct SCSIBusInfo usb_msd_scsi_info_storage = {
582     .tcq = false,
583     .max_target = 0,
584     .max_lun = 0,
585 
586     .transfer_data = usb_msd_transfer_data,
587     .complete = usb_msd_command_complete,
588     .cancel = usb_msd_request_cancelled,
589     .load_request = usb_msd_load_request,
590 };
591 
592 static const struct SCSIBusInfo usb_msd_scsi_info_bot = {
593     .tcq = false,
594     .max_target = 0,
595     .max_lun = 15,
596 
597     .transfer_data = usb_msd_transfer_data,
598     .complete = usb_msd_command_complete,
599     .cancel = usb_msd_request_cancelled,
600     .load_request = usb_msd_load_request,
601 };
602 
603 static void usb_msd_realize_storage(USBDevice *dev, Error **errp)
604 {
605     MSDState *s = USB_STORAGE_DEV(dev);
606     BlockBackend *blk = s->conf.blk;
607     SCSIDevice *scsi_dev;
608     Error *err = NULL;
609 
610     if (!blk) {
611         error_setg(errp, "drive property not set");
612         return;
613     }
614 
615     bdrv_add_key(blk_bs(blk), NULL, &err);
616     if (err) {
617         if (monitor_cur_is_qmp()) {
618             error_propagate(errp, err);
619             return;
620         }
621         error_free(err);
622         err = NULL;
623         if (cur_mon) {
624             monitor_read_bdrv_key_start(cur_mon, blk_bs(blk),
625                                         usb_msd_password_cb, s);
626             s->dev.auto_attach = 0;
627         } else {
628             autostart = 0;
629         }
630     }
631 
632     blkconf_serial(&s->conf, &dev->serial);
633     blkconf_blocksizes(&s->conf);
634 
635     /*
636      * Hack alert: this pretends to be a block device, but it's really
637      * a SCSI bus that can serve only a single device, which it
638      * creates automatically.  But first it needs to detach from its
639      * blockdev, or else scsi_bus_legacy_add_drive() dies when it
640      * attaches again.
641      *
642      * The hack is probably a bad idea.
643      */
644     blk_detach_dev(blk, &s->dev.qdev);
645     s->conf.blk = NULL;
646 
647     usb_desc_create_serial(dev);
648     usb_desc_init(dev);
649     scsi_bus_new(&s->bus, sizeof(s->bus), DEVICE(dev),
650                  &usb_msd_scsi_info_storage, NULL);
651     scsi_dev = scsi_bus_legacy_add_drive(&s->bus, blk, 0, !!s->removable,
652                                          s->conf.bootindex, dev->serial,
653                                          &err);
654     if (!scsi_dev) {
655         error_propagate(errp, err);
656         return;
657     }
658     usb_msd_handle_reset(dev);
659     s->scsi_dev = scsi_dev;
660 }
661 
662 static void usb_msd_realize_bot(USBDevice *dev, Error **errp)
663 {
664     MSDState *s = USB_STORAGE_DEV(dev);
665 
666     usb_desc_create_serial(dev);
667     usb_desc_init(dev);
668     scsi_bus_new(&s->bus, sizeof(s->bus), DEVICE(dev),
669                  &usb_msd_scsi_info_bot, NULL);
670     usb_msd_handle_reset(dev);
671 }
672 
673 static USBDevice *usb_msd_init(USBBus *bus, const char *filename)
674 {
675     static int nr=0;
676     Error *err = NULL;
677     char id[8];
678     QemuOpts *opts;
679     DriveInfo *dinfo;
680     USBDevice *dev;
681     const char *p1;
682     char fmt[32];
683 
684     /* parse -usbdevice disk: syntax into drive opts */
685     do {
686         snprintf(id, sizeof(id), "usb%d", nr++);
687         opts = qemu_opts_create(qemu_find_opts("drive"), id, 1, NULL);
688     } while (!opts);
689 
690     p1 = strchr(filename, ':');
691     if (p1++) {
692         const char *p2;
693 
694         if (strstart(filename, "format=", &p2)) {
695             int len = MIN(p1 - p2, sizeof(fmt));
696             pstrcpy(fmt, len, p2);
697             qemu_opt_set(opts, "format", fmt, &error_abort);
698         } else if (*filename != ':') {
699             error_report("unrecognized USB mass-storage option %s", filename);
700             return NULL;
701         }
702         filename = p1;
703     }
704     if (!*filename) {
705         error_report("block device specification needed");
706         return NULL;
707     }
708     qemu_opt_set(opts, "file", filename, &error_abort);
709     qemu_opt_set(opts, "if", "none", &error_abort);
710 
711     /* create host drive */
712     dinfo = drive_new(opts, 0);
713     if (!dinfo) {
714         qemu_opts_del(opts);
715         return NULL;
716     }
717 
718     /* create guest device */
719     dev = usb_create(bus, "usb-storage");
720     qdev_prop_set_drive(&dev->qdev, "drive", blk_by_legacy_dinfo(dinfo),
721                         &err);
722     if (err) {
723         error_report_err(err);
724         object_unparent(OBJECT(dev));
725         return NULL;
726     }
727     return dev;
728 }
729 
730 static const VMStateDescription vmstate_usb_msd = {
731     .name = "usb-storage",
732     .version_id = 1,
733     .minimum_version_id = 1,
734     .fields = (VMStateField[]) {
735         VMSTATE_USB_DEVICE(dev, MSDState),
736         VMSTATE_UINT32(mode, MSDState),
737         VMSTATE_UINT32(scsi_len, MSDState),
738         VMSTATE_UINT32(scsi_off, MSDState),
739         VMSTATE_UINT32(data_len, MSDState),
740         VMSTATE_UINT32(csw.sig, MSDState),
741         VMSTATE_UINT32(csw.tag, MSDState),
742         VMSTATE_UINT32(csw.residue, MSDState),
743         VMSTATE_UINT8(csw.status, MSDState),
744         VMSTATE_END_OF_LIST()
745     }
746 };
747 
748 static Property msd_properties[] = {
749     DEFINE_BLOCK_PROPERTIES(MSDState, conf),
750     DEFINE_PROP_BIT("removable", MSDState, removable, 0, false),
751     DEFINE_PROP_END_OF_LIST(),
752 };
753 
754 static void usb_msd_class_initfn_common(ObjectClass *klass, void *data)
755 {
756     DeviceClass *dc = DEVICE_CLASS(klass);
757     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
758 
759     uc->product_desc   = "QEMU USB MSD";
760     uc->usb_desc       = &desc;
761     uc->cancel_packet  = usb_msd_cancel_io;
762     uc->handle_attach  = usb_desc_attach;
763     uc->handle_reset   = usb_msd_handle_reset;
764     uc->handle_control = usb_msd_handle_control;
765     uc->handle_data    = usb_msd_handle_data;
766     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
767     dc->fw_name = "storage";
768     dc->vmsd = &vmstate_usb_msd;
769 }
770 
771 static void usb_msd_class_initfn_storage(ObjectClass *klass, void *data)
772 {
773     DeviceClass *dc = DEVICE_CLASS(klass);
774     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
775 
776     uc->realize = usb_msd_realize_storage;
777     dc->props = msd_properties;
778 }
779 
780 static void usb_msd_get_bootindex(Object *obj, Visitor *v, void *opaque,
781                                   const char *name, Error **errp)
782 {
783     USBDevice *dev = USB_DEVICE(obj);
784     MSDState *s = USB_STORAGE_DEV(dev);
785 
786     visit_type_int32(v, &s->conf.bootindex, name, errp);
787 }
788 
789 static void usb_msd_set_bootindex(Object *obj, Visitor *v, void *opaque,
790                                   const char *name, Error **errp)
791 {
792     USBDevice *dev = USB_DEVICE(obj);
793     MSDState *s = USB_STORAGE_DEV(dev);
794     int32_t boot_index;
795     Error *local_err = NULL;
796 
797     visit_type_int32(v, &boot_index, name, &local_err);
798     if (local_err) {
799         goto out;
800     }
801     /* check whether bootindex is present in fw_boot_order list  */
802     check_boot_index(boot_index, &local_err);
803     if (local_err) {
804         goto out;
805     }
806     /* change bootindex to a new one */
807     s->conf.bootindex = boot_index;
808 
809     if (s->scsi_dev) {
810         object_property_set_int(OBJECT(s->scsi_dev), boot_index, "bootindex",
811                                 &error_abort);
812     }
813 
814 out:
815     if (local_err) {
816         error_propagate(errp, local_err);
817     }
818 }
819 
820 static const TypeInfo usb_storage_dev_type_info = {
821     .name = TYPE_USB_STORAGE,
822     .parent = TYPE_USB_DEVICE,
823     .instance_size = sizeof(MSDState),
824     .abstract = true,
825     .class_init = usb_msd_class_initfn_common,
826 };
827 
828 static void usb_msd_instance_init(Object *obj)
829 {
830     object_property_add(obj, "bootindex", "int32",
831                         usb_msd_get_bootindex,
832                         usb_msd_set_bootindex, NULL, NULL, NULL);
833     object_property_set_int(obj, -1, "bootindex", NULL);
834 }
835 
836 static void usb_msd_class_initfn_bot(ObjectClass *klass, void *data)
837 {
838     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
839     DeviceClass *dc = DEVICE_CLASS(klass);
840 
841     uc->realize = usb_msd_realize_bot;
842     dc->hotpluggable = false;
843 }
844 
845 static const TypeInfo msd_info = {
846     .name          = "usb-storage",
847     .parent        = TYPE_USB_STORAGE,
848     .class_init    = usb_msd_class_initfn_storage,
849     .instance_init = usb_msd_instance_init,
850 };
851 
852 static const TypeInfo bot_info = {
853     .name          = "usb-bot",
854     .parent        = TYPE_USB_STORAGE,
855     .class_init    = usb_msd_class_initfn_bot,
856 };
857 
858 static void usb_msd_register_types(void)
859 {
860     type_register_static(&usb_storage_dev_type_info);
861     type_register_static(&msd_info);
862     type_register_static(&bot_info);
863     usb_legacy_register("usb-storage", "disk", usb_msd_init);
864 }
865 
866 type_init(usb_msd_register_types)
867