Add to machine structure a flag to use SCSI drives instead of IDE: fixes SS-20
[qemu/mini2440.git] / usb-linux.c
blobc5da5b51302aad5c7a6e42d80f16250f66b1c862
1 /*
2 * Linux host USB redirector
4 * Copyright (c) 2005 Fabrice Bellard
6 * Copyright (c) 2008 Max Krasnyansky
7 * Support for host device auto connect & disconnect
8 * Major rewrite to support fully async operation
10 * Permission is hereby granted, free of charge, to any person obtaining a copy
11 * of this software and associated documentation files (the "Software"), to deal
12 * in the Software without restriction, including without limitation the rights
13 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 * copies of the Software, and to permit persons to whom the Software is
15 * furnished to do so, subject to the following conditions:
17 * The above copyright notice and this permission notice shall be included in
18 * all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 * THE SOFTWARE.
29 #include "qemu-common.h"
30 #include "qemu-timer.h"
31 #include "console.h"
33 #if defined(__linux__)
34 #include <dirent.h>
35 #include <sys/ioctl.h>
36 #include <signal.h>
38 #include <linux/usbdevice_fs.h>
39 #include <linux/version.h>
40 #include "hw/usb.h"
42 /* We redefine it to avoid version problems */
43 struct usb_ctrltransfer {
44 uint8_t bRequestType;
45 uint8_t bRequest;
46 uint16_t wValue;
47 uint16_t wIndex;
48 uint16_t wLength;
49 uint32_t timeout;
50 void *data;
53 struct usb_ctrlrequest {
54 uint8_t bRequestType;
55 uint8_t bRequest;
56 uint16_t wValue;
57 uint16_t wIndex;
58 uint16_t wLength;
61 typedef int USBScanFunc(void *opaque, int bus_num, int addr, int class_id,
62 int vendor_id, int product_id,
63 const char *product_name, int speed);
64 static int usb_host_find_device(int *pbus_num, int *paddr,
65 char *product_name, int product_name_size,
66 const char *devname);
67 //#define DEBUG
69 #ifdef DEBUG
70 #define dprintf printf
71 #else
72 #define dprintf(...)
73 #endif
75 #define USBDEVFS_PATH "/proc/bus/usb"
76 #define PRODUCT_NAME_SZ 32
77 #define MAX_ENDPOINTS 16
79 /* endpoint association data */
80 struct endp_data {
81 uint8_t type;
82 uint8_t halted;
85 enum {
86 CTRL_STATE_IDLE = 0,
87 CTRL_STATE_SETUP,
88 CTRL_STATE_DATA,
89 CTRL_STATE_ACK
93 * Control transfer state.
94 * Note that 'buffer' _must_ follow 'req' field because
95 * we need contigious buffer when we submit control URB.
96 */
97 struct ctrl_struct {
98 uint16_t len;
99 uint16_t offset;
100 uint8_t state;
101 struct usb_ctrlrequest req;
102 uint8_t buffer[1024];
105 typedef struct USBHostDevice {
106 USBDevice dev;
107 int fd;
109 uint8_t descr[1024];
110 int descr_len;
111 int configuration;
112 int ninterfaces;
113 int closing;
115 struct ctrl_struct ctrl;
116 struct endp_data endp_table[MAX_ENDPOINTS];
118 /* Host side address */
119 int bus_num;
120 int addr;
122 struct USBHostDevice *next;
123 } USBHostDevice;
125 static int is_isoc(USBHostDevice *s, int ep)
127 return s->endp_table[ep - 1].type == USBDEVFS_URB_TYPE_ISO;
130 static int is_halted(USBHostDevice *s, int ep)
132 return s->endp_table[ep - 1].halted;
135 static void clear_halt(USBHostDevice *s, int ep)
137 s->endp_table[ep - 1].halted = 0;
140 static void set_halt(USBHostDevice *s, int ep)
142 s->endp_table[ep - 1].halted = 1;
145 static USBHostDevice *hostdev_list;
147 static void hostdev_link(USBHostDevice *dev)
149 dev->next = hostdev_list;
150 hostdev_list = dev;
153 static void hostdev_unlink(USBHostDevice *dev)
155 USBHostDevice *pdev = hostdev_list;
156 USBHostDevice **prev = &hostdev_list;
158 while (pdev) {
159 if (pdev == dev) {
160 *prev = dev->next;
161 return;
164 prev = &pdev->next;
165 pdev = pdev->next;
169 static USBHostDevice *hostdev_find(int bus_num, int addr)
171 USBHostDevice *s = hostdev_list;
172 while (s) {
173 if (s->bus_num == bus_num && s->addr == addr)
174 return s;
175 s = s->next;
177 return NULL;
181 * Async URB state.
182 * We always allocate one isoc descriptor even for bulk transfers
183 * to simplify allocation and casts.
185 typedef struct AsyncURB
187 struct usbdevfs_urb urb;
188 struct usbdevfs_iso_packet_desc isocpd;
190 USBPacket *packet;
191 USBHostDevice *hdev;
192 } AsyncURB;
194 static AsyncURB *async_alloc(void)
196 return (AsyncURB *) qemu_mallocz(sizeof(AsyncURB));
199 static void async_free(AsyncURB *aurb)
201 qemu_free(aurb);
204 static void async_complete_ctrl(USBHostDevice *s, USBPacket *p)
206 switch(s->ctrl.state) {
207 case CTRL_STATE_SETUP:
208 if (p->len < s->ctrl.len)
209 s->ctrl.len = p->len;
210 s->ctrl.state = CTRL_STATE_DATA;
211 p->len = 8;
212 break;
214 case CTRL_STATE_ACK:
215 s->ctrl.state = CTRL_STATE_IDLE;
216 p->len = 0;
217 break;
219 default:
220 break;
224 static void async_complete(void *opaque)
226 USBHostDevice *s = opaque;
227 AsyncURB *aurb;
229 while (1) {
230 USBPacket *p;
232 int r = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &aurb);
233 if (r < 0) {
234 if (errno == EAGAIN)
235 return;
237 if (errno == ENODEV && !s->closing) {
238 printf("husb: device %d.%d disconnected\n", s->bus_num, s->addr);
239 usb_device_del_addr(0, s->dev.addr);
240 return;
243 dprintf("husb: async. reap urb failed errno %d\n", errno);
244 return;
247 p = aurb->packet;
249 dprintf("husb: async completed. aurb %p status %d alen %d\n",
250 aurb, aurb->urb.status, aurb->urb.actual_length);
252 if (p) {
253 switch (aurb->urb.status) {
254 case 0:
255 p->len = aurb->urb.actual_length;
256 if (aurb->urb.type == USBDEVFS_URB_TYPE_CONTROL)
257 async_complete_ctrl(s, p);
258 break;
260 case -EPIPE:
261 set_halt(s, p->devep);
262 /* fall through */
263 default:
264 p->len = USB_RET_NAK;
265 break;
268 usb_packet_complete(p);
271 async_free(aurb);
275 static void async_cancel(USBPacket *unused, void *opaque)
277 AsyncURB *aurb = opaque;
278 USBHostDevice *s = aurb->hdev;
280 dprintf("husb: async cancel. aurb %p\n", aurb);
282 /* Mark it as dead (see async_complete above) */
283 aurb->packet = NULL;
285 int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
286 if (r < 0) {
287 dprintf("husb: async. discard urb failed errno %d\n", errno);
291 static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
293 int dev_descr_len, config_descr_len;
294 int interface, nb_interfaces, nb_configurations;
295 int ret, i;
297 if (configuration == 0) /* address state - ignore */
298 return 1;
300 dprintf("husb: claiming interfaces. config %d\n", configuration);
302 i = 0;
303 dev_descr_len = dev->descr[0];
304 if (dev_descr_len > dev->descr_len)
305 goto fail;
306 nb_configurations = dev->descr[17];
308 i += dev_descr_len;
309 while (i < dev->descr_len) {
310 dprintf("husb: i is %d, descr_len is %d, dl %d, dt %d\n", i, dev->descr_len,
311 dev->descr[i], dev->descr[i+1]);
313 if (dev->descr[i+1] != USB_DT_CONFIG) {
314 i += dev->descr[i];
315 continue;
317 config_descr_len = dev->descr[i];
319 printf("husb: config #%d need %d\n", dev->descr[i + 5], configuration);
321 if (configuration < 0 || configuration == dev->descr[i + 5]) {
322 configuration = dev->descr[i + 5];
323 break;
326 i += config_descr_len;
329 if (i >= dev->descr_len) {
330 fprintf(stderr, "husb: update iface failed. no matching configuration\n");
331 goto fail;
333 nb_interfaces = dev->descr[i + 4];
335 #ifdef USBDEVFS_DISCONNECT
336 /* earlier Linux 2.4 do not support that */
338 struct usbdevfs_ioctl ctrl;
339 for (interface = 0; interface < nb_interfaces; interface++) {
340 ctrl.ioctl_code = USBDEVFS_DISCONNECT;
341 ctrl.ifno = interface;
342 ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
343 if (ret < 0 && errno != ENODATA) {
344 perror("USBDEVFS_DISCONNECT");
345 goto fail;
349 #endif
351 /* XXX: only grab if all interfaces are free */
352 for (interface = 0; interface < nb_interfaces; interface++) {
353 ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
354 if (ret < 0) {
355 if (errno == EBUSY) {
356 printf("husb: update iface. device already grabbed\n");
357 } else {
358 perror("husb: failed to claim interface");
360 fail:
361 return 0;
365 printf("husb: %d interfaces claimed for configuration %d\n",
366 nb_interfaces, configuration);
368 dev->ninterfaces = nb_interfaces;
369 dev->configuration = configuration;
370 return 1;
373 static int usb_host_release_interfaces(USBHostDevice *s)
375 int ret, i;
377 dprintf("husb: releasing interfaces\n");
379 for (i = 0; i < s->ninterfaces; i++) {
380 ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
381 if (ret < 0) {
382 perror("husb: failed to release interface");
383 return 0;
387 return 1;
390 static void usb_host_handle_reset(USBDevice *dev)
392 USBHostDevice *s = (USBHostDevice *) dev;
394 dprintf("husb: reset device %u.%u\n", s->bus_num, s->addr);
396 ioctl(s->fd, USBDEVFS_RESET);
398 usb_host_claim_interfaces(s, s->configuration);
401 static void usb_host_handle_destroy(USBDevice *dev)
403 USBHostDevice *s = (USBHostDevice *)dev;
405 s->closing = 1;
407 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
409 hostdev_unlink(s);
411 async_complete(s);
413 if (s->fd >= 0)
414 close(s->fd);
416 qemu_free(s);
419 static int usb_linux_update_endp_table(USBHostDevice *s);
421 static int usb_host_handle_data(USBHostDevice *s, USBPacket *p)
423 struct usbdevfs_urb *urb;
424 AsyncURB *aurb;
425 int ret;
427 aurb = async_alloc();
428 if (!aurb) {
429 dprintf("husb: async malloc failed\n");
430 return USB_RET_NAK;
432 aurb->hdev = s;
433 aurb->packet = p;
435 urb = &aurb->urb;
437 if (p->pid == USB_TOKEN_IN)
438 urb->endpoint = p->devep | 0x80;
439 else
440 urb->endpoint = p->devep;
442 if (is_halted(s, p->devep)) {
443 ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &urb->endpoint);
444 if (ret < 0) {
445 dprintf("husb: failed to clear halt. ep 0x%x errno %d\n",
446 urb->endpoint, errno);
447 return USB_RET_NAK;
449 clear_halt(s, p->devep);
452 urb->buffer = p->data;
453 urb->buffer_length = p->len;
455 if (is_isoc(s, p->devep)) {
456 /* Setup ISOC transfer */
457 urb->type = USBDEVFS_URB_TYPE_ISO;
458 urb->flags = USBDEVFS_URB_ISO_ASAP;
459 urb->number_of_packets = 1;
460 urb->iso_frame_desc[0].length = p->len;
461 } else {
462 /* Setup bulk transfer */
463 urb->type = USBDEVFS_URB_TYPE_BULK;
466 urb->usercontext = s;
468 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
470 dprintf("husb: data submit. ep 0x%x len %u aurb %p\n", urb->endpoint, p->len, aurb);
472 if (ret < 0) {
473 dprintf("husb: submit failed. errno %d\n", errno);
474 async_free(aurb);
476 switch(errno) {
477 case ETIMEDOUT:
478 return USB_RET_NAK;
479 case EPIPE:
480 default:
481 return USB_RET_STALL;
485 usb_defer_packet(p, async_cancel, aurb);
486 return USB_RET_ASYNC;
489 static int ctrl_error(void)
491 if (errno == ETIMEDOUT)
492 return USB_RET_NAK;
493 else
494 return USB_RET_STALL;
497 static int usb_host_set_address(USBHostDevice *s, int addr)
499 dprintf("husb: ctrl set addr %u\n", addr);
500 s->dev.addr = addr;
501 return 0;
504 static int usb_host_set_config(USBHostDevice *s, int config)
506 usb_host_release_interfaces(s);
508 int ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
510 dprintf("husb: ctrl set config %d ret %d errno %d\n", config, ret, errno);
512 if (ret < 0)
513 return ctrl_error();
515 usb_host_claim_interfaces(s, config);
516 return 0;
519 static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
521 struct usbdevfs_setinterface si;
522 int ret;
524 si.interface = iface;
525 si.altsetting = alt;
526 ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
528 dprintf("husb: ctrl set iface %d altset %d ret %d errno %d\n",
529 iface, alt, ret, errno);
531 if (ret < 0)
532 return ctrl_error();
534 usb_linux_update_endp_table(s);
535 return 0;
538 static int usb_host_handle_control(USBHostDevice *s, USBPacket *p)
540 struct usbdevfs_urb *urb;
541 AsyncURB *aurb;
542 int ret, value, index;
545 * Process certain standard device requests.
546 * These are infrequent and are processed synchronously.
548 value = le16_to_cpu(s->ctrl.req.wValue);
549 index = le16_to_cpu(s->ctrl.req.wIndex);
551 dprintf("husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\n",
552 s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index,
553 s->ctrl.len);
555 if (s->ctrl.req.bRequestType == 0) {
556 switch (s->ctrl.req.bRequest) {
557 case USB_REQ_SET_ADDRESS:
558 return usb_host_set_address(s, value);
560 case USB_REQ_SET_CONFIGURATION:
561 return usb_host_set_config(s, value & 0xff);
565 if (s->ctrl.req.bRequestType == 1 &&
566 s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE)
567 return usb_host_set_interface(s, index, value);
569 /* The rest are asynchronous */
571 aurb = async_alloc();
572 if (!aurb) {
573 dprintf("husb: async malloc failed\n");
574 return USB_RET_NAK;
576 aurb->hdev = s;
577 aurb->packet = p;
580 * Setup ctrl transfer.
582 * s->ctrl is layed out such that data buffer immediately follows
583 * 'req' struct which is exactly what usbdevfs expects.
585 urb = &aurb->urb;
587 urb->type = USBDEVFS_URB_TYPE_CONTROL;
588 urb->endpoint = p->devep;
590 urb->buffer = &s->ctrl.req;
591 urb->buffer_length = 8 + s->ctrl.len;
593 urb->usercontext = s;
595 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
597 dprintf("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb);
599 if (ret < 0) {
600 dprintf("husb: submit failed. errno %d\n", errno);
601 async_free(aurb);
603 switch(errno) {
604 case ETIMEDOUT:
605 return USB_RET_NAK;
606 case EPIPE:
607 default:
608 return USB_RET_STALL;
612 usb_defer_packet(p, async_cancel, aurb);
613 return USB_RET_ASYNC;
616 static int do_token_setup(USBDevice *dev, USBPacket *p)
618 USBHostDevice *s = (USBHostDevice *) dev;
619 int ret = 0;
621 if (p->len != 8)
622 return USB_RET_STALL;
624 memcpy(&s->ctrl.req, p->data, 8);
625 s->ctrl.len = le16_to_cpu(s->ctrl.req.wLength);
626 s->ctrl.offset = 0;
627 s->ctrl.state = CTRL_STATE_SETUP;
629 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
630 ret = usb_host_handle_control(s, p);
631 if (ret < 0)
632 return ret;
634 if (ret < s->ctrl.len)
635 s->ctrl.len = ret;
636 s->ctrl.state = CTRL_STATE_DATA;
637 } else {
638 if (s->ctrl.len == 0)
639 s->ctrl.state = CTRL_STATE_ACK;
640 else
641 s->ctrl.state = CTRL_STATE_DATA;
644 return ret;
647 static int do_token_in(USBDevice *dev, USBPacket *p)
649 USBHostDevice *s = (USBHostDevice *) dev;
650 int ret = 0;
652 if (p->devep != 0)
653 return usb_host_handle_data(s, p);
655 switch(s->ctrl.state) {
656 case CTRL_STATE_ACK:
657 if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
658 ret = usb_host_handle_control(s, p);
659 if (ret == USB_RET_ASYNC)
660 return USB_RET_ASYNC;
662 s->ctrl.state = CTRL_STATE_IDLE;
663 return ret > 0 ? 0 : ret;
666 return 0;
668 case CTRL_STATE_DATA:
669 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
670 int len = s->ctrl.len - s->ctrl.offset;
671 if (len > p->len)
672 len = p->len;
673 memcpy(p->data, s->ctrl.buffer + s->ctrl.offset, len);
674 s->ctrl.offset += len;
675 if (s->ctrl.offset >= s->ctrl.len)
676 s->ctrl.state = CTRL_STATE_ACK;
677 return len;
680 s->ctrl.state = CTRL_STATE_IDLE;
681 return USB_RET_STALL;
683 default:
684 return USB_RET_STALL;
688 static int do_token_out(USBDevice *dev, USBPacket *p)
690 USBHostDevice *s = (USBHostDevice *) dev;
692 if (p->devep != 0)
693 return usb_host_handle_data(s, p);
695 switch(s->ctrl.state) {
696 case CTRL_STATE_ACK:
697 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
698 s->ctrl.state = CTRL_STATE_IDLE;
699 /* transfer OK */
700 } else {
701 /* ignore additional output */
703 return 0;
705 case CTRL_STATE_DATA:
706 if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
707 int len = s->ctrl.len - s->ctrl.offset;
708 if (len > p->len)
709 len = p->len;
710 memcpy(s->ctrl.buffer + s->ctrl.offset, p->data, len);
711 s->ctrl.offset += len;
712 if (s->ctrl.offset >= s->ctrl.len)
713 s->ctrl.state = CTRL_STATE_ACK;
714 return len;
717 s->ctrl.state = CTRL_STATE_IDLE;
718 return USB_RET_STALL;
720 default:
721 return USB_RET_STALL;
726 * Packet handler.
727 * Called by the HC (host controller).
729 * Returns length of the transaction or one of the USB_RET_XXX codes.
731 static int usb_host_handle_packet(USBDevice *s, USBPacket *p)
733 switch(p->pid) {
734 case USB_MSG_ATTACH:
735 s->state = USB_STATE_ATTACHED;
736 return 0;
738 case USB_MSG_DETACH:
739 s->state = USB_STATE_NOTATTACHED;
740 return 0;
742 case USB_MSG_RESET:
743 s->remote_wakeup = 0;
744 s->addr = 0;
745 s->state = USB_STATE_DEFAULT;
746 s->handle_reset(s);
747 return 0;
750 /* Rest of the PIDs must match our address */
751 if (s->state < USB_STATE_DEFAULT || p->devaddr != s->addr)
752 return USB_RET_NODEV;
754 switch (p->pid) {
755 case USB_TOKEN_SETUP:
756 return do_token_setup(s, p);
758 case USB_TOKEN_IN:
759 return do_token_in(s, p);
761 case USB_TOKEN_OUT:
762 return do_token_out(s, p);
764 default:
765 return USB_RET_STALL;
769 /* returns 1 on problem encountered or 0 for success */
770 static int usb_linux_update_endp_table(USBHostDevice *s)
772 uint8_t *descriptors;
773 uint8_t devep, type, configuration, alt_interface;
774 struct usbdevfs_ctrltransfer ct;
775 int interface, ret, length, i;
777 ct.bRequestType = USB_DIR_IN;
778 ct.bRequest = USB_REQ_GET_CONFIGURATION;
779 ct.wValue = 0;
780 ct.wIndex = 0;
781 ct.wLength = 1;
782 ct.data = &configuration;
783 ct.timeout = 50;
785 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
786 if (ret < 0) {
787 perror("usb_linux_update_endp_table");
788 return 1;
791 /* in address state */
792 if (configuration == 0)
793 return 1;
795 /* get the desired configuration, interface, and endpoint descriptors
796 * from device description */
797 descriptors = &s->descr[18];
798 length = s->descr_len - 18;
799 i = 0;
801 if (descriptors[i + 1] != USB_DT_CONFIG ||
802 descriptors[i + 5] != configuration) {
803 dprintf("invalid descriptor data - configuration\n");
804 return 1;
806 i += descriptors[i];
808 while (i < length) {
809 if (descriptors[i + 1] != USB_DT_INTERFACE ||
810 (descriptors[i + 1] == USB_DT_INTERFACE &&
811 descriptors[i + 4] == 0)) {
812 i += descriptors[i];
813 continue;
816 interface = descriptors[i + 2];
818 ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
819 ct.bRequest = USB_REQ_GET_INTERFACE;
820 ct.wValue = 0;
821 ct.wIndex = interface;
822 ct.wLength = 1;
823 ct.data = &alt_interface;
824 ct.timeout = 50;
826 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
827 if (ret < 0) {
828 perror("usb_linux_update_endp_table");
829 return 1;
832 /* the current interface descriptor is the active interface
833 * and has endpoints */
834 if (descriptors[i + 3] != alt_interface) {
835 i += descriptors[i];
836 continue;
839 /* advance to the endpoints */
840 while (i < length && descriptors[i +1] != USB_DT_ENDPOINT)
841 i += descriptors[i];
843 if (i >= length)
844 break;
846 while (i < length) {
847 if (descriptors[i + 1] != USB_DT_ENDPOINT)
848 break;
850 devep = descriptors[i + 2];
851 switch (descriptors[i + 3] & 0x3) {
852 case 0x00:
853 type = USBDEVFS_URB_TYPE_CONTROL;
854 break;
855 case 0x01:
856 type = USBDEVFS_URB_TYPE_ISO;
857 break;
858 case 0x02:
859 type = USBDEVFS_URB_TYPE_BULK;
860 break;
861 case 0x03:
862 type = USBDEVFS_URB_TYPE_INTERRUPT;
863 break;
864 default:
865 dprintf("usb_host: malformed endpoint type\n");
866 type = USBDEVFS_URB_TYPE_BULK;
868 s->endp_table[(devep & 0xf) - 1].type = type;
869 s->endp_table[(devep & 0xf) - 1].halted = 0;
871 i += descriptors[i];
874 return 0;
877 static USBDevice *usb_host_device_open_addr(int bus_num, int addr, const char *prod_name)
879 int fd = -1, ret;
880 USBHostDevice *dev = NULL;
881 struct usbdevfs_connectinfo ci;
882 char buf[1024];
884 dev = qemu_mallocz(sizeof(USBHostDevice));
885 if (!dev)
886 goto fail;
888 dev->bus_num = bus_num;
889 dev->addr = addr;
891 printf("husb: open device %d.%d\n", bus_num, addr);
893 snprintf(buf, sizeof(buf), USBDEVFS_PATH "/%03d/%03d",
894 bus_num, addr);
895 fd = open(buf, O_RDWR | O_NONBLOCK);
896 if (fd < 0) {
897 perror(buf);
898 goto fail;
901 /* read the device description */
902 dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
903 if (dev->descr_len <= 0) {
904 perror("husb: reading device data failed");
905 goto fail;
908 #ifdef DEBUG
910 int x;
911 printf("=== begin dumping device descriptor data ===\n");
912 for (x = 0; x < dev->descr_len; x++)
913 printf("%02x ", dev->descr[x]);
914 printf("\n=== end dumping device descriptor data ===\n");
916 #endif
918 dev->fd = fd;
921 * Initial configuration is -1 which makes us claim first
922 * available config. We used to start with 1, which does not
923 * always work. I've seen devices where first config starts
924 * with 2.
926 if (!usb_host_claim_interfaces(dev, -1))
927 goto fail;
929 ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
930 if (ret < 0) {
931 perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
932 goto fail;
935 printf("husb: grabbed usb device %d.%d\n", bus_num, addr);
937 ret = usb_linux_update_endp_table(dev);
938 if (ret)
939 goto fail;
941 if (ci.slow)
942 dev->dev.speed = USB_SPEED_LOW;
943 else
944 dev->dev.speed = USB_SPEED_HIGH;
946 dev->dev.handle_packet = usb_host_handle_packet;
947 dev->dev.handle_reset = usb_host_handle_reset;
948 dev->dev.handle_destroy = usb_host_handle_destroy;
950 if (!prod_name || prod_name[0] == '\0')
951 snprintf(dev->dev.devname, sizeof(dev->dev.devname),
952 "host:%d.%d", bus_num, addr);
953 else
954 pstrcpy(dev->dev.devname, sizeof(dev->dev.devname),
955 prod_name);
957 /* USB devio uses 'write' flag to check for async completions */
958 qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);
960 hostdev_link(dev);
962 return (USBDevice *) dev;
964 fail:
965 if (dev)
966 qemu_free(dev);
968 close(fd);
969 return NULL;
972 static int usb_host_auto_add(const char *spec);
973 static int usb_host_auto_del(const char *spec);
975 USBDevice *usb_host_device_open(const char *devname)
977 int bus_num, addr;
978 char product_name[PRODUCT_NAME_SZ];
980 if (strstr(devname, "auto:")) {
981 usb_host_auto_add(devname);
982 return NULL;
985 if (usb_host_find_device(&bus_num, &addr, product_name, sizeof(product_name),
986 devname) < 0)
987 return NULL;
989 if (hostdev_find(bus_num, addr)) {
990 term_printf("husb: host usb device %d.%d is already open\n", bus_num, addr);
991 return NULL;
994 return usb_host_device_open_addr(bus_num, addr, product_name);
997 int usb_host_device_close(const char *devname)
999 char product_name[PRODUCT_NAME_SZ];
1000 int bus_num, addr;
1001 USBHostDevice *s;
1003 if (strstr(devname, "auto:"))
1004 return usb_host_auto_del(devname);
1006 if (usb_host_find_device(&bus_num, &addr, product_name, sizeof(product_name),
1007 devname) < 0)
1008 return -1;
1010 s = hostdev_find(bus_num, addr);
1011 if (s) {
1012 usb_device_del_addr(0, s->dev.addr);
1013 return 0;
1016 return -1;
1019 static int get_tag_value(char *buf, int buf_size,
1020 const char *str, const char *tag,
1021 const char *stopchars)
1023 const char *p;
1024 char *q;
1025 p = strstr(str, tag);
1026 if (!p)
1027 return -1;
1028 p += strlen(tag);
1029 while (isspace(*p))
1030 p++;
1031 q = buf;
1032 while (*p != '\0' && !strchr(stopchars, *p)) {
1033 if ((q - buf) < (buf_size - 1))
1034 *q++ = *p;
1035 p++;
1037 *q = '\0';
1038 return q - buf;
1041 static int usb_host_scan(void *opaque, USBScanFunc *func)
1043 FILE *f;
1044 char line[1024];
1045 char buf[1024];
1046 int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
1047 int ret;
1048 char product_name[512];
1050 f = fopen(USBDEVFS_PATH "/devices", "r");
1051 if (!f) {
1052 term_printf("husb: could not open %s\n", USBDEVFS_PATH "/devices");
1053 return 0;
1055 device_count = 0;
1056 bus_num = addr = speed = class_id = product_id = vendor_id = 0;
1057 ret = 0;
1058 for(;;) {
1059 if (fgets(line, sizeof(line), f) == NULL)
1060 break;
1061 if (strlen(line) > 0)
1062 line[strlen(line) - 1] = '\0';
1063 if (line[0] == 'T' && line[1] == ':') {
1064 if (device_count && (vendor_id || product_id)) {
1065 /* New device. Add the previously discovered device. */
1066 ret = func(opaque, bus_num, addr, class_id, vendor_id,
1067 product_id, product_name, speed);
1068 if (ret)
1069 goto the_end;
1071 if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0)
1072 goto fail;
1073 bus_num = atoi(buf);
1074 if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0)
1075 goto fail;
1076 addr = atoi(buf);
1077 if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0)
1078 goto fail;
1079 if (!strcmp(buf, "480"))
1080 speed = USB_SPEED_HIGH;
1081 else if (!strcmp(buf, "1.5"))
1082 speed = USB_SPEED_LOW;
1083 else
1084 speed = USB_SPEED_FULL;
1085 product_name[0] = '\0';
1086 class_id = 0xff;
1087 device_count++;
1088 product_id = 0;
1089 vendor_id = 0;
1090 } else if (line[0] == 'P' && line[1] == ':') {
1091 if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0)
1092 goto fail;
1093 vendor_id = strtoul(buf, NULL, 16);
1094 if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0)
1095 goto fail;
1096 product_id = strtoul(buf, NULL, 16);
1097 } else if (line[0] == 'S' && line[1] == ':') {
1098 if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0)
1099 goto fail;
1100 pstrcpy(product_name, sizeof(product_name), buf);
1101 } else if (line[0] == 'D' && line[1] == ':') {
1102 if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0)
1103 goto fail;
1104 class_id = strtoul(buf, NULL, 16);
1106 fail: ;
1108 if (device_count && (vendor_id || product_id)) {
1109 /* Add the last device. */
1110 ret = func(opaque, bus_num, addr, class_id, vendor_id,
1111 product_id, product_name, speed);
1113 the_end:
1114 fclose(f);
1115 return ret;
1118 struct USBAutoFilter {
1119 struct USBAutoFilter *next;
1120 int bus_num;
1121 int addr;
1122 int vendor_id;
1123 int product_id;
1126 static QEMUTimer *usb_auto_timer;
1127 static struct USBAutoFilter *usb_auto_filter;
1129 static int usb_host_auto_scan(void *opaque, int bus_num, int addr,
1130 int class_id, int vendor_id, int product_id,
1131 const char *product_name, int speed)
1133 struct USBAutoFilter *f;
1134 struct USBDevice *dev;
1136 /* Ignore hubs */
1137 if (class_id == 9)
1138 return 0;
1140 for (f = usb_auto_filter; f; f = f->next) {
1141 if (f->bus_num >= 0 && f->bus_num != bus_num)
1142 continue;
1144 if (f->addr >= 0 && f->addr != addr)
1145 continue;
1147 if (f->vendor_id >= 0 && f->vendor_id != vendor_id)
1148 continue;
1150 if (f->product_id >= 0 && f->product_id != product_id)
1151 continue;
1153 /* We got a match */
1155 /* Allredy attached ? */
1156 if (hostdev_find(bus_num, addr))
1157 return 0;
1159 dprintf("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1161 dev = usb_host_device_open_addr(bus_num, addr, product_name);
1162 if (dev)
1163 usb_device_add_dev(dev);
1166 return 0;
1169 static void usb_host_auto_timer(void *unused)
1171 usb_host_scan(NULL, usb_host_auto_scan);
1172 qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000);
1176 * Autoconnect filter
1177 * Format:
1178 * auto:bus:dev[:vid:pid]
1179 * auto:bus.dev[:vid:pid]
1181 * bus - bus number (dec, * means any)
1182 * dev - device number (dec, * means any)
1183 * vid - vendor id (hex, * means any)
1184 * pid - product id (hex, * means any)
1186 * See 'lsusb' output.
1188 static int parse_filter(const char *spec, struct USBAutoFilter *f)
1190 enum { BUS, DEV, VID, PID, DONE };
1191 const char *p = spec;
1192 int i;
1194 f->bus_num = -1;
1195 f->addr = -1;
1196 f->vendor_id = -1;
1197 f->product_id = -1;
1199 for (i = BUS; i < DONE; i++) {
1200 p = strpbrk(p, ":.");
1201 if (!p) break;
1202 p++;
1204 if (*p == '*')
1205 continue;
1207 switch(i) {
1208 case BUS: f->bus_num = strtol(p, NULL, 10); break;
1209 case DEV: f->addr = strtol(p, NULL, 10); break;
1210 case VID: f->vendor_id = strtol(p, NULL, 16); break;
1211 case PID: f->product_id = strtol(p, NULL, 16); break;
1215 if (i < DEV) {
1216 fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1217 return -1;
1220 return 0;
1223 static int match_filter(const struct USBAutoFilter *f1,
1224 const struct USBAutoFilter *f2)
1226 return f1->bus_num == f2->bus_num &&
1227 f1->addr == f2->addr &&
1228 f1->vendor_id == f2->vendor_id &&
1229 f1->product_id == f2->product_id;
1232 static int usb_host_auto_add(const char *spec)
1234 struct USBAutoFilter filter, *f;
1236 if (parse_filter(spec, &filter) < 0)
1237 return -1;
1239 f = qemu_mallocz(sizeof(*f));
1240 if (!f) {
1241 fprintf(stderr, "husb: failed to allocate auto filter\n");
1242 return -1;
1245 *f = filter;
1247 if (!usb_auto_filter) {
1249 * First entry. Init and start the monitor.
1250 * Right now we're using timer to check for new devices.
1251 * If this turns out to be too expensive we can move that into a
1252 * separate thread.
1254 usb_auto_timer = qemu_new_timer(rt_clock, usb_host_auto_timer, NULL);
1255 if (!usb_auto_timer) {
1256 fprintf(stderr, "husb: failed to allocate auto scan timer\n");
1257 qemu_free(f);
1258 return -1;
1261 /* Check for new devices every two seconds */
1262 qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000);
1265 dprintf("husb: added auto filter: bus_num %d addr %d vid %d pid %d\n",
1266 f->bus_num, f->addr, f->vendor_id, f->product_id);
1268 f->next = usb_auto_filter;
1269 usb_auto_filter = f;
1271 return 0;
1274 static int usb_host_auto_del(const char *spec)
1276 struct USBAutoFilter *pf = usb_auto_filter;
1277 struct USBAutoFilter **prev = &usb_auto_filter;
1278 struct USBAutoFilter filter;
1280 if (parse_filter(spec, &filter) < 0)
1281 return -1;
1283 while (pf) {
1284 if (match_filter(pf, &filter)) {
1285 dprintf("husb: removed auto filter: bus_num %d addr %d vid %d pid %d\n",
1286 pf->bus_num, pf->addr, pf->vendor_id, pf->product_id);
1288 *prev = pf->next;
1290 if (!usb_auto_filter) {
1291 /* No more filters. Stop scanning. */
1292 qemu_del_timer(usb_auto_timer);
1293 qemu_free_timer(usb_auto_timer);
1296 return 0;
1299 prev = &pf->next;
1300 pf = pf->next;
1303 return -1;
1306 typedef struct FindDeviceState {
1307 int vendor_id;
1308 int product_id;
1309 int bus_num;
1310 int addr;
1311 char product_name[PRODUCT_NAME_SZ];
1312 } FindDeviceState;
1314 static int usb_host_find_device_scan(void *opaque, int bus_num, int addr,
1315 int class_id,
1316 int vendor_id, int product_id,
1317 const char *product_name, int speed)
1319 FindDeviceState *s = opaque;
1320 if ((vendor_id == s->vendor_id &&
1321 product_id == s->product_id) ||
1322 (bus_num == s->bus_num &&
1323 addr == s->addr)) {
1324 pstrcpy(s->product_name, PRODUCT_NAME_SZ, product_name);
1325 s->bus_num = bus_num;
1326 s->addr = addr;
1327 return 1;
1328 } else {
1329 return 0;
1333 /* the syntax is :
1334 'bus.addr' (decimal numbers) or
1335 'vendor_id:product_id' (hexa numbers) */
1336 static int usb_host_find_device(int *pbus_num, int *paddr,
1337 char *product_name, int product_name_size,
1338 const char *devname)
1340 const char *p;
1341 int ret;
1342 FindDeviceState fs;
1344 p = strchr(devname, '.');
1345 if (p) {
1346 *pbus_num = strtoul(devname, NULL, 0);
1347 *paddr = strtoul(p + 1, NULL, 0);
1348 fs.bus_num = *pbus_num;
1349 fs.addr = *paddr;
1350 ret = usb_host_scan(&fs, usb_host_find_device_scan);
1351 if (ret)
1352 pstrcpy(product_name, product_name_size, fs.product_name);
1353 return 0;
1356 p = strchr(devname, ':');
1357 if (p) {
1358 fs.vendor_id = strtoul(devname, NULL, 16);
1359 fs.product_id = strtoul(p + 1, NULL, 16);
1360 ret = usb_host_scan(&fs, usb_host_find_device_scan);
1361 if (ret) {
1362 *pbus_num = fs.bus_num;
1363 *paddr = fs.addr;
1364 pstrcpy(product_name, product_name_size, fs.product_name);
1365 return 0;
1368 return -1;
1371 /**********************/
1372 /* USB host device info */
1374 struct usb_class_info {
1375 int class;
1376 const char *class_name;
1379 static const struct usb_class_info usb_class_info[] = {
1380 { USB_CLASS_AUDIO, "Audio"},
1381 { USB_CLASS_COMM, "Communication"},
1382 { USB_CLASS_HID, "HID"},
1383 { USB_CLASS_HUB, "Hub" },
1384 { USB_CLASS_PHYSICAL, "Physical" },
1385 { USB_CLASS_PRINTER, "Printer" },
1386 { USB_CLASS_MASS_STORAGE, "Storage" },
1387 { USB_CLASS_CDC_DATA, "Data" },
1388 { USB_CLASS_APP_SPEC, "Application Specific" },
1389 { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1390 { USB_CLASS_STILL_IMAGE, "Still Image" },
1391 { USB_CLASS_CSCID, "Smart Card" },
1392 { USB_CLASS_CONTENT_SEC, "Content Security" },
1393 { -1, NULL }
1396 static const char *usb_class_str(uint8_t class)
1398 const struct usb_class_info *p;
1399 for(p = usb_class_info; p->class != -1; p++) {
1400 if (p->class == class)
1401 break;
1403 return p->class_name;
1406 static void usb_info_device(int bus_num, int addr, int class_id,
1407 int vendor_id, int product_id,
1408 const char *product_name,
1409 int speed)
1411 const char *class_str, *speed_str;
1413 switch(speed) {
1414 case USB_SPEED_LOW:
1415 speed_str = "1.5";
1416 break;
1417 case USB_SPEED_FULL:
1418 speed_str = "12";
1419 break;
1420 case USB_SPEED_HIGH:
1421 speed_str = "480";
1422 break;
1423 default:
1424 speed_str = "?";
1425 break;
1428 term_printf(" Device %d.%d, speed %s Mb/s\n",
1429 bus_num, addr, speed_str);
1430 class_str = usb_class_str(class_id);
1431 if (class_str)
1432 term_printf(" %s:", class_str);
1433 else
1434 term_printf(" Class %02x:", class_id);
1435 term_printf(" USB device %04x:%04x", vendor_id, product_id);
1436 if (product_name[0] != '\0')
1437 term_printf(", %s", product_name);
1438 term_printf("\n");
1441 static int usb_host_info_device(void *opaque, int bus_num, int addr,
1442 int class_id,
1443 int vendor_id, int product_id,
1444 const char *product_name,
1445 int speed)
1447 usb_info_device(bus_num, addr, class_id, vendor_id, product_id,
1448 product_name, speed);
1449 return 0;
1452 static void dec2str(int val, char *str, size_t size)
1454 if (val == -1)
1455 snprintf(str, size, "*");
1456 else
1457 snprintf(str, size, "%d", val);
1460 static void hex2str(int val, char *str, size_t size)
1462 if (val == -1)
1463 snprintf(str, size, "*");
1464 else
1465 snprintf(str, size, "%x", val);
1468 void usb_host_info(void)
1470 struct USBAutoFilter *f;
1472 usb_host_scan(NULL, usb_host_info_device);
1474 if (usb_auto_filter)
1475 term_printf(" Auto filters:\n");
1476 for (f = usb_auto_filter; f; f = f->next) {
1477 char bus[10], addr[10], vid[10], pid[10];
1478 dec2str(f->bus_num, bus, sizeof(bus));
1479 dec2str(f->addr, addr, sizeof(addr));
1480 hex2str(f->vendor_id, vid, sizeof(vid));
1481 hex2str(f->product_id, pid, sizeof(pid));
1482 term_printf(" Device %s.%s ID %s:%s\n", bus, addr, vid, pid);
1486 #else
1488 #include "hw/usb.h"
1490 void usb_host_info(void)
1492 term_printf("USB host devices not supported\n");
1495 /* XXX: modify configure to compile the right host driver */
1496 USBDevice *usb_host_device_open(const char *devname)
1498 return NULL;
1501 int usb_host_device_close(const char *devname)
1503 return 0;
1506 #endif