mainstone: convert to memory API
[qemu.git] / hw / usb-msd.c
blob4072efd4b75cbcf43e33057290b691220b491b74
1 /*
2 * USB Mass Storage Device emulation
4 * Copyright (c) 2006 CodeSourcery.
5 * Written by Paul Brook
7 * This code is licensed under the LGPL.
8 */
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"
21 //#define DEBUG_MSD
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
30 /* USB requests. */
31 #define MassStorageReset 0xff
32 #define GetMaxLun 0xfe
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. */
41 typedef struct {
42 USBDevice dev;
43 enum USBMSDMode mode;
44 uint32_t scsi_len;
45 uint8_t *scsi_buf;
46 uint32_t data_len;
47 uint32_t residue;
48 uint32_t tag;
49 SCSIRequest *req;
50 SCSIBus bus;
51 BlockConf conf;
52 char *serial;
53 SCSIDevice *scsi_dev;
54 uint32_t removable;
55 int result;
56 /* For async completion. */
57 USBPacket *packet;
58 } MSDState;
60 struct usb_msd_cbw {
61 uint32_t sig;
62 uint32_t tag;
63 uint32_t data_len;
64 uint8_t flags;
65 uint8_t lun;
66 uint8_t cmd_len;
67 uint8_t cmd[16];
70 struct usb_msd_csw {
71 uint32_t sig;
72 uint32_t tag;
73 uint32_t residue;
74 uint8_t status;
77 enum {
78 STR_MANUFACTURER = 1,
79 STR_PRODUCT,
80 STR_SERIALNUMBER,
81 STR_CONFIG_FULL,
82 STR_CONFIG_HIGH,
85 static const USBDescStrings desc_strings = {
86 [STR_MANUFACTURER] = "QEMU " QEMU_VERSION,
87 [STR_PRODUCT] = "QEMU USB HARDDRIVE",
88 [STR_SERIALNUMBER] = "1",
89 [STR_CONFIG_FULL] = "Full speed config (usb 1.1)",
90 [STR_CONFIG_HIGH] = "High speed config (usb 2.0)",
93 static const USBDescIface desc_iface_full = {
94 .bInterfaceNumber = 0,
95 .bNumEndpoints = 2,
96 .bInterfaceClass = USB_CLASS_MASS_STORAGE,
97 .bInterfaceSubClass = 0x06, /* SCSI */
98 .bInterfaceProtocol = 0x50, /* Bulk */
99 .eps = (USBDescEndpoint[]) {
101 .bEndpointAddress = USB_DIR_IN | 0x01,
102 .bmAttributes = USB_ENDPOINT_XFER_BULK,
103 .wMaxPacketSize = 64,
105 .bEndpointAddress = USB_DIR_OUT | 0x02,
106 .bmAttributes = USB_ENDPOINT_XFER_BULK,
107 .wMaxPacketSize = 64,
112 static const USBDescDevice desc_device_full = {
113 .bcdUSB = 0x0200,
114 .bMaxPacketSize0 = 8,
115 .bNumConfigurations = 1,
116 .confs = (USBDescConfig[]) {
118 .bNumInterfaces = 1,
119 .bConfigurationValue = 1,
120 .iConfiguration = STR_CONFIG_FULL,
121 .bmAttributes = 0xc0,
122 .nif = 1,
123 .ifs = &desc_iface_full,
128 static const USBDescIface desc_iface_high = {
129 .bInterfaceNumber = 0,
130 .bNumEndpoints = 2,
131 .bInterfaceClass = USB_CLASS_MASS_STORAGE,
132 .bInterfaceSubClass = 0x06, /* SCSI */
133 .bInterfaceProtocol = 0x50, /* Bulk */
134 .eps = (USBDescEndpoint[]) {
136 .bEndpointAddress = USB_DIR_IN | 0x01,
137 .bmAttributes = USB_ENDPOINT_XFER_BULK,
138 .wMaxPacketSize = 512,
140 .bEndpointAddress = USB_DIR_OUT | 0x02,
141 .bmAttributes = USB_ENDPOINT_XFER_BULK,
142 .wMaxPacketSize = 512,
147 static const USBDescDevice desc_device_high = {
148 .bcdUSB = 0x0200,
149 .bMaxPacketSize0 = 64,
150 .bNumConfigurations = 1,
151 .confs = (USBDescConfig[]) {
153 .bNumInterfaces = 1,
154 .bConfigurationValue = 1,
155 .iConfiguration = STR_CONFIG_HIGH,
156 .bmAttributes = 0xc0,
157 .nif = 1,
158 .ifs = &desc_iface_high,
163 static const USBDesc desc = {
164 .id = {
165 .idVendor = 0,
166 .idProduct = 0,
167 .bcdDevice = 0,
168 .iManufacturer = STR_MANUFACTURER,
169 .iProduct = STR_PRODUCT,
170 .iSerialNumber = STR_SERIALNUMBER,
172 .full = &desc_device_full,
173 .high = &desc_device_high,
174 .str = desc_strings,
177 static void usb_msd_copy_data(MSDState *s, USBPacket *p)
179 uint32_t len;
180 len = p->iov.size - p->result;
181 if (len > s->scsi_len)
182 len = s->scsi_len;
183 usb_packet_copy(p, s->scsi_buf, len);
184 s->scsi_len -= len;
185 s->scsi_buf += len;
186 s->data_len -= len;
187 if (s->scsi_len == 0 || s->data_len == 0) {
188 scsi_req_continue(s->req);
192 static void usb_msd_send_status(MSDState *s, USBPacket *p)
194 struct usb_msd_csw csw;
195 int len;
197 csw.sig = cpu_to_le32(0x53425355);
198 csw.tag = cpu_to_le32(s->tag);
199 csw.residue = s->residue;
200 csw.status = s->result;
202 len = MIN(sizeof(csw), p->iov.size);
203 usb_packet_copy(p, &csw, len);
204 p->result = len;
207 static void usb_msd_transfer_data(SCSIRequest *req, uint32_t len)
209 MSDState *s = DO_UPCAST(MSDState, dev.qdev, req->bus->qbus.parent);
210 USBPacket *p = s->packet;
212 assert((s->mode == USB_MSDM_DATAOUT) == (req->cmd.mode == SCSI_XFER_TO_DEV));
213 s->scsi_len = len;
214 s->scsi_buf = scsi_req_get_buf(req);
215 if (p) {
216 usb_msd_copy_data(s, p);
217 p = s->packet;
218 if (p && p->result == p->iov.size) {
219 /* Set s->packet to NULL before calling usb_packet_complete
220 because another request may be issued before
221 usb_packet_complete returns. */
222 DPRINTF("Packet complete %p\n", p);
223 s->packet = NULL;
224 usb_packet_complete(&s->dev, p);
229 static void usb_msd_command_complete(SCSIRequest *req, uint32_t status)
231 MSDState *s = DO_UPCAST(MSDState, dev.qdev, req->bus->qbus.parent);
232 USBPacket *p = s->packet;
234 DPRINTF("Command complete %d\n", status);
235 s->residue = s->data_len;
236 s->result = status != 0;
237 if (s->packet) {
238 if (s->data_len == 0 && s->mode == USB_MSDM_DATAOUT) {
239 /* A deferred packet with no write data remaining must be
240 the status read packet. */
241 usb_msd_send_status(s, p);
242 s->mode = USB_MSDM_CBW;
243 } else {
244 if (s->data_len) {
245 int len = (p->iov.size - p->result);
246 usb_packet_skip(p, len);
247 s->data_len -= len;
249 if (s->data_len == 0) {
250 s->mode = USB_MSDM_CSW;
253 s->packet = NULL;
254 usb_packet_complete(&s->dev, p);
255 } else if (s->data_len == 0) {
256 s->mode = USB_MSDM_CSW;
258 scsi_req_unref(req);
259 s->req = NULL;
262 static void usb_msd_request_cancelled(SCSIRequest *req)
264 MSDState *s = DO_UPCAST(MSDState, dev.qdev, req->bus->qbus.parent);
266 if (req == s->req) {
267 scsi_req_unref(s->req);
268 s->req = NULL;
269 s->packet = NULL;
270 s->scsi_len = 0;
274 static void usb_msd_handle_reset(USBDevice *dev)
276 MSDState *s = (MSDState *)dev;
278 DPRINTF("Reset\n");
279 s->mode = USB_MSDM_CBW;
282 static int usb_msd_handle_control(USBDevice *dev, USBPacket *p,
283 int request, int value, int index, int length, uint8_t *data)
285 MSDState *s = (MSDState *)dev;
286 int ret;
288 ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
289 if (ret >= 0) {
290 return ret;
293 ret = 0;
294 switch (request) {
295 case DeviceRequest | USB_REQ_GET_INTERFACE:
296 data[0] = 0;
297 ret = 1;
298 break;
299 case DeviceOutRequest | USB_REQ_SET_INTERFACE:
300 ret = 0;
301 break;
302 case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
303 ret = 0;
304 break;
305 case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
306 ret = 0;
307 break;
308 /* Class specific requests. */
309 case ClassInterfaceOutRequest | MassStorageReset:
310 /* Reset state ready for the next CBW. */
311 s->mode = USB_MSDM_CBW;
312 ret = 0;
313 break;
314 case ClassInterfaceRequest | GetMaxLun:
315 data[0] = 0;
316 ret = 1;
317 break;
318 default:
319 ret = USB_RET_STALL;
320 break;
322 return ret;
325 static void usb_msd_cancel_io(USBDevice *dev, USBPacket *p)
327 MSDState *s = DO_UPCAST(MSDState, dev, dev);
328 scsi_req_cancel(s->req);
331 static int usb_msd_handle_data(USBDevice *dev, USBPacket *p)
333 MSDState *s = (MSDState *)dev;
334 int ret = 0;
335 struct usb_msd_cbw cbw;
336 uint8_t devep = p->devep;
338 switch (p->pid) {
339 case USB_TOKEN_OUT:
340 if (devep != 2)
341 goto fail;
343 switch (s->mode) {
344 case USB_MSDM_CBW:
345 if (p->iov.size != 31) {
346 fprintf(stderr, "usb-msd: Bad CBW size");
347 goto fail;
349 usb_packet_copy(p, &cbw, 31);
350 if (le32_to_cpu(cbw.sig) != 0x43425355) {
351 fprintf(stderr, "usb-msd: Bad signature %08x\n",
352 le32_to_cpu(cbw.sig));
353 goto fail;
355 DPRINTF("Command on LUN %d\n", cbw.lun);
356 if (cbw.lun != 0) {
357 fprintf(stderr, "usb-msd: Bad LUN %d\n", cbw.lun);
358 goto fail;
360 s->tag = le32_to_cpu(cbw.tag);
361 s->data_len = le32_to_cpu(cbw.data_len);
362 if (s->data_len == 0) {
363 s->mode = USB_MSDM_CSW;
364 } else if (cbw.flags & 0x80) {
365 s->mode = USB_MSDM_DATAIN;
366 } else {
367 s->mode = USB_MSDM_DATAOUT;
369 DPRINTF("Command tag 0x%x flags %08x len %d data %d\n",
370 s->tag, cbw.flags, cbw.cmd_len, s->data_len);
371 s->residue = 0;
372 s->scsi_len = 0;
373 s->req = scsi_req_new(s->scsi_dev, s->tag, 0, cbw.cmd, NULL);
374 scsi_req_enqueue(s->req);
375 /* ??? Should check that USB and SCSI data transfer
376 directions match. */
377 if (s->mode != USB_MSDM_CSW && s->residue == 0) {
378 scsi_req_continue(s->req);
380 ret = p->result;
381 break;
383 case USB_MSDM_DATAOUT:
384 DPRINTF("Data out %zd/%d\n", p->iov.size, s->data_len);
385 if (p->iov.size > s->data_len) {
386 goto fail;
389 if (s->scsi_len) {
390 usb_msd_copy_data(s, p);
392 if (s->residue) {
393 int len = p->iov.size - p->result;
394 if (len) {
395 usb_packet_skip(p, len);
396 s->data_len -= len;
397 if (s->data_len == 0) {
398 s->mode = USB_MSDM_CSW;
402 if (p->result < p->iov.size) {
403 DPRINTF("Deferring packet %p\n", p);
404 s->packet = p;
405 ret = USB_RET_ASYNC;
406 } else {
407 ret = p->result;
409 break;
411 default:
412 DPRINTF("Unexpected write (len %zd)\n", p->iov.size);
413 goto fail;
415 break;
417 case USB_TOKEN_IN:
418 if (devep != 1)
419 goto fail;
421 switch (s->mode) {
422 case USB_MSDM_DATAOUT:
423 if (s->data_len != 0 || p->iov.size < 13) {
424 goto fail;
426 /* Waiting for SCSI write to complete. */
427 s->packet = p;
428 ret = USB_RET_ASYNC;
429 break;
431 case USB_MSDM_CSW:
432 DPRINTF("Command status %d tag 0x%x, len %zd\n",
433 s->result, s->tag, p->iov.size);
434 if (p->iov.size < 13) {
435 goto fail;
438 usb_msd_send_status(s, p);
439 s->mode = USB_MSDM_CBW;
440 ret = 13;
441 break;
443 case USB_MSDM_DATAIN:
444 DPRINTF("Data in %zd/%d, scsi_len %d\n",
445 p->iov.size, s->data_len, s->scsi_len);
446 if (s->scsi_len) {
447 usb_msd_copy_data(s, p);
449 if (s->residue) {
450 int len = p->iov.size - p->result;
451 if (len) {
452 usb_packet_skip(p, len);
453 s->data_len -= len;
454 if (s->data_len == 0) {
455 s->mode = USB_MSDM_CSW;
459 if (p->result < p->iov.size) {
460 DPRINTF("Deferring packet %p\n", p);
461 s->packet = p;
462 ret = USB_RET_ASYNC;
463 } else {
464 ret = p->result;
466 break;
468 default:
469 DPRINTF("Unexpected read (len %zd)\n", p->iov.size);
470 goto fail;
472 break;
474 default:
475 DPRINTF("Bad token\n");
476 fail:
477 ret = USB_RET_STALL;
478 break;
481 return ret;
484 static void usb_msd_password_cb(void *opaque, int err)
486 MSDState *s = opaque;
488 if (!err)
489 err = usb_device_attach(&s->dev);
491 if (err)
492 qdev_unplug(&s->dev.qdev);
495 static const struct SCSIBusOps usb_msd_scsi_ops = {
496 .transfer_data = usb_msd_transfer_data,
497 .complete = usb_msd_command_complete,
498 .cancel = usb_msd_request_cancelled
501 static int usb_msd_initfn(USBDevice *dev)
503 MSDState *s = DO_UPCAST(MSDState, dev, dev);
504 BlockDriverState *bs = s->conf.bs;
505 DriveInfo *dinfo;
507 if (!bs) {
508 error_report("usb-msd: drive property not set");
509 return -1;
513 * Hack alert: this pretends to be a block device, but it's really
514 * a SCSI bus that can serve only a single device, which it
515 * creates automatically. But first it needs to detach from its
516 * blockdev, or else scsi_bus_legacy_add_drive() dies when it
517 * attaches again.
519 * The hack is probably a bad idea.
521 bdrv_detach(bs, &s->dev.qdev);
522 s->conf.bs = NULL;
524 if (!s->serial) {
525 /* try to fall back to value set with legacy -drive serial=... */
526 dinfo = drive_get_by_blockdev(bs);
527 if (*dinfo->serial) {
528 s->serial = strdup(dinfo->serial);
531 if (s->serial) {
532 usb_desc_set_string(dev, STR_SERIALNUMBER, s->serial);
535 usb_desc_init(dev);
536 scsi_bus_new(&s->bus, &s->dev.qdev, 0, 1, &usb_msd_scsi_ops);
537 s->scsi_dev = scsi_bus_legacy_add_drive(&s->bus, bs, 0, !!s->removable);
538 if (!s->scsi_dev) {
539 return -1;
541 s->bus.qbus.allow_hotplug = 0;
542 usb_msd_handle_reset(dev);
544 if (bdrv_key_required(bs)) {
545 if (cur_mon) {
546 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb, s);
547 s->dev.auto_attach = 0;
548 } else {
549 autostart = 0;
553 add_boot_device_path(s->conf.bootindex, &dev->qdev, "/disk@0,0");
554 return 0;
557 static USBDevice *usb_msd_init(const char *filename)
559 static int nr=0;
560 char id[8];
561 QemuOpts *opts;
562 DriveInfo *dinfo;
563 USBDevice *dev;
564 const char *p1;
565 char fmt[32];
567 /* parse -usbdevice disk: syntax into drive opts */
568 snprintf(id, sizeof(id), "usb%d", nr++);
569 opts = qemu_opts_create(qemu_find_opts("drive"), id, 0);
571 p1 = strchr(filename, ':');
572 if (p1++) {
573 const char *p2;
575 if (strstart(filename, "format=", &p2)) {
576 int len = MIN(p1 - p2, sizeof(fmt));
577 pstrcpy(fmt, len, p2);
578 qemu_opt_set(opts, "format", fmt);
579 } else if (*filename != ':') {
580 printf("unrecognized USB mass-storage option %s\n", filename);
581 return NULL;
583 filename = p1;
585 if (!*filename) {
586 printf("block device specification needed\n");
587 return NULL;
589 qemu_opt_set(opts, "file", filename);
590 qemu_opt_set(opts, "if", "none");
592 /* create host drive */
593 dinfo = drive_init(opts, 0);
594 if (!dinfo) {
595 qemu_opts_del(opts);
596 return NULL;
599 /* create guest device */
600 dev = usb_create(NULL /* FIXME */, "usb-storage");
601 if (!dev) {
602 return NULL;
604 if (qdev_prop_set_drive(&dev->qdev, "drive", dinfo->bdrv) < 0) {
605 qdev_free(&dev->qdev);
606 return NULL;
608 if (qdev_init(&dev->qdev) < 0)
609 return NULL;
611 return dev;
614 static const VMStateDescription vmstate_usb_msd = {
615 .name = "usb-storage",
616 .unmigratable = 1, /* FIXME: handle transactions which are in flight */
617 .version_id = 1,
618 .minimum_version_id = 1,
619 .fields = (VMStateField []) {
620 VMSTATE_USB_DEVICE(dev, MSDState),
621 VMSTATE_END_OF_LIST()
625 static struct USBDeviceInfo msd_info = {
626 .product_desc = "QEMU USB MSD",
627 .qdev.name = "usb-storage",
628 .qdev.fw_name = "storage",
629 .qdev.size = sizeof(MSDState),
630 .qdev.vmsd = &vmstate_usb_msd,
631 .usb_desc = &desc,
632 .init = usb_msd_initfn,
633 .handle_packet = usb_generic_handle_packet,
634 .cancel_packet = usb_msd_cancel_io,
635 .handle_attach = usb_desc_attach,
636 .handle_reset = usb_msd_handle_reset,
637 .handle_control = usb_msd_handle_control,
638 .handle_data = usb_msd_handle_data,
639 .usbdevice_name = "disk",
640 .usbdevice_init = usb_msd_init,
641 .qdev.props = (Property[]) {
642 DEFINE_BLOCK_PROPERTIES(MSDState, conf),
643 DEFINE_PROP_STRING("serial", MSDState, serial),
644 DEFINE_PROP_BIT("removable", MSDState, removable, 0, false),
645 DEFINE_PROP_END_OF_LIST(),
649 static void usb_msd_register_devices(void)
651 usb_qdev_register(&msd_info);
653 device_init(usb_msd_register_devices)