]> Git Repo - qemu.git/blob - hw/usb-msd.c
usb-storage: fill status in complete callback.
[qemu.git] / hw / usb-msd.c
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.h"
13 #include "usb.h"
14 #include "usb-desc.h"
15 #include "scsi.h"
16 #include "console.h"
17 #include "monitor.h"
18 #include "sysemu.h"
19 #include "blockdev.h"
20
21 //#define DEBUG_MSD
22
23 #ifdef DEBUG_MSD
24 #define DPRINTF(fmt, ...) \
25 do { printf("usb-msd: " fmt , ## __VA_ARGS__); } while (0)
26 #else
27 #define DPRINTF(fmt, ...) do {} while(0)
28 #endif
29
30 /* USB requests.  */
31 #define MassStorageReset  0xff
32 #define GetMaxLun         0xfe
33
34 enum USBMSDMode {
35     USB_MSDM_CBW, /* Command Block.  */
36     USB_MSDM_DATAOUT, /* Transfer data to device.  */
37     USB_MSDM_DATAIN, /* Transfer data from device.  */
38     USB_MSDM_CSW /* Command Status.  */
39 };
40
41 struct usb_msd_csw {
42     uint32_t sig;
43     uint32_t tag;
44     uint32_t residue;
45     uint8_t status;
46 };
47
48 typedef struct {
49     USBDevice dev;
50     enum USBMSDMode mode;
51     uint32_t scsi_len;
52     uint8_t *scsi_buf;
53     uint32_t data_len;
54     uint32_t residue;
55     uint32_t tag;
56     struct usb_msd_csw csw;
57     SCSIRequest *req;
58     SCSIBus bus;
59     BlockConf conf;
60     char *serial;
61     SCSIDevice *scsi_dev;
62     uint32_t removable;
63     int result;
64     /* For async completion.  */
65     USBPacket *packet;
66 } MSDState;
67
68 struct usb_msd_cbw {
69     uint32_t sig;
70     uint32_t tag;
71     uint32_t data_len;
72     uint8_t flags;
73     uint8_t lun;
74     uint8_t cmd_len;
75     uint8_t cmd[16];
76 };
77
78 enum {
79     STR_MANUFACTURER = 1,
80     STR_PRODUCT,
81     STR_SERIALNUMBER,
82     STR_CONFIG_FULL,
83     STR_CONFIG_HIGH,
84 };
85
86 static const USBDescStrings desc_strings = {
87     [STR_MANUFACTURER] = "QEMU " QEMU_VERSION,
88     [STR_PRODUCT]      = "QEMU USB HARDDRIVE",
89     [STR_SERIALNUMBER] = "1",
90     [STR_CONFIG_FULL]  = "Full speed config (usb 1.1)",
91     [STR_CONFIG_HIGH]  = "High speed config (usb 2.0)",
92 };
93
94 static const USBDescIface desc_iface_full = {
95     .bInterfaceNumber              = 0,
96     .bNumEndpoints                 = 2,
97     .bInterfaceClass               = USB_CLASS_MASS_STORAGE,
98     .bInterfaceSubClass            = 0x06, /* SCSI */
99     .bInterfaceProtocol            = 0x50, /* Bulk */
100     .eps = (USBDescEndpoint[]) {
101         {
102             .bEndpointAddress      = USB_DIR_IN | 0x01,
103             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
104             .wMaxPacketSize        = 64,
105         },{
106             .bEndpointAddress      = USB_DIR_OUT | 0x02,
107             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
108             .wMaxPacketSize        = 64,
109         },
110     }
111 };
112
113 static const USBDescDevice desc_device_full = {
114     .bcdUSB                        = 0x0200,
115     .bMaxPacketSize0               = 8,
116     .bNumConfigurations            = 1,
117     .confs = (USBDescConfig[]) {
118         {
119             .bNumInterfaces        = 1,
120             .bConfigurationValue   = 1,
121             .iConfiguration        = STR_CONFIG_FULL,
122             .bmAttributes          = 0xc0,
123             .nif = 1,
124             .ifs = &desc_iface_full,
125         },
126     },
127 };
128
129 static const USBDescIface desc_iface_high = {
130     .bInterfaceNumber              = 0,
131     .bNumEndpoints                 = 2,
132     .bInterfaceClass               = USB_CLASS_MASS_STORAGE,
133     .bInterfaceSubClass            = 0x06, /* SCSI */
134     .bInterfaceProtocol            = 0x50, /* Bulk */
135     .eps = (USBDescEndpoint[]) {
136         {
137             .bEndpointAddress      = USB_DIR_IN | 0x01,
138             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
139             .wMaxPacketSize        = 512,
140         },{
141             .bEndpointAddress      = USB_DIR_OUT | 0x02,
142             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
143             .wMaxPacketSize        = 512,
144         },
145     }
146 };
147
148 static const USBDescDevice desc_device_high = {
149     .bcdUSB                        = 0x0200,
150     .bMaxPacketSize0               = 64,
151     .bNumConfigurations            = 1,
152     .confs = (USBDescConfig[]) {
153         {
154             .bNumInterfaces        = 1,
155             .bConfigurationValue   = 1,
156             .iConfiguration        = STR_CONFIG_HIGH,
157             .bmAttributes          = 0xc0,
158             .nif = 1,
159             .ifs = &desc_iface_high,
160         },
161     },
162 };
163
164 static const USBDesc desc = {
165     .id = {
166         .idVendor          = 0x46f4, /* CRC16() of "QEMU" */
167         .idProduct         = 0x0001,
168         .bcdDevice         = 0,
169         .iManufacturer     = STR_MANUFACTURER,
170         .iProduct          = STR_PRODUCT,
171         .iSerialNumber     = STR_SERIALNUMBER,
172     },
173     .full = &desc_device_full,
174     .high = &desc_device_high,
175     .str  = desc_strings,
176 };
177
178 static void usb_msd_copy_data(MSDState *s, USBPacket *p)
179 {
180     uint32_t len;
181     len = p->iov.size - p->result;
182     if (len > s->scsi_len)
183         len = s->scsi_len;
184     usb_packet_copy(p, s->scsi_buf, len);
185     s->scsi_len -= len;
186     s->scsi_buf += len;
187     s->data_len -= len;
188     if (s->scsi_len == 0 || s->data_len == 0) {
189         scsi_req_continue(s->req);
190     }
191 }
192
193 static void usb_msd_send_status(MSDState *s, USBPacket *p)
194 {
195     int len;
196
197     DPRINTF("Command status %d tag 0x%x, len %zd\n",
198             s->csw.status, s->csw.tag, p->iov.size);
199
200     assert(s->csw.sig == 0x53425355);
201     len = MIN(sizeof(s->csw), p->iov.size);
202     usb_packet_copy(p, &s->csw, len);
203     memset(&s->csw, 0, sizeof(s->csw));
204 }
205
206 static void usb_msd_transfer_data(SCSIRequest *req, uint32_t len)
207 {
208     MSDState *s = DO_UPCAST(MSDState, dev.qdev, req->bus->qbus.parent);
209     USBPacket *p = s->packet;
210
211     assert((s->mode == USB_MSDM_DATAOUT) == (req->cmd.mode == SCSI_XFER_TO_DEV));
212     s->scsi_len = len;
213     s->scsi_buf = scsi_req_get_buf(req);
214     if (p) {
215         usb_msd_copy_data(s, p);
216         p = s->packet;
217         if (p && p->result == p->iov.size) {
218             /* Set s->packet to NULL before calling usb_packet_complete
219                because another request may be issued before
220                usb_packet_complete returns.  */
221             DPRINTF("Packet complete %p\n", p);
222             s->packet = NULL;
223             usb_packet_complete(&s->dev, p);
224         }
225     }
226 }
227
228 static void usb_msd_command_complete(SCSIRequest *req, uint32_t status)
229 {
230     MSDState *s = DO_UPCAST(MSDState, dev.qdev, req->bus->qbus.parent);
231     USBPacket *p = s->packet;
232
233     DPRINTF("Command complete %d\n", status);
234     s->residue = s->data_len;
235     s->result = status != 0;
236
237     s->csw.sig = cpu_to_le32(0x53425355);
238     s->csw.tag = cpu_to_le32(s->tag);
239     s->csw.residue = s->residue;
240     s->csw.status = s->result;
241
242     if (s->packet) {
243         if (s->data_len == 0 && s->mode == USB_MSDM_DATAOUT) {
244             /* A deferred packet with no write data remaining must be
245                the status read packet.  */
246             usb_msd_send_status(s, p);
247             s->mode = USB_MSDM_CBW;
248         } else {
249             if (s->data_len) {
250                 int len = (p->iov.size - p->result);
251                 usb_packet_skip(p, len);
252                 s->data_len -= len;
253             }
254             if (s->data_len == 0) {
255                 s->mode = USB_MSDM_CSW;
256             }
257         }
258         s->packet = NULL;
259         usb_packet_complete(&s->dev, p);
260     } else if (s->data_len == 0) {
261         s->mode = USB_MSDM_CSW;
262     }
263
264     scsi_req_unref(req);
265     s->req = NULL;
266 }
267
268 static void usb_msd_request_cancelled(SCSIRequest *req)
269 {
270     MSDState *s = DO_UPCAST(MSDState, dev.qdev, req->bus->qbus.parent);
271
272     if (req == s->req) {
273         scsi_req_unref(s->req);
274         s->req = NULL;
275         s->packet = NULL;
276         s->scsi_len = 0;
277     }
278 }
279
280 static void usb_msd_handle_reset(USBDevice *dev)
281 {
282     MSDState *s = (MSDState *)dev;
283
284     DPRINTF("Reset\n");
285     s->mode = USB_MSDM_CBW;
286 }
287
288 static int usb_msd_handle_control(USBDevice *dev, USBPacket *p,
289                int request, int value, int index, int length, uint8_t *data)
290 {
291     MSDState *s = (MSDState *)dev;
292     int ret;
293
294     ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
295     if (ret >= 0) {
296         return ret;
297     }
298
299     ret = 0;
300     switch (request) {
301     case DeviceRequest | USB_REQ_GET_INTERFACE:
302         data[0] = 0;
303         ret = 1;
304         break;
305     case DeviceOutRequest | USB_REQ_SET_INTERFACE:
306         ret = 0;
307         break;
308     case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
309         ret = 0;
310         break;
311     case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
312         ret = 0;
313         break;
314         /* Class specific requests.  */
315     case ClassInterfaceOutRequest | MassStorageReset:
316         /* Reset state ready for the next CBW.  */
317         s->mode = USB_MSDM_CBW;
318         ret = 0;
319         break;
320     case ClassInterfaceRequest | GetMaxLun:
321         data[0] = 0;
322         ret = 1;
323         break;
324     default:
325         ret = USB_RET_STALL;
326         break;
327     }
328     return ret;
329 }
330
331 static void usb_msd_cancel_io(USBDevice *dev, USBPacket *p)
332 {
333     MSDState *s = DO_UPCAST(MSDState, dev, dev);
334
335     if (s->req) {
336         scsi_req_cancel(s->req);
337     }
338 }
339
340 static int usb_msd_handle_data(USBDevice *dev, USBPacket *p)
341 {
342     MSDState *s = (MSDState *)dev;
343     int ret = 0;
344     struct usb_msd_cbw cbw;
345     uint8_t devep = p->devep;
346
347     switch (p->pid) {
348     case USB_TOKEN_OUT:
349         if (devep != 2)
350             goto fail;
351
352         switch (s->mode) {
353         case USB_MSDM_CBW:
354             if (p->iov.size != 31) {
355                 fprintf(stderr, "usb-msd: Bad CBW size");
356                 goto fail;
357             }
358             usb_packet_copy(p, &cbw, 31);
359             if (le32_to_cpu(cbw.sig) != 0x43425355) {
360                 fprintf(stderr, "usb-msd: Bad signature %08x\n",
361                         le32_to_cpu(cbw.sig));
362                 goto fail;
363             }
364             DPRINTF("Command on LUN %d\n", cbw.lun);
365             if (cbw.lun != 0) {
366                 fprintf(stderr, "usb-msd: Bad LUN %d\n", cbw.lun);
367                 goto fail;
368             }
369             s->tag = le32_to_cpu(cbw.tag);
370             s->data_len = le32_to_cpu(cbw.data_len);
371             if (s->data_len == 0) {
372                 s->mode = USB_MSDM_CSW;
373             } else if (cbw.flags & 0x80) {
374                 s->mode = USB_MSDM_DATAIN;
375             } else {
376                 s->mode = USB_MSDM_DATAOUT;
377             }
378             DPRINTF("Command tag 0x%x flags %08x len %d data %d\n",
379                     s->tag, cbw.flags, cbw.cmd_len, s->data_len);
380             s->residue = 0;
381             s->scsi_len = 0;
382             s->req = scsi_req_new(s->scsi_dev, s->tag, 0, cbw.cmd, NULL);
383             scsi_req_enqueue(s->req);
384             /* ??? Should check that USB and SCSI data transfer
385                directions match.  */
386             if (s->mode != USB_MSDM_CSW && s->residue == 0) {
387                 scsi_req_continue(s->req);
388             }
389             ret = p->result;
390             break;
391
392         case USB_MSDM_DATAOUT:
393             DPRINTF("Data out %zd/%d\n", p->iov.size, s->data_len);
394             if (p->iov.size > s->data_len) {
395                 goto fail;
396             }
397
398             if (s->scsi_len) {
399                 usb_msd_copy_data(s, p);
400             }
401             if (s->residue) {
402                 int len = p->iov.size - p->result;
403                 if (len) {
404                     usb_packet_skip(p, len);
405                     s->data_len -= len;
406                     if (s->data_len == 0) {
407                         s->mode = USB_MSDM_CSW;
408                     }
409                 }
410             }
411             if (p->result < p->iov.size) {
412                 DPRINTF("Deferring packet %p\n", p);
413                 s->packet = p;
414                 ret = USB_RET_ASYNC;
415             } else {
416                 ret = p->result;
417             }
418             break;
419
420         default:
421             DPRINTF("Unexpected write (len %zd)\n", p->iov.size);
422             goto fail;
423         }
424         break;
425
426     case USB_TOKEN_IN:
427         if (devep != 1)
428             goto fail;
429
430         switch (s->mode) {
431         case USB_MSDM_DATAOUT:
432             if (s->data_len != 0 || p->iov.size < 13) {
433                 goto fail;
434             }
435             /* Waiting for SCSI write to complete.  */
436             s->packet = p;
437             ret = USB_RET_ASYNC;
438             break;
439
440         case USB_MSDM_CSW:
441             if (p->iov.size < 13) {
442                 goto fail;
443             }
444
445             usb_msd_send_status(s, p);
446             s->mode = USB_MSDM_CBW;
447             ret = 13;
448             break;
449
450         case USB_MSDM_DATAIN:
451             DPRINTF("Data in %zd/%d, scsi_len %d\n",
452                     p->iov.size, s->data_len, s->scsi_len);
453             if (s->scsi_len) {
454                 usb_msd_copy_data(s, p);
455             }
456             if (s->residue) {
457                 int len = p->iov.size - p->result;
458                 if (len) {
459                     usb_packet_skip(p, len);
460                     s->data_len -= len;
461                     if (s->data_len == 0) {
462                         s->mode = USB_MSDM_CSW;
463                     }
464                 }
465             }
466             if (p->result < p->iov.size) {
467                 DPRINTF("Deferring packet %p\n", p);
468                 s->packet = p;
469                 ret = USB_RET_ASYNC;
470             } else {
471                 ret = p->result;
472             }
473             break;
474
475         default:
476             DPRINTF("Unexpected read (len %zd)\n", p->iov.size);
477             goto fail;
478         }
479         break;
480
481     default:
482         DPRINTF("Bad token\n");
483     fail:
484         ret = USB_RET_STALL;
485         break;
486     }
487
488     return ret;
489 }
490
491 static void usb_msd_password_cb(void *opaque, int err)
492 {
493     MSDState *s = opaque;
494
495     if (!err)
496         err = usb_device_attach(&s->dev);
497
498     if (err)
499         qdev_unplug(&s->dev.qdev);
500 }
501
502 static const struct SCSIBusInfo usb_msd_scsi_info = {
503     .tcq = false,
504     .max_target = 0,
505     .max_lun = 0,
506
507     .transfer_data = usb_msd_transfer_data,
508     .complete = usb_msd_command_complete,
509     .cancel = usb_msd_request_cancelled
510 };
511
512 static int usb_msd_initfn(USBDevice *dev)
513 {
514     MSDState *s = DO_UPCAST(MSDState, dev, dev);
515     BlockDriverState *bs = s->conf.bs;
516     DriveInfo *dinfo;
517
518     if (!bs) {
519         error_report("usb-msd: drive property not set");
520         return -1;
521     }
522
523     /*
524      * Hack alert: this pretends to be a block device, but it's really
525      * a SCSI bus that can serve only a single device, which it
526      * creates automatically.  But first it needs to detach from its
527      * blockdev, or else scsi_bus_legacy_add_drive() dies when it
528      * attaches again.
529      *
530      * The hack is probably a bad idea.
531      */
532     bdrv_detach_dev(bs, &s->dev.qdev);
533     s->conf.bs = NULL;
534
535     if (!s->serial) {
536         /* try to fall back to value set with legacy -drive serial=... */
537         dinfo = drive_get_by_blockdev(bs);
538         if (*dinfo->serial) {
539             s->serial = strdup(dinfo->serial);
540         }
541     }
542     if (s->serial) {
543         usb_desc_set_string(dev, STR_SERIALNUMBER, s->serial);
544     }
545
546     usb_desc_init(dev);
547     scsi_bus_new(&s->bus, &s->dev.qdev, &usb_msd_scsi_info);
548     s->scsi_dev = scsi_bus_legacy_add_drive(&s->bus, bs, 0, !!s->removable);
549     if (!s->scsi_dev) {
550         return -1;
551     }
552     s->bus.qbus.allow_hotplug = 0;
553     usb_msd_handle_reset(dev);
554
555     if (bdrv_key_required(bs)) {
556         if (cur_mon) {
557             monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb, s);
558             s->dev.auto_attach = 0;
559         } else {
560             autostart = 0;
561         }
562     }
563
564     add_boot_device_path(s->conf.bootindex, &dev->qdev, "/disk@0,0");
565     return 0;
566 }
567
568 static USBDevice *usb_msd_init(const char *filename)
569 {
570     static int nr=0;
571     char id[8];
572     QemuOpts *opts;
573     DriveInfo *dinfo;
574     USBDevice *dev;
575     const char *p1;
576     char fmt[32];
577
578     /* parse -usbdevice disk: syntax into drive opts */
579     snprintf(id, sizeof(id), "usb%d", nr++);
580     opts = qemu_opts_create(qemu_find_opts("drive"), id, 0);
581
582     p1 = strchr(filename, ':');
583     if (p1++) {
584         const char *p2;
585
586         if (strstart(filename, "format=", &p2)) {
587             int len = MIN(p1 - p2, sizeof(fmt));
588             pstrcpy(fmt, len, p2);
589             qemu_opt_set(opts, "format", fmt);
590         } else if (*filename != ':') {
591             printf("unrecognized USB mass-storage option %s\n", filename);
592             return NULL;
593         }
594         filename = p1;
595     }
596     if (!*filename) {
597         printf("block device specification needed\n");
598         return NULL;
599     }
600     qemu_opt_set(opts, "file", filename);
601     qemu_opt_set(opts, "if", "none");
602
603     /* create host drive */
604     dinfo = drive_init(opts, 0);
605     if (!dinfo) {
606         qemu_opts_del(opts);
607         return NULL;
608     }
609
610     /* create guest device */
611     dev = usb_create(NULL /* FIXME */, "usb-storage");
612     if (!dev) {
613         return NULL;
614     }
615     if (qdev_prop_set_drive(&dev->qdev, "drive", dinfo->bdrv) < 0) {
616         qdev_free(&dev->qdev);
617         return NULL;
618     }
619     if (qdev_init(&dev->qdev) < 0)
620         return NULL;
621
622     return dev;
623 }
624
625 static const VMStateDescription vmstate_usb_msd = {
626     .name = "usb-storage",
627     .unmigratable = 1, /* FIXME: handle transactions which are in flight */
628     .version_id = 1,
629     .minimum_version_id = 1,
630     .fields = (VMStateField []) {
631         VMSTATE_USB_DEVICE(dev, MSDState),
632         VMSTATE_END_OF_LIST()
633     }
634 };
635
636 static struct USBDeviceInfo msd_info = {
637     .product_desc   = "QEMU USB MSD",
638     .qdev.name      = "usb-storage",
639     .qdev.fw_name      = "storage",
640     .qdev.size      = sizeof(MSDState),
641     .qdev.vmsd      = &vmstate_usb_msd,
642     .usb_desc       = &desc,
643     .init           = usb_msd_initfn,
644     .handle_packet  = usb_generic_handle_packet,
645     .cancel_packet  = usb_msd_cancel_io,
646     .handle_attach  = usb_desc_attach,
647     .handle_reset   = usb_msd_handle_reset,
648     .handle_control = usb_msd_handle_control,
649     .handle_data    = usb_msd_handle_data,
650     .usbdevice_name = "disk",
651     .usbdevice_init = usb_msd_init,
652     .qdev.props     = (Property[]) {
653         DEFINE_BLOCK_PROPERTIES(MSDState, conf),
654         DEFINE_PROP_STRING("serial", MSDState, serial),
655         DEFINE_PROP_BIT("removable", MSDState, removable, 0, false),
656         DEFINE_PROP_END_OF_LIST(),
657     },
658 };
659
660 static void usb_msd_register_devices(void)
661 {
662     usb_qdev_register(&msd_info);
663 }
664 device_init(usb_msd_register_devices)
This page took 0.060679 seconds and 4 git commands to generate.