USB iso transfers support for the linux redirector and for UHCI, by Arnon Gilboa.
[qemu] / usb-linux.c
1 /*
2  * Linux host USB redirector
3  *
4  * Copyright (c) 2005 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include "vl.h"
25
26 #if defined(__linux__)
27 #include <dirent.h>
28 #include <sys/ioctl.h>
29 #include <linux/usbdevice_fs.h>
30 #include <linux/version.h>
31 #include <signal.h>
32
33 /* We redefine it to avoid version problems */
34 struct usb_ctrltransfer {
35     uint8_t  bRequestType;
36     uint8_t  bRequest;
37     uint16_t wValue;
38     uint16_t wIndex;
39     uint16_t wLength;
40     uint32_t timeout;
41     void *data;
42 };
43
44 typedef int USBScanFunc(void *opaque, int bus_num, int addr, int class_id,
45                         int vendor_id, int product_id,
46                         const char *product_name, int speed);
47 static int usb_host_find_device(int *pbus_num, int *paddr,
48                                 char *product_name, int product_name_size,
49                                 const char *devname);
50
51 //#define DEBUG
52 //#define DEBUG_ISOCH
53 //#define USE_ASYNCIO
54
55 #define USBDEVFS_PATH "/proc/bus/usb"
56 #define PRODUCT_NAME_SZ 32
57 #define SIG_ISOCOMPLETE (SIGRTMIN+7)
58 #define MAX_ENDPOINTS 16
59
60 struct sigaction sigact;
61
62 /* endpoint association data */
63 struct endp_data {
64     uint8_t type;
65 };
66
67 /* FIXME: move USBPacket to PendingURB */
68 typedef struct USBHostDevice {
69     USBDevice dev;
70     int fd;
71     USBPacket *packet;
72     struct endp_data endp_table[MAX_ENDPOINTS];
73     int configuration;
74     uint8_t descr[1024];
75     int descr_len;
76     int urbs_ready;
77 } USBHostDevice;
78
79 typedef struct PendingURB {
80     struct usbdevfs_urb *urb;
81     USBHostDevice *dev;
82     QEMUBH *bh;
83     int status;
84     struct PendingURB *next;
85 } PendingURB;
86
87 PendingURB *pending_urbs = NULL;
88
89 int add_pending_urb(struct usbdevfs_urb *urb)
90 {
91     PendingURB *purb = qemu_mallocz(sizeof(PendingURB));
92     if (purb) {
93         purb->urb = urb;
94         purb->dev = NULL;
95         purb->bh = NULL;
96         purb->status = 0;
97         purb->next = pending_urbs;
98         pending_urbs = purb;
99         return 1;
100     }
101     return 0;
102 }
103
104 int del_pending_urb(struct usbdevfs_urb *urb)
105 {
106     PendingURB *purb = pending_urbs;
107     PendingURB *prev = NULL;
108
109     while (purb && purb->urb != urb) {
110         prev = purb;
111         purb = purb->next;
112     }
113
114     if (purb && purb->urb == urb) {
115         if (prev) {
116             prev->next = purb->next;
117         } else {
118             pending_urbs = purb->next;
119         }
120         qemu_free(purb);
121         return 1;
122     }
123     return 0;
124 }
125
126 PendingURB *get_pending_urb(struct usbdevfs_urb *urb)
127 {
128     PendingURB *purb = pending_urbs;
129
130     while (purb && purb->urb != urb) {
131         purb = purb->next;
132     }
133
134     if (purb && purb->urb == urb) {
135         return purb;
136     }
137     return NULL;
138 }
139
140 static int usb_host_update_interfaces(USBHostDevice *dev, int configuration)
141 {
142     int dev_descr_len, config_descr_len;
143     int interface, nb_interfaces, nb_configurations;
144     int ret, i;
145
146     if (configuration == 0) /* address state - ignore */
147         return 1;
148
149     i = 0;
150     dev_descr_len = dev->descr[0];
151     if (dev_descr_len > dev->descr_len)
152         goto fail;
153     nb_configurations = dev->descr[17];
154
155     i += dev_descr_len;
156     while (i < dev->descr_len) {
157 #ifdef DEBUG
158         printf("i is %d, descr_len is %d, dl %d, dt %d\n", i, dev->descr_len,
159                dev->descr[i], dev->descr[i+1]);
160 #endif
161         if (dev->descr[i+1] != USB_DT_CONFIG) {
162             i += dev->descr[i];
163             continue;
164         }
165         config_descr_len = dev->descr[i];
166
167         if (configuration == dev->descr[i + 5])
168             break;
169
170         i += config_descr_len;
171     }
172
173     if (i >= dev->descr_len) {
174         printf("usb_host: error - device has no matching configuration\n");
175         goto fail;
176     }
177     nb_interfaces = dev->descr[i + 4];
178
179 #ifdef USBDEVFS_DISCONNECT
180     /* earlier Linux 2.4 do not support that */
181     {
182         struct usbdevfs_ioctl ctrl;
183         for (interface = 0; interface < nb_interfaces; interface++) {
184             ctrl.ioctl_code = USBDEVFS_DISCONNECT;
185             ctrl.ifno = interface;
186             ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
187             if (ret < 0 && errno != ENODATA) {
188                 perror("USBDEVFS_DISCONNECT");
189                 goto fail;
190             }
191         }
192     }
193 #endif
194
195     /* XXX: only grab if all interfaces are free */
196     for (interface = 0; interface < nb_interfaces; interface++) {
197         ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
198         if (ret < 0) {
199             if (errno == EBUSY) {
200                 fprintf(stderr,
201                         "usb_host: warning - device already grabbed\n");
202             } else {
203                 perror("USBDEVFS_CLAIMINTERFACE");
204             }
205         fail:
206             return 0;
207         }
208     }
209
210 #ifdef DEBUG
211     printf("usb_host: %d interfaces claimed for configuration %d\n",
212            nb_interfaces, configuration);
213 #endif
214
215     return 1;
216 }
217
218 static void usb_host_handle_reset(USBDevice *dev)
219 {
220 #if 0
221     USBHostDevice *s = (USBHostDevice *)dev;
222     /* USBDEVFS_RESET, but not the first time as it has already be
223        done by the host OS */
224     ioctl(s->fd, USBDEVFS_RESET);
225 #endif
226 }
227
228 static void usb_host_handle_destroy(USBDevice *dev)
229 {
230     USBHostDevice *s = (USBHostDevice *)dev;
231
232     if (s->fd >= 0)
233         close(s->fd);
234     qemu_free(s);
235 }
236
237 static int usb_linux_update_endp_table(USBHostDevice *s);
238
239 static int usb_host_handle_control(USBDevice *dev,
240                                    int request,
241                                    int value,
242                                    int index,
243                                    int length,
244                                    uint8_t *data)
245 {
246     USBHostDevice *s = (USBHostDevice *)dev;
247     struct usb_ctrltransfer ct;
248     struct usbdevfs_setinterface si;
249     int intf_update_required = 0;
250     int ret;
251
252     if (request == (DeviceOutRequest | USB_REQ_SET_ADDRESS)) {
253         /* specific SET_ADDRESS support */
254         dev->addr = value;
255         return 0;
256     } else if (request == ((USB_RECIP_INTERFACE << 8) |
257                            USB_REQ_SET_INTERFACE)) {
258         /* set alternate setting for the interface */
259         si.interface = index;
260         si.altsetting = value;
261         ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
262         usb_linux_update_endp_table(s);
263     } else if (request == (DeviceOutRequest | USB_REQ_SET_CONFIGURATION)) {
264 #ifdef DEBUG
265         printf("usb_host_handle_control: SET_CONFIGURATION request - "
266                "config %d\n", value & 0xff);
267 #endif
268         if (s->configuration != (value & 0xff)) {
269             s->configuration = (value & 0xff);
270             intf_update_required = 1;
271         }
272         goto do_request;
273     } else {
274     do_request:
275         ct.bRequestType = request >> 8;
276         ct.bRequest = request;
277         ct.wValue = value;
278         ct.wIndex = index;
279         ct.wLength = length;
280         ct.timeout = 50;
281         ct.data = data;
282         ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
283     }
284
285     if (ret < 0) {
286         switch(errno) {
287         case ETIMEDOUT:
288             return USB_RET_NAK;
289         default:
290             return USB_RET_STALL;
291         }
292     } else {
293         if (intf_update_required) {
294 #ifdef DEBUG
295             printf("usb_host_handle_control: updating interfaces\n");
296 #endif
297             usb_host_update_interfaces(s, value & 0xff);
298         }
299         return ret;
300     }
301 }
302
303 static int usb_host_handle_isoch(USBDevice *dev, USBPacket *p);
304
305 static int usb_host_handle_data(USBDevice *dev, USBPacket *p)
306 {
307     USBHostDevice *s = (USBHostDevice *)dev;
308     struct usbdevfs_bulktransfer bt;
309     int ret;
310     uint8_t devep = p->devep;
311
312     if (s->endp_table[p->devep - 1].type == USBDEVFS_URB_TYPE_ISO) {
313         return usb_host_handle_isoch(dev, p);
314     }
315
316     /* XXX: optimize and handle all data types by looking at the
317        config descriptor */
318     if (p->pid == USB_TOKEN_IN)
319         devep |= 0x80;
320     bt.ep = devep;
321     bt.len = p->len;
322     bt.timeout = 50;
323     bt.data = p->data;
324     ret = ioctl(s->fd, USBDEVFS_BULK, &bt);
325     if (ret < 0) {
326         switch(errno) {
327         case ETIMEDOUT:
328             return USB_RET_NAK;
329         case EPIPE:
330         default:
331 #ifdef DEBUG
332             printf("handle_data: errno=%d\n", errno);
333 #endif
334             return USB_RET_STALL;
335         }
336     } else {
337         return ret;
338     }
339 }
340
341 static void usb_linux_bh_cb(void *opaque);
342
343 void isoch_done(int signum, siginfo_t *info, void *context) {
344     struct usbdevfs_urb *urb = (struct usbdevfs_urb *)info->si_addr;
345     USBHostDevice *s = (USBHostDevice *)urb->usercontext;
346     PendingURB *purb;
347
348     if (info->si_code != SI_ASYNCIO ||
349         info->si_signo != SIG_ISOCOMPLETE) {
350         return;
351     }
352
353     purb = get_pending_urb(urb);
354     if (purb) {
355         purb->bh = qemu_bh_new(usb_linux_bh_cb, purb);
356         if (purb->bh) {
357             purb->dev = s;
358             purb->status = info->si_errno;
359             qemu_bh_schedule(purb->bh);
360         }
361     }
362 }
363
364 static int usb_host_handle_isoch(USBDevice *dev, USBPacket *p)
365 {
366     USBHostDevice *s = (USBHostDevice *)dev;
367     struct usbdevfs_urb *urb, *purb = NULL;
368     int ret;
369     uint8_t devep = p->devep;
370
371     if (p->pid == USB_TOKEN_IN)
372         devep |= 0x80;
373
374     urb = qemu_mallocz(sizeof(struct usbdevfs_urb) +
375                        sizeof(struct usbdevfs_iso_packet_desc));
376     if (!urb) {
377         printf("usb_host_handle_isoch: malloc failed\n");
378         return 0;
379     }
380
381     urb->type = USBDEVFS_URB_TYPE_ISO;
382     urb->endpoint = devep;
383     urb->status = 0;
384     urb->flags = USBDEVFS_URB_ISO_ASAP;
385     urb->buffer = p->data;
386     urb->buffer_length = p->len;
387     urb->actual_length = 0;
388     urb->start_frame = 0;
389     urb->error_count = 0;
390 #ifdef USE_ASYNCIO
391     urb->signr = SIG_ISOCOMPLETE;
392 #else
393     urb->signr = 0;
394 #endif
395     urb->usercontext = s;
396     urb->number_of_packets = 1;
397     urb->iso_frame_desc[0].length = p->len;
398     urb->iso_frame_desc[0].actual_length = 0;
399     urb->iso_frame_desc[0].status = 0;
400     ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
401     if (ret == 0) {
402         if (!add_pending_urb(urb)) {
403             printf("usb_host_handle_isoch: add_pending_urb failed %p\n", urb);
404         }
405     } else {
406         printf("usb_host_handle_isoch: SUBMITURB ioctl=%d errno=%d\n",
407                ret, errno);
408         qemu_free(urb);
409         switch(errno) {
410         case ETIMEDOUT:
411             return USB_RET_NAK;
412         case EPIPE:
413         default:
414             return USB_RET_STALL;
415         }
416     }
417 #ifdef USE_ASYNCIO
418     /* FIXME: handle urbs_ready together with sync io
419      * workaround for injecting the signaled urbs into current frame */
420     if (s->urbs_ready > 0) {
421         ret = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &purb);
422         if (ret == 0) {
423             ret = purb->actual_length;
424             qemu_free(purb);
425             s->urbs_ready--;
426         }
427         return ret;
428     }
429     s->packet = p;
430     return USB_RET_ASYNC;
431 #else
432     ret = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &purb);
433     if (ret == 0) {
434         if (del_pending_urb(purb)) {
435             ret = purb->actual_length;
436             qemu_free(purb);
437         } else {
438             printf("usb_host_handle_isoch: del_pending_urb failed %p\n", purb);
439         }
440     } else {
441 #ifdef DEBUG_ISOCH
442         printf("usb_host_handle_isoch: REAPURBNDELAY ioctl=%d errno=%d\n",
443                ret, errno);
444 #endif
445     }
446     return ret;
447 #endif
448 }
449
450 static void usb_linux_bh_cb(void *opaque)
451 {
452     PendingURB *pending_urb = (PendingURB *)opaque;
453     USBHostDevice *s = pending_urb->dev;
454     struct usbdevfs_urb *purb = NULL;
455     USBPacket *p = s->packet;
456     int ret;
457
458     /* FIXME: handle purb->status */
459     qemu_free(pending_urb->bh);
460     del_pending_urb(pending_urb->urb);
461
462     if (!p) {
463         s->urbs_ready++;
464         return;
465     }
466
467     ret = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &purb);
468     if (ret < 0) {
469         printf("usb_linux_bh_cb: REAPURBNDELAY ioctl=%d errno=%d\n",
470                ret, errno);
471         return;
472     }
473
474 #ifdef DEBUG_ISOCH
475     if (purb == pending_urb->urb) {
476         printf("usb_linux_bh_cb: urb mismatch reaped=%p pending=%p\n",
477                purb, urb);
478     }
479 #endif
480
481     p->len = purb->actual_length;
482     usb_packet_complete(p);
483     qemu_free(purb);
484     s->packet = NULL;
485 }
486
487 /* returns 1 on problem encountered or 0 for success */
488 static int usb_linux_update_endp_table(USBHostDevice *s)
489 {
490     uint8_t *descriptors;
491     uint8_t devep, type, configuration, alt_interface;
492     struct usb_ctrltransfer ct;
493     int interface, ret, length, i;
494
495     ct.bRequestType = USB_DIR_IN;
496     ct.bRequest = USB_REQ_GET_CONFIGURATION;
497     ct.wValue = 0;
498     ct.wIndex = 0;
499     ct.wLength = 1;
500     ct.data = &configuration;
501     ct.timeout = 50;
502
503     ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
504     if (ret < 0) {
505         perror("usb_linux_update_endp_table");
506         return 1;
507     }
508
509     /* in address state */
510     if (configuration == 0)
511         return 1;
512
513     /* get the desired configuration, interface, and endpoint descriptors
514      * from device description */
515     descriptors = &s->descr[18];
516     length = s->descr_len - 18;
517     i = 0;
518
519     if (descriptors[i + 1] != USB_DT_CONFIG ||
520         descriptors[i + 5] != configuration) {
521         printf("invalid descriptor data - configuration\n");
522         return 1;
523     }
524     i += descriptors[i];
525
526     while (i < length) {
527         if (descriptors[i + 1] != USB_DT_INTERFACE ||
528             (descriptors[i + 1] == USB_DT_INTERFACE &&
529              descriptors[i + 4] == 0)) {
530             i += descriptors[i];
531             continue;
532         }
533
534         interface = descriptors[i + 2];
535
536         ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
537         ct.bRequest = USB_REQ_GET_INTERFACE;
538         ct.wValue = 0;
539         ct.wIndex = interface;
540         ct.wLength = 1;
541         ct.data = &alt_interface;
542         ct.timeout = 50;
543
544         ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
545         if (ret < 0) {
546             perror("usb_linux_update_endp_table");
547             return 1;
548         }
549
550         /* the current interface descriptor is the active interface
551          * and has endpoints */
552         if (descriptors[i + 3] != alt_interface) {
553             i += descriptors[i];
554             continue;
555         }
556
557         /* advance to the endpoints */
558         while (i < length && descriptors[i +1] != USB_DT_ENDPOINT)
559             i += descriptors[i];
560
561         if (i >= length)
562             break;
563
564         while (i < length) {
565             if (descriptors[i + 1] != USB_DT_ENDPOINT)
566                 break;
567
568             devep = descriptors[i + 2];
569             switch (descriptors[i + 3] & 0x3) {
570             case 0x00:
571                 type = USBDEVFS_URB_TYPE_CONTROL;
572                 break;
573             case 0x01:
574                 type = USBDEVFS_URB_TYPE_ISO;
575                 break;
576             case 0x02:
577                 type = USBDEVFS_URB_TYPE_BULK;
578                 break;
579             case 0x03:
580                 type = USBDEVFS_URB_TYPE_INTERRUPT;
581                 break;
582             default:
583                 printf("usb_host: malformed endpoint type\n");
584                 type = USBDEVFS_URB_TYPE_BULK;
585             }
586             s->endp_table[(devep & 0xf) - 1].type = type;
587
588             i += descriptors[i];
589         }
590     }
591     return 0;
592 }
593
594 /* XXX: exclude high speed devices or implement EHCI */
595 USBDevice *usb_host_device_open(const char *devname)
596 {
597     int fd = -1, ret;
598     USBHostDevice *dev = NULL;
599     struct usbdevfs_connectinfo ci;
600     char buf[1024];
601     int bus_num, addr;
602     char product_name[PRODUCT_NAME_SZ];
603
604     dev = qemu_mallocz(sizeof(USBHostDevice));
605     if (!dev)
606         goto fail;
607
608 #ifdef DEBUG_ISOCH
609     printf("usb_host_device_open %s\n", devname);
610 #endif
611     if (usb_host_find_device(&bus_num, &addr,
612                              product_name, sizeof(product_name),
613                              devname) < 0)
614         return NULL;
615
616     snprintf(buf, sizeof(buf), USBDEVFS_PATH "/%03d/%03d",
617              bus_num, addr);
618     fd = open(buf, O_RDWR | O_NONBLOCK);
619     if (fd < 0) {
620         perror(buf);
621         return NULL;
622     }
623
624     /* read the device description */
625     dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
626     if (dev->descr_len <= 0) {
627         perror("usb_host_update_interfaces: reading device data failed");
628         goto fail;
629     }
630
631 #ifdef DEBUG
632     {
633         int x;
634         printf("=== begin dumping device descriptor data ===\n");
635         for (x = 0; x < dev->descr_len; x++)
636             printf("%02x ", dev->descr[x]);
637         printf("\n=== end dumping device descriptor data ===\n");
638     }
639 #endif
640
641     dev->fd = fd;
642     dev->configuration = 1;
643
644     /* XXX - do something about initial configuration */
645     if (!usb_host_update_interfaces(dev, 1))
646         goto fail;
647
648     ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
649     if (ret < 0) {
650         perror("USBDEVFS_CONNECTINFO");
651         goto fail;
652     }
653
654 #ifdef DEBUG
655     printf("host USB device %d.%d grabbed\n", bus_num, addr);
656 #endif
657
658     ret = usb_linux_update_endp_table(dev);
659     if (ret)
660         goto fail;
661
662     if (ci.slow)
663         dev->dev.speed = USB_SPEED_LOW;
664     else
665         dev->dev.speed = USB_SPEED_HIGH;
666     dev->dev.handle_packet = usb_generic_handle_packet;
667
668     dev->dev.handle_reset = usb_host_handle_reset;
669     dev->dev.handle_control = usb_host_handle_control;
670     dev->dev.handle_data = usb_host_handle_data;
671     dev->dev.handle_destroy = usb_host_handle_destroy;
672
673     if (product_name[0] == '\0')
674         snprintf(dev->dev.devname, sizeof(dev->dev.devname),
675                  "host:%s", devname);
676     else
677         pstrcpy(dev->dev.devname, sizeof(dev->dev.devname),
678                 product_name);
679
680 #ifdef USE_ASYNCIO
681     /* set up the signal handlers */
682     sigemptyset(&sigact.sa_mask);
683     sigact.sa_sigaction = isoch_done;
684     sigact.sa_flags = SA_SIGINFO;
685     sigact.sa_restorer = 0;
686     ret = sigaction(SIG_ISOCOMPLETE, &sigact, NULL);
687     if (ret < 0) {
688         printf("sigaction SIG_ISOCOMPLETE=%d errno=%d\n", ret, errno);
689     }
690 #endif
691     dev->urbs_ready = 0;
692     return (USBDevice *)dev;
693 fail:
694     if (dev)
695         qemu_free(dev);
696     close(fd);
697     return NULL;
698 }
699
700 static int get_tag_value(char *buf, int buf_size,
701                          const char *str, const char *tag,
702                          const char *stopchars)
703 {
704     const char *p;
705     char *q;
706     p = strstr(str, tag);
707     if (!p)
708         return -1;
709     p += strlen(tag);
710     while (isspace(*p))
711         p++;
712     q = buf;
713     while (*p != '\0' && !strchr(stopchars, *p)) {
714         if ((q - buf) < (buf_size - 1))
715             *q++ = *p;
716         p++;
717     }
718     *q = '\0';
719     return q - buf;
720 }
721
722 static int usb_host_scan(void *opaque, USBScanFunc *func)
723 {
724     FILE *f;
725     char line[1024];
726     char buf[1024];
727     int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
728     int ret;
729     char product_name[512];
730
731     f = fopen(USBDEVFS_PATH "/devices", "r");
732     if (!f) {
733         term_printf("Could not open %s\n", USBDEVFS_PATH "/devices");
734         return 0;
735     }
736     device_count = 0;
737     bus_num = addr = speed = class_id = product_id = vendor_id = 0;
738     ret = 0;
739     for(;;) {
740         if (fgets(line, sizeof(line), f) == NULL)
741             break;
742         if (strlen(line) > 0)
743             line[strlen(line) - 1] = '\0';
744         if (line[0] == 'T' && line[1] == ':') {
745             if (device_count && (vendor_id || product_id)) {
746                 /* New device.  Add the previously discovered device.  */
747                 ret = func(opaque, bus_num, addr, class_id, vendor_id,
748                            product_id, product_name, speed);
749                 if (ret)
750                     goto the_end;
751             }
752             if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0)
753                 goto fail;
754             bus_num = atoi(buf);
755             if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0)
756                 goto fail;
757             addr = atoi(buf);
758             if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0)
759                 goto fail;
760             if (!strcmp(buf, "480"))
761                 speed = USB_SPEED_HIGH;
762             else if (!strcmp(buf, "1.5"))
763                 speed = USB_SPEED_LOW;
764             else
765                 speed = USB_SPEED_FULL;
766             product_name[0] = '\0';
767             class_id = 0xff;
768             device_count++;
769             product_id = 0;
770             vendor_id = 0;
771         } else if (line[0] == 'P' && line[1] == ':') {
772             if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0)
773                 goto fail;
774             vendor_id = strtoul(buf, NULL, 16);
775             if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0)
776                 goto fail;
777             product_id = strtoul(buf, NULL, 16);
778         } else if (line[0] == 'S' && line[1] == ':') {
779             if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0)
780                 goto fail;
781             pstrcpy(product_name, sizeof(product_name), buf);
782         } else if (line[0] == 'D' && line[1] == ':') {
783             if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0)
784                 goto fail;
785             class_id = strtoul(buf, NULL, 16);
786         }
787     fail: ;
788     }
789     if (device_count && (vendor_id || product_id)) {
790         /* Add the last device.  */
791         ret = func(opaque, bus_num, addr, class_id, vendor_id,
792                    product_id, product_name, speed);
793     }
794  the_end:
795     fclose(f);
796     return ret;
797 }
798
799 typedef struct FindDeviceState {
800     int vendor_id;
801     int product_id;
802     int bus_num;
803     int addr;
804     char product_name[PRODUCT_NAME_SZ];
805 } FindDeviceState;
806
807 static int usb_host_find_device_scan(void *opaque, int bus_num, int addr,
808                                      int class_id,
809                                      int vendor_id, int product_id,
810                                      const char *product_name, int speed)
811 {
812     FindDeviceState *s = opaque;
813     if ((vendor_id == s->vendor_id &&
814         product_id == s->product_id) ||
815         (bus_num == s->bus_num &&
816         addr == s->addr)) {
817         pstrcpy(s->product_name, PRODUCT_NAME_SZ, product_name);
818         s->bus_num = bus_num;
819         s->addr = addr;
820         return 1;
821     } else {
822         return 0;
823     }
824 }
825
826 /* the syntax is :
827    'bus.addr' (decimal numbers) or
828    'vendor_id:product_id' (hexa numbers) */
829 static int usb_host_find_device(int *pbus_num, int *paddr,
830                                 char *product_name, int product_name_size,
831                                 const char *devname)
832 {
833     const char *p;
834     int ret;
835     FindDeviceState fs;
836
837     p = strchr(devname, '.');
838     if (p) {
839         *pbus_num = strtoul(devname, NULL, 0);
840         *paddr = strtoul(p + 1, NULL, 0);
841         fs.bus_num = *pbus_num;
842         fs.addr = *paddr;
843         ret = usb_host_scan(&fs, usb_host_find_device_scan);
844         if (ret)
845             pstrcpy(product_name, product_name_size, fs.product_name);
846         return 0;
847     }
848     p = strchr(devname, ':');
849     if (p) {
850         fs.vendor_id = strtoul(devname, NULL, 16);
851         fs.product_id = strtoul(p + 1, NULL, 16);
852         ret = usb_host_scan(&fs, usb_host_find_device_scan);
853         if (ret) {
854             *pbus_num = fs.bus_num;
855             *paddr = fs.addr;
856             pstrcpy(product_name, product_name_size, fs.product_name);
857             return 0;
858         }
859     }
860     return -1;
861 }
862
863 /**********************/
864 /* USB host device info */
865
866 struct usb_class_info {
867     int class;
868     const char *class_name;
869 };
870
871 static const struct usb_class_info usb_class_info[] = {
872     { USB_CLASS_AUDIO, "Audio"},
873     { USB_CLASS_COMM, "Communication"},
874     { USB_CLASS_HID, "HID"},
875     { USB_CLASS_HUB, "Hub" },
876     { USB_CLASS_PHYSICAL, "Physical" },
877     { USB_CLASS_PRINTER, "Printer" },
878     { USB_CLASS_MASS_STORAGE, "Storage" },
879     { USB_CLASS_CDC_DATA, "Data" },
880     { USB_CLASS_APP_SPEC, "Application Specific" },
881     { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
882     { USB_CLASS_STILL_IMAGE, "Still Image" },
883     { USB_CLASS_CSCID, "Smart Card" },
884     { USB_CLASS_CONTENT_SEC, "Content Security" },
885     { -1, NULL }
886 };
887
888 static const char *usb_class_str(uint8_t class)
889 {
890     const struct usb_class_info *p;
891     for(p = usb_class_info; p->class != -1; p++) {
892         if (p->class == class)
893             break;
894     }
895     return p->class_name;
896 }
897
898 void usb_info_device(int bus_num, int addr, int class_id,
899                      int vendor_id, int product_id,
900                      const char *product_name,
901                      int speed)
902 {
903     const char *class_str, *speed_str;
904
905     switch(speed) {
906     case USB_SPEED_LOW:
907         speed_str = "1.5";
908         break;
909     case USB_SPEED_FULL:
910         speed_str = "12";
911         break;
912     case USB_SPEED_HIGH:
913         speed_str = "480";
914         break;
915     default:
916         speed_str = "?";
917         break;
918     }
919
920     term_printf("  Device %d.%d, speed %s Mb/s\n",
921                 bus_num, addr, speed_str);
922     class_str = usb_class_str(class_id);
923     if (class_str)
924         term_printf("    %s:", class_str);
925     else
926         term_printf("    Class %02x:", class_id);
927     term_printf(" USB device %04x:%04x", vendor_id, product_id);
928     if (product_name[0] != '\0')
929         term_printf(", %s", product_name);
930     term_printf("\n");
931 }
932
933 static int usb_host_info_device(void *opaque, int bus_num, int addr,
934                                 int class_id,
935                                 int vendor_id, int product_id,
936                                 const char *product_name,
937                                 int speed)
938 {
939     usb_info_device(bus_num, addr, class_id, vendor_id, product_id,
940                     product_name, speed);
941     return 0;
942 }
943
944 void usb_host_info(void)
945 {
946     usb_host_scan(NULL, usb_host_info_device);
947 }
948
949 #else
950
951 void usb_host_info(void)
952 {
953     term_printf("USB host devices not supported\n");
954 }
955
956 /* XXX: modify configure to compile the right host driver */
957 USBDevice *usb_host_device_open(const char *devname)
958 {
959     return NULL;
960 }
961
962 #endif