husb: rewrite Linux host USB layer, fully async operation (Max Krasnyansky)
[qemu] / usb-linux.c
1 /*
2  * Linux host USB redirector
3  *
4  * Copyright (c) 2005 Fabrice Bellard
5  *
6  * Copyright (c) 2008 Max Krasnyansky
7  *      Support for host device auto connect & disconnect
8  *      Magor rewrite to support fully async operation
9  *
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:
16  *
17  * The above copyright notice and this permission notice shall be included in
18  * all copies or substantial portions of the Software.
19  *
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.
27  */
28 #include "qemu-common.h"
29 #include "qemu-timer.h"
30 #include "hw/usb.h"
31 #include "console.h"
32
33 #if defined(__linux__)
34 #include <dirent.h>
35 #include <sys/ioctl.h>
36 #include <linux/usbdevice_fs.h>
37 #include <linux/version.h>
38 #include <signal.h>
39
40 /* We redefine it to avoid version problems */
41 struct usb_ctrltransfer {
42     uint8_t  bRequestType;
43     uint8_t  bRequest;
44     uint16_t wValue;
45     uint16_t wIndex;
46     uint16_t wLength;
47     uint32_t timeout;
48     void *data;
49 };
50
51 typedef int USBScanFunc(void *opaque, int bus_num, int addr, int class_id,
52                         int vendor_id, int product_id,
53                         const char *product_name, int speed);
54 static int usb_host_find_device(int *pbus_num, int *paddr,
55                                 char *product_name, int product_name_size,
56                                 const char *devname);
57
58 //#define DEBUG
59
60 #ifdef DEBUG
61 #define dprintf printf
62 #else
63 #define dprintf(...)
64 #endif
65
66 #define USBDEVFS_PATH "/proc/bus/usb"
67 #define PRODUCT_NAME_SZ 32
68 #define MAX_ENDPOINTS 16
69
70 struct sigaction sigact;
71
72 /* endpoint association data */
73 struct endp_data {
74     uint8_t type;
75     uint8_t halted;
76 };
77
78 typedef struct USBHostDevice {
79     USBDevice dev;
80     int       fd;
81
82     uint8_t   descr[1024];
83     int       descr_len;
84     int       configuration;
85
86     struct endp_data endp_table[MAX_ENDPOINTS];
87
88     QEMUTimer *timer;
89
90     /* Host side address */
91     int bus_num;
92     int addr;
93
94     struct USBHostDevice *next;
95 } USBHostDevice;
96
97 static int is_isoc(USBHostDevice *s, int ep)
98 {
99     return s->endp_table[ep - 1].type == USBDEVFS_URB_TYPE_ISO;
100 }
101
102 static int is_halted(USBHostDevice *s, int ep)
103 {
104     return s->endp_table[ep - 1].halted;
105 }
106
107 static void clear_halt(USBHostDevice *s, int ep)
108 {
109     s->endp_table[ep - 1].halted = 0;
110 }
111
112 static void set_halt(USBHostDevice *s, int ep)
113 {
114     s->endp_table[ep - 1].halted = 1;
115 }
116
117 static USBHostDevice *hostdev_list;
118
119 static void hostdev_link(USBHostDevice *dev)
120 {
121     dev->next = hostdev_list;
122     hostdev_list = dev;
123 }
124
125 static void hostdev_unlink(USBHostDevice *dev)
126 {
127     USBHostDevice *pdev = hostdev_list;
128     USBHostDevice **prev = &hostdev_list;
129
130     while (pdev) {
131         if (pdev == dev) {
132             *prev = dev->next;
133             return;
134         }
135
136         prev = &pdev->next;
137         pdev = pdev->next;
138     }
139 }
140
141 static USBHostDevice *hostdev_find(int bus_num, int addr)
142 {
143     USBHostDevice *s = hostdev_list;
144     while (s) {
145         if (s->bus_num == bus_num && s->addr == addr)
146             return s;
147         s = s->next;
148     }
149     return NULL;
150 }
151
152 /* 
153  * Async URB state.
154  * We always allocate one isoc descriptor even for bulk transfers
155  * to simplify allocation and casts. 
156  */
157 typedef struct AsyncURB
158 {
159     struct usbdevfs_urb urb;
160     struct usbdevfs_iso_packet_desc isocpd;
161
162     USBPacket     *packet;
163     USBHostDevice *hdev;
164 } AsyncURB;
165
166 static AsyncURB *async_alloc(void)
167 {
168     return (AsyncURB *) qemu_mallocz(sizeof(AsyncURB));
169 }
170
171 static void async_free(AsyncURB *aurb)
172 {
173     qemu_free(aurb);
174 }
175
176 static void async_complete(void *opaque)
177 {
178     USBHostDevice *s = opaque;
179     AsyncURB *aurb;
180
181     while (1) {
182         USBPacket *p;
183
184         int r = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &aurb);
185         if (r < 0) {
186             if (errno == EAGAIN)
187                 return;
188
189             if (errno == ENODEV) {
190                 printf("husb: device %d.%d disconnected\n", s->bus_num, s->addr);
191                 usb_device_del_addr(0, s->dev.addr);
192                 return;
193             }
194
195             dprintf("husb: async. reap urb failed errno %d\n", errno);
196             return;
197         }
198
199         p = aurb->packet;
200
201         dprintf("husb: async completed. aurb %p status %d alen %d\n", 
202                 aurb, aurb->urb.status, aurb->urb.actual_length);
203
204         if (p) {
205             switch (aurb->urb.status) {
206             case 0:
207                 p->len = aurb->urb.actual_length;
208                 break;
209
210             case -EPIPE:
211                 set_halt(s, p->devep);
212                 /* fall through */
213             default:
214                 p->len = USB_RET_NAK;
215                 break;
216             }
217
218             usb_packet_complete(p);
219         }
220
221         async_free(aurb);
222     }
223 }
224
225 static void async_cancel(USBPacket *unused, void *opaque)
226 {
227     AsyncURB *aurb = opaque;
228     USBHostDevice *s = aurb->hdev;
229
230     dprintf("husb: async cancel. aurb %p\n", aurb);
231
232     /* Mark it as dead (see async_complete above) */
233     aurb->packet = NULL;
234
235     int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
236     if (r < 0) {
237         dprintf("husb: async. discard urb failed errno %d\n", errno);
238     }
239 }
240
241 static int usb_host_update_interfaces(USBHostDevice *dev, int configuration)
242 {
243     int dev_descr_len, config_descr_len;
244     int interface, nb_interfaces, nb_configurations;
245     int ret, i;
246
247     if (configuration == 0) /* address state - ignore */
248         return 1;
249
250     i = 0;
251     dev_descr_len = dev->descr[0];
252     if (dev_descr_len > dev->descr_len)
253         goto fail;
254     nb_configurations = dev->descr[17];
255
256     i += dev_descr_len;
257     while (i < dev->descr_len) {
258         dprintf("husb: i is %d, descr_len is %d, dl %d, dt %d\n", i, dev->descr_len,
259                dev->descr[i], dev->descr[i+1]);
260
261         if (dev->descr[i+1] != USB_DT_CONFIG) {
262             i += dev->descr[i];
263             continue;
264         }
265         config_descr_len = dev->descr[i];
266
267         printf("husb: config #%d need %d\n", dev->descr[i + 5], configuration); 
268
269         if (configuration < 0 || configuration == dev->descr[i + 5])
270             break;
271
272         i += config_descr_len;
273     }
274
275     if (i >= dev->descr_len) {
276         printf("husb: update iface failed. no matching configuration\n");
277         goto fail;
278     }
279     nb_interfaces = dev->descr[i + 4];
280
281 #ifdef USBDEVFS_DISCONNECT
282     /* earlier Linux 2.4 do not support that */
283     {
284         struct usbdevfs_ioctl ctrl;
285         for (interface = 0; interface < nb_interfaces; interface++) {
286             ctrl.ioctl_code = USBDEVFS_DISCONNECT;
287             ctrl.ifno = interface;
288             ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
289             if (ret < 0 && errno != ENODATA) {
290                 perror("USBDEVFS_DISCONNECT");
291                 goto fail;
292             }
293         }
294     }
295 #endif
296
297     /* XXX: only grab if all interfaces are free */
298     for (interface = 0; interface < nb_interfaces; interface++) {
299         ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
300         if (ret < 0) {
301             if (errno == EBUSY) {
302                 printf("husb: update iface. device already grabbed\n");
303             } else {
304                 perror("husb: failed to claim interface");
305             }
306         fail:
307             return 0;
308         }
309     }
310
311     printf("husb: %d interfaces claimed for configuration %d\n",
312            nb_interfaces, configuration);
313
314     return 1;
315 }
316
317 static void usb_host_handle_reset(USBDevice *dev)
318 {
319     USBHostDevice *s = (USBHostDevice *)dev;
320
321     dprintf("husb: reset device %u.%u\n", s->bus_num, s->addr);
322
323     ioctl(s->fd, USBDEVFS_RESET);
324     usb_host_update_interfaces(s, s->configuration);
325 }
326
327 static void usb_host_handle_destroy(USBDevice *dev)
328 {
329     USBHostDevice *s = (USBHostDevice *)dev;
330
331     qemu_del_timer(s->timer);
332     qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
333
334     hostdev_unlink(s);
335
336     async_complete(s);
337
338     if (s->fd >= 0)
339         close(s->fd);
340
341     qemu_free(s);
342 }
343
344 static int usb_linux_update_endp_table(USBHostDevice *s);
345
346 static int usb_host_handle_control(USBDevice *dev,
347                                    int request,
348                                    int value,
349                                    int index,
350                                    int length,
351                                    uint8_t *data)
352 {
353     USBHostDevice *s = (USBHostDevice *)dev;
354     struct usb_ctrltransfer ct;
355     struct usbdevfs_setinterface si;
356     int intf_update_required = 0;
357     int ret;
358
359     if (request == (DeviceOutRequest | USB_REQ_SET_ADDRESS)) {
360         /* specific SET_ADDRESS support */
361         dev->addr = value;
362         return 0;
363     } else if (request == ((USB_RECIP_INTERFACE << 8) |
364                            USB_REQ_SET_INTERFACE)) {
365         /* set alternate setting for the interface */
366         si.interface = index;
367         si.altsetting = value;
368         ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
369         usb_linux_update_endp_table(s);
370     } else if (request == (DeviceOutRequest | USB_REQ_SET_CONFIGURATION)) {
371         dprintf("husb: ctrl set config %d\n", value & 0xff);
372         if (s->configuration != (value & 0xff)) {
373             s->configuration = (value & 0xff);
374             intf_update_required = 1;
375         }
376         goto do_request;
377     } else {
378     do_request:
379         ct.bRequestType = request >> 8;
380         ct.bRequest = request;
381         ct.wValue = value;
382         ct.wIndex = index;
383         ct.wLength = length;
384         ct.timeout = 50;
385         ct.data = data;
386         ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
387
388         dprintf("husb: ctrl req 0x%x val 0x%x index %u len %u ret %d\n",
389             ct.bRequest, ct.wValue, ct.wIndex, ct.wLength, ret);
390     }
391
392     if (ret < 0) {
393         switch(errno) {
394         case ETIMEDOUT:
395             return USB_RET_NAK;
396         default:
397             return USB_RET_STALL;
398         }
399     } else {
400         if (intf_update_required) {
401             dprintf("husb: updating interfaces\n");
402             usb_host_update_interfaces(s, value & 0xff);
403         }
404         return ret;
405     }
406 }
407
408 static int usb_host_handle_data(USBDevice *dev, USBPacket *p)
409 {
410     USBHostDevice *s = (USBHostDevice *) dev;
411     AsyncURB *aurb;
412     struct usbdevfs_urb *urb;
413     int ret;
414
415     aurb = async_alloc();
416     if (!aurb) {
417         dprintf("husb: async malloc failed\n");
418         return USB_RET_NAK;
419     }
420     aurb->hdev   = s;
421     aurb->packet = p;
422
423     urb = &aurb->urb;
424
425     if (p->pid == USB_TOKEN_IN)
426         urb->endpoint = p->devep | 0x80;
427     else
428         urb->endpoint = p->devep;
429
430     if (is_halted(s, p->devep)) {
431         ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &urb->endpoint);
432         if (ret < 0) {
433             dprintf("husb: failed to clear halt. ep 0x%x errno %d\n", 
434                    urb->endpoint, errno);
435             return USB_RET_NAK;
436         }
437         clear_halt(s, p->devep);
438     }
439
440     urb->buffer        = p->data;
441     urb->buffer_length = p->len;
442
443     if (is_isoc(s, p->devep)) {
444         /* Setup ISOC transfer */
445         urb->type     = USBDEVFS_URB_TYPE_ISO;
446         urb->flags    = USBDEVFS_URB_ISO_ASAP;
447         urb->number_of_packets = 1;
448         urb->iso_frame_desc[0].length = p->len;
449     } else {
450         /* Setup bulk transfer */
451         urb->type     = USBDEVFS_URB_TYPE_BULK;
452     }
453
454     urb->usercontext = s;
455
456     ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
457
458     dprintf("husb: data submit. ep 0x%x len %u aurb %p\n", urb->endpoint, p->len, aurb);
459
460     if (ret < 0) {
461         dprintf("husb: submit failed. errno %d\n", errno);
462         async_free(aurb);
463
464         switch(errno) {
465         case ETIMEDOUT:
466             return USB_RET_NAK;
467         case EPIPE:
468         default:
469             return USB_RET_STALL;
470         }
471     }
472
473     usb_defer_packet(p, async_cancel, aurb);
474     return USB_RET_ASYNC;
475 }
476
477 /* returns 1 on problem encountered or 0 for success */
478 static int usb_linux_update_endp_table(USBHostDevice *s)
479 {
480     uint8_t *descriptors;
481     uint8_t devep, type, configuration, alt_interface;
482     struct usb_ctrltransfer ct;
483     int interface, ret, length, i;
484
485     ct.bRequestType = USB_DIR_IN;
486     ct.bRequest = USB_REQ_GET_CONFIGURATION;
487     ct.wValue = 0;
488     ct.wIndex = 0;
489     ct.wLength = 1;
490     ct.data = &configuration;
491     ct.timeout = 50;
492
493     ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
494     if (ret < 0) {
495         perror("usb_linux_update_endp_table");
496         return 1;
497     }
498
499     /* in address state */
500     if (configuration == 0)
501         return 1;
502
503     /* get the desired configuration, interface, and endpoint descriptors
504      * from device description */
505     descriptors = &s->descr[18];
506     length = s->descr_len - 18;
507     i = 0;
508
509     if (descriptors[i + 1] != USB_DT_CONFIG ||
510         descriptors[i + 5] != configuration) {
511         dprintf("invalid descriptor data - configuration\n");
512         return 1;
513     }
514     i += descriptors[i];
515
516     while (i < length) {
517         if (descriptors[i + 1] != USB_DT_INTERFACE ||
518             (descriptors[i + 1] == USB_DT_INTERFACE &&
519              descriptors[i + 4] == 0)) {
520             i += descriptors[i];
521             continue;
522         }
523
524         interface = descriptors[i + 2];
525
526         ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
527         ct.bRequest = USB_REQ_GET_INTERFACE;
528         ct.wValue = 0;
529         ct.wIndex = interface;
530         ct.wLength = 1;
531         ct.data = &alt_interface;
532         ct.timeout = 50;
533
534         ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
535         if (ret < 0) {
536             perror("usb_linux_update_endp_table");
537             return 1;
538         }
539
540         /* the current interface descriptor is the active interface
541          * and has endpoints */
542         if (descriptors[i + 3] != alt_interface) {
543             i += descriptors[i];
544             continue;
545         }
546
547         /* advance to the endpoints */
548         while (i < length && descriptors[i +1] != USB_DT_ENDPOINT)
549             i += descriptors[i];
550
551         if (i >= length)
552             break;
553
554         while (i < length) {
555             if (descriptors[i + 1] != USB_DT_ENDPOINT)
556                 break;
557
558             devep = descriptors[i + 2];
559             switch (descriptors[i + 3] & 0x3) {
560             case 0x00:
561                 type = USBDEVFS_URB_TYPE_CONTROL;
562                 break;
563             case 0x01:
564                 type = USBDEVFS_URB_TYPE_ISO;
565                 break;
566             case 0x02:
567                 type = USBDEVFS_URB_TYPE_BULK;
568                 break;
569             case 0x03:
570                 type = USBDEVFS_URB_TYPE_INTERRUPT;
571                 break;
572             default:
573                 dprintf("usb_host: malformed endpoint type\n");
574                 type = USBDEVFS_URB_TYPE_BULK;
575             }
576             s->endp_table[(devep & 0xf) - 1].type = type;
577             s->endp_table[(devep & 0xf) - 1].halted = 0;
578
579             i += descriptors[i];
580         }
581     }
582     return 0;
583 }
584
585 static void usb_host_device_check(void *priv)
586 {
587     USBHostDevice *s = priv;
588     struct usbdevfs_connectinfo ci;
589     int err;
590
591     err = ioctl(s->fd, USBDEVFS_CONNECTINFO, &ci);
592     if (err < 0) {
593         printf("husb: device %d.%d disconnected\n", s->bus_num, s->addr);
594         usb_device_del_addr(0, s->dev.addr);
595         return;
596     }
597
598     qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
599 }
600
601 static USBDevice *usb_host_device_open_addr(int bus_num, int addr, const char *prod_name)
602 {
603     int fd = -1, ret;
604     USBHostDevice *dev = NULL;
605     struct usbdevfs_connectinfo ci;
606     char buf[1024];
607
608     dev = qemu_mallocz(sizeof(USBHostDevice));
609     if (!dev)
610         goto fail;
611
612     dev->bus_num = bus_num;
613     dev->addr = addr;
614
615     dev->timer = qemu_new_timer(rt_clock, usb_host_device_check, (void *) dev);
616     if (!dev->timer)
617         goto fail;
618
619     printf("husb: open device %d.%d\n", bus_num, addr);
620
621     snprintf(buf, sizeof(buf), USBDEVFS_PATH "/%03d/%03d",
622              bus_num, addr);
623     fd = open(buf, O_RDWR | O_NONBLOCK);
624     if (fd < 0) {
625         perror(buf);
626         goto fail;
627     }
628
629     /* read the device description */
630     dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
631     if (dev->descr_len <= 0) {
632         perror("husb: reading device data failed");
633         goto fail;
634     }
635
636 #ifdef DEBUG
637     {
638         int x;
639         printf("=== begin dumping device descriptor data ===\n");
640         for (x = 0; x < dev->descr_len; x++)
641             printf("%02x ", dev->descr[x]);
642         printf("\n=== end dumping device descriptor data ===\n");
643     }
644 #endif
645
646     dev->fd = fd;
647     dev->configuration = 1;
648
649     /* XXX - do something about initial configuration */
650     if (!usb_host_update_interfaces(dev, -1))
651         goto fail;
652
653     ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
654     if (ret < 0) {
655         perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
656         goto fail;
657     }
658
659     printf("husb: grabbed usb device %d.%d\n", bus_num, addr);
660
661     ret = usb_linux_update_endp_table(dev);
662     if (ret)
663         goto fail;
664
665     if (ci.slow)
666         dev->dev.speed = USB_SPEED_LOW;
667     else
668         dev->dev.speed = USB_SPEED_HIGH;
669     dev->dev.handle_packet = usb_generic_handle_packet;
670
671     dev->dev.handle_reset = usb_host_handle_reset;
672     dev->dev.handle_control = usb_host_handle_control;
673     dev->dev.handle_data = usb_host_handle_data;
674     dev->dev.handle_destroy = usb_host_handle_destroy;
675
676     if (!prod_name || prod_name[0] == '\0')
677         snprintf(dev->dev.devname, sizeof(dev->dev.devname),
678                  "host:%d.%d", bus_num, addr);
679     else
680         pstrcpy(dev->dev.devname, sizeof(dev->dev.devname),
681                 prod_name);
682
683     /* USB devio uses 'write' flag to check for async completions */
684     qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);
685
686     /* Start the timer to detect disconnect */
687     qemu_mod_timer(dev->timer, qemu_get_clock(rt_clock) + 1000);
688
689     hostdev_link(dev);
690
691     return (USBDevice *) dev;
692
693 fail:
694     if (dev) {
695         if (dev->timer)
696                 qemu_del_timer(dev->timer);
697         qemu_free(dev);
698     }
699     close(fd);
700     return NULL;
701 }
702
703 USBDevice *usb_host_device_open(const char *devname)
704 {
705     int bus_num, addr;
706     char product_name[PRODUCT_NAME_SZ];
707
708     if (usb_host_find_device(&bus_num, &addr,
709                              product_name, sizeof(product_name),
710                              devname) < 0)
711         return NULL;
712
713      if (hostdev_find(bus_num, addr)) {
714         term_printf("husb: host usb device %d.%d is already open\n", bus_num, addr);
715         return NULL;
716      }
717
718     return usb_host_device_open_addr(bus_num, addr, product_name);
719 }
720  
721 static int get_tag_value(char *buf, int buf_size,
722                          const char *str, const char *tag,
723                          const char *stopchars)
724 {
725     const char *p;
726     char *q;
727     p = strstr(str, tag);
728     if (!p)
729         return -1;
730     p += strlen(tag);
731     while (isspace(*p))
732         p++;
733     q = buf;
734     while (*p != '\0' && !strchr(stopchars, *p)) {
735         if ((q - buf) < (buf_size - 1))
736             *q++ = *p;
737         p++;
738     }
739     *q = '\0';
740     return q - buf;
741 }
742
743 static int usb_host_scan(void *opaque, USBScanFunc *func)
744 {
745     FILE *f;
746     char line[1024];
747     char buf[1024];
748     int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
749     int ret;
750     char product_name[512];
751
752     f = fopen(USBDEVFS_PATH "/devices", "r");
753     if (!f) {
754         term_printf("husb: could not open %s\n", USBDEVFS_PATH "/devices");
755         return 0;
756     }
757     device_count = 0;
758     bus_num = addr = speed = class_id = product_id = vendor_id = 0;
759     ret = 0;
760     for(;;) {
761         if (fgets(line, sizeof(line), f) == NULL)
762             break;
763         if (strlen(line) > 0)
764             line[strlen(line) - 1] = '\0';
765         if (line[0] == 'T' && line[1] == ':') {
766             if (device_count && (vendor_id || product_id)) {
767                 /* New device.  Add the previously discovered device.  */
768                 ret = func(opaque, bus_num, addr, class_id, vendor_id,
769                            product_id, product_name, speed);
770                 if (ret)
771                     goto the_end;
772             }
773             if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0)
774                 goto fail;
775             bus_num = atoi(buf);
776             if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0)
777                 goto fail;
778             addr = atoi(buf);
779             if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0)
780                 goto fail;
781             if (!strcmp(buf, "480"))
782                 speed = USB_SPEED_HIGH;
783             else if (!strcmp(buf, "1.5"))
784                 speed = USB_SPEED_LOW;
785             else
786                 speed = USB_SPEED_FULL;
787             product_name[0] = '\0';
788             class_id = 0xff;
789             device_count++;
790             product_id = 0;
791             vendor_id = 0;
792         } else if (line[0] == 'P' && line[1] == ':') {
793             if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0)
794                 goto fail;
795             vendor_id = strtoul(buf, NULL, 16);
796             if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0)
797                 goto fail;
798             product_id = strtoul(buf, NULL, 16);
799         } else if (line[0] == 'S' && line[1] == ':') {
800             if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0)
801                 goto fail;
802             pstrcpy(product_name, sizeof(product_name), buf);
803         } else if (line[0] == 'D' && line[1] == ':') {
804             if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0)
805                 goto fail;
806             class_id = strtoul(buf, NULL, 16);
807         }
808     fail: ;
809     }
810     if (device_count && (vendor_id || product_id)) {
811         /* Add the last device.  */
812         ret = func(opaque, bus_num, addr, class_id, vendor_id,
813                    product_id, product_name, speed);
814     }
815  the_end:
816     fclose(f);
817     return ret;
818 }
819
820 struct USBAutoFilter {
821     struct USBAutoFilter *next;
822     int bus_num;
823     int addr;
824     int vendor_id;
825     int product_id;
826 };
827
828 static QEMUTimer *usb_auto_timer;
829 static struct USBAutoFilter *usb_auto_filter;
830
831 static int usb_host_auto_scan(void *opaque, int bus_num, int addr,
832                      int class_id, int vendor_id, int product_id,
833                      const char *product_name, int speed)
834 {
835     struct USBAutoFilter *f;
836     struct USBDevice *dev;
837
838     /* Ignore hubs */
839     if (class_id == 9)
840         return 0;
841
842     for (f = usb_auto_filter; f; f = f->next) {
843         // printf("Auto match: bus_num %d addr %d vid %d pid %d\n",
844         //    bus_num, addr, vendor_id, product_id);
845
846         if (f->bus_num >= 0 && f->bus_num != bus_num)
847             continue;
848
849         if (f->addr >= 0 && f->addr != addr)
850             continue;
851
852         if (f->vendor_id >= 0 && f->vendor_id != vendor_id)
853             continue;
854
855         if (f->product_id >= 0 && f->product_id != product_id)
856             continue;
857
858         /* We got a match */
859
860         /* Allredy attached ? */
861         if (hostdev_find(bus_num, addr))
862             return 0;
863
864         dprintf("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
865
866         dev = usb_host_device_open_addr(bus_num, addr, product_name);
867         if (dev)
868             usb_device_add_dev(dev);
869     }
870
871     return 0;
872 }
873
874 static void usb_host_auto_timer(void *unused)
875 {
876     usb_host_scan(NULL, usb_host_auto_scan);
877     qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000);
878 }
879
880 /*
881  * Add autoconnect filter
882  * -1 means 'any' (device, vendor, etc)
883  */
884 static void usb_host_auto_add(int bus_num, int addr, int vendor_id, int product_id)
885 {
886     struct USBAutoFilter *f = qemu_mallocz(sizeof(*f));
887     if (!f) {
888         printf("husb: failed to allocate auto filter\n");
889         return;
890     }
891
892     f->bus_num = bus_num;
893     f->addr    = addr;
894     f->vendor_id  = vendor_id;
895     f->product_id = product_id;
896
897     if (!usb_auto_filter) {
898         /*
899          * First entry. Init and start the monitor.
900          * Right now we're using timer to check for new devices.
901          * If this turns out to be too expensive we can move that into a 
902          * separate thread.
903          */
904         usb_auto_timer = qemu_new_timer(rt_clock, usb_host_auto_timer, NULL);
905         if (!usb_auto_timer) {
906             printf("husb: failed to allocate timer\n");
907             qemu_free(f);
908             return;
909         }
910
911         /* Check for new devices every two seconds */
912         qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000);
913     }
914
915     dprintf("husb: auto filter: bus_num %d addr %d vid %d pid %d\n",
916         bus_num, addr, vendor_id, product_id);
917
918     f->next = usb_auto_filter;
919     usb_auto_filter = f;
920 }
921
922 typedef struct FindDeviceState {
923     int vendor_id;
924     int product_id;
925     int bus_num;
926     int addr;
927     char product_name[PRODUCT_NAME_SZ];
928 } FindDeviceState;
929
930 static int usb_host_find_device_scan(void *opaque, int bus_num, int addr,
931                                      int class_id,
932                                      int vendor_id, int product_id,
933                                      const char *product_name, int speed)
934 {
935     FindDeviceState *s = opaque;
936     if ((vendor_id == s->vendor_id &&
937         product_id == s->product_id) ||
938         (bus_num == s->bus_num &&
939         addr == s->addr)) {
940         pstrcpy(s->product_name, PRODUCT_NAME_SZ, product_name);
941         s->bus_num = bus_num;
942         s->addr = addr;
943         return 1;
944     } else {
945         return 0;
946     }
947 }
948
949 /* the syntax is :
950    'bus.addr' (decimal numbers) or
951    'vendor_id:product_id' (hexa numbers) */
952 static int usb_host_find_device(int *pbus_num, int *paddr,
953                                 char *product_name, int product_name_size,
954                                 const char *devname)
955 {
956     const char *p;
957     int ret;
958     FindDeviceState fs;
959
960     p = strchr(devname, '.');
961     if (p) {
962         *pbus_num = strtoul(devname, NULL, 0);
963
964         if (*(p + 1) == '*') {
965             usb_host_auto_add(*pbus_num, -1, -1, -1);
966             return -1;
967         }
968
969         *paddr = strtoul(p + 1, NULL, 0);
970         fs.bus_num = *pbus_num;
971         fs.addr = *paddr;
972         ret = usb_host_scan(&fs, usb_host_find_device_scan);
973         if (ret)
974             pstrcpy(product_name, product_name_size, fs.product_name);
975         return 0;
976     }
977     p = strchr(devname, ':');
978     if (p) {
979         fs.vendor_id = strtoul(devname, NULL, 16);
980
981         if (*(p + 1) == '*') {
982             usb_host_auto_add(-1, -1, fs.vendor_id, -1);
983             return -1;
984         }
985
986         fs.product_id = strtoul(p + 1, NULL, 16);
987         ret = usb_host_scan(&fs, usb_host_find_device_scan);
988         if (ret) {
989             *pbus_num = fs.bus_num;
990             *paddr = fs.addr;
991             pstrcpy(product_name, product_name_size, fs.product_name);
992             return 0;
993         }
994     }
995     return -1;
996 }
997
998 /**********************/
999 /* USB host device info */
1000
1001 struct usb_class_info {
1002     int class;
1003     const char *class_name;
1004 };
1005
1006 static const struct usb_class_info usb_class_info[] = {
1007     { USB_CLASS_AUDIO, "Audio"},
1008     { USB_CLASS_COMM, "Communication"},
1009     { USB_CLASS_HID, "HID"},
1010     { USB_CLASS_HUB, "Hub" },
1011     { USB_CLASS_PHYSICAL, "Physical" },
1012     { USB_CLASS_PRINTER, "Printer" },
1013     { USB_CLASS_MASS_STORAGE, "Storage" },
1014     { USB_CLASS_CDC_DATA, "Data" },
1015     { USB_CLASS_APP_SPEC, "Application Specific" },
1016     { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1017     { USB_CLASS_STILL_IMAGE, "Still Image" },
1018     { USB_CLASS_CSCID, "Smart Card" },
1019     { USB_CLASS_CONTENT_SEC, "Content Security" },
1020     { -1, NULL }
1021 };
1022
1023 static const char *usb_class_str(uint8_t class)
1024 {
1025     const struct usb_class_info *p;
1026     for(p = usb_class_info; p->class != -1; p++) {
1027         if (p->class == class)
1028             break;
1029     }
1030     return p->class_name;
1031 }
1032
1033 static void usb_info_device(int bus_num, int addr, int class_id,
1034                             int vendor_id, int product_id,
1035                             const char *product_name,
1036                             int speed)
1037 {
1038     const char *class_str, *speed_str;
1039
1040     switch(speed) {
1041     case USB_SPEED_LOW:
1042         speed_str = "1.5";
1043         break;
1044     case USB_SPEED_FULL:
1045         speed_str = "12";
1046         break;
1047     case USB_SPEED_HIGH:
1048         speed_str = "480";
1049         break;
1050     default:
1051         speed_str = "?";
1052         break;
1053     }
1054
1055     term_printf("  Device %d.%d, speed %s Mb/s\n",
1056                 bus_num, addr, speed_str);
1057     class_str = usb_class_str(class_id);
1058     if (class_str)
1059         term_printf("    %s:", class_str);
1060     else
1061         term_printf("    Class %02x:", class_id);
1062     term_printf(" USB device %04x:%04x", vendor_id, product_id);
1063     if (product_name[0] != '\0')
1064         term_printf(", %s", product_name);
1065     term_printf("\n");
1066 }
1067
1068 static int usb_host_info_device(void *opaque, int bus_num, int addr,
1069                                 int class_id,
1070                                 int vendor_id, int product_id,
1071                                 const char *product_name,
1072                                 int speed)
1073 {
1074     usb_info_device(bus_num, addr, class_id, vendor_id, product_id,
1075                     product_name, speed);
1076     return 0;
1077 }
1078
1079 void usb_host_info(void)
1080 {
1081     usb_host_scan(NULL, usb_host_info_device);
1082 }
1083
1084 #else
1085
1086 void usb_host_info(void)
1087 {
1088     term_printf("USB host devices not supported\n");
1089 }
1090
1091 /* XXX: modify configure to compile the right host driver */
1092 USBDevice *usb_host_device_open(const char *devname)
1093 {
1094     return NULL;
1095 }
1096
1097 #endif