Don't use sprintf() or strcpy()
[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  *      Major 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
29 #include "qemu-common.h"
30 #include "qemu-timer.h"
31 #include "console.h"
32
33 #if defined(__linux__)
34 #include <dirent.h>
35 #include <sys/ioctl.h>
36 #include <signal.h>
37
38 #include <linux/usbdevice_fs.h>
39 #include <linux/version.h>
40 #include "hw/usb.h"
41
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;
51 };
52
53 struct usb_ctrlrequest {
54     uint8_t bRequestType;
55     uint8_t bRequest;
56     uint16_t wValue;
57     uint16_t wIndex;
58     uint16_t wLength;
59 };
60
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
68
69 #ifdef DEBUG
70 #define dprintf printf
71 #else
72 #define dprintf(...)
73 #endif
74
75 #define USBDEVFS_PATH "/proc/bus/usb"
76 #define PRODUCT_NAME_SZ 32
77 #define MAX_ENDPOINTS 16
78
79 /* endpoint association data */
80 struct endp_data {
81     uint8_t type;
82     uint8_t halted;
83 };
84
85 enum {
86     CTRL_STATE_IDLE = 0,
87     CTRL_STATE_SETUP,
88     CTRL_STATE_DATA,
89     CTRL_STATE_ACK
90 };
91
92 /*
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];
103 };
104
105 typedef struct USBHostDevice {
106     USBDevice dev;
107     int       fd;
108
109     uint8_t   descr[1024];
110     int       descr_len;
111     int       configuration;
112     int       ninterfaces;
113     int       closing;
114
115     struct ctrl_struct ctrl;
116     struct endp_data endp_table[MAX_ENDPOINTS];
117
118     /* Host side address */
119     int bus_num;
120     int addr;
121
122     struct USBHostDevice *next;
123 } USBHostDevice;
124
125 static int is_isoc(USBHostDevice *s, int ep)
126 {
127     return s->endp_table[ep - 1].type == USBDEVFS_URB_TYPE_ISO;
128 }
129
130 static int is_halted(USBHostDevice *s, int ep)
131 {
132     return s->endp_table[ep - 1].halted;
133 }
134
135 static void clear_halt(USBHostDevice *s, int ep)
136 {
137     s->endp_table[ep - 1].halted = 0;
138 }
139
140 static void set_halt(USBHostDevice *s, int ep)
141 {
142     s->endp_table[ep - 1].halted = 1;
143 }
144
145 static USBHostDevice *hostdev_list;
146
147 static void hostdev_link(USBHostDevice *dev)
148 {
149     dev->next = hostdev_list;
150     hostdev_list = dev;
151 }
152
153 static void hostdev_unlink(USBHostDevice *dev)
154 {
155     USBHostDevice *pdev = hostdev_list;
156     USBHostDevice **prev = &hostdev_list;
157
158     while (pdev) {
159         if (pdev == dev) {
160             *prev = dev->next;
161             return;
162         }
163
164         prev = &pdev->next;
165         pdev = pdev->next;
166     }
167 }
168
169 static USBHostDevice *hostdev_find(int bus_num, int addr)
170 {
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;
176     }
177     return NULL;
178 }
179
180 /* 
181  * Async URB state.
182  * We always allocate one isoc descriptor even for bulk transfers
183  * to simplify allocation and casts. 
184  */
185 typedef struct AsyncURB
186 {
187     struct usbdevfs_urb urb;
188     struct usbdevfs_iso_packet_desc isocpd;
189
190     USBPacket     *packet;
191     USBHostDevice *hdev;
192 } AsyncURB;
193
194 static AsyncURB *async_alloc(void)
195 {
196     return (AsyncURB *) qemu_mallocz(sizeof(AsyncURB));
197 }
198
199 static void async_free(AsyncURB *aurb)
200 {
201     qemu_free(aurb);
202 }
203
204 static void async_complete_ctrl(USBHostDevice *s, USBPacket *p)
205 {
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;
213
214     case CTRL_STATE_ACK:
215         s->ctrl.state = CTRL_STATE_IDLE;
216         p->len = 0;
217         break;
218
219     default:
220         break;
221     }
222 }
223
224 static void async_complete(void *opaque)
225 {
226     USBHostDevice *s = opaque;
227     AsyncURB *aurb;
228
229     while (1) {
230         USBPacket *p;
231
232         int r = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &aurb);
233         if (r < 0) {
234             if (errno == EAGAIN)
235                 return;
236
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;
241             }
242
243             dprintf("husb: async. reap urb failed errno %d\n", errno);
244             return;
245         }
246
247         p = aurb->packet;
248
249         dprintf("husb: async completed. aurb %p status %d alen %d\n", 
250                 aurb, aurb->urb.status, aurb->urb.actual_length);
251
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;
259
260             case -EPIPE:
261                 set_halt(s, p->devep);
262                 /* fall through */
263             default:
264                 p->len = USB_RET_NAK;
265                 break;
266             }
267
268             usb_packet_complete(p);
269         }
270
271         async_free(aurb);
272     }
273 }
274
275 static void async_cancel(USBPacket *unused, void *opaque)
276 {
277     AsyncURB *aurb = opaque;
278     USBHostDevice *s = aurb->hdev;
279
280     dprintf("husb: async cancel. aurb %p\n", aurb);
281
282     /* Mark it as dead (see async_complete above) */
283     aurb->packet = NULL;
284
285     int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
286     if (r < 0) {
287         dprintf("husb: async. discard urb failed errno %d\n", errno);
288     }
289 }
290
291 static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
292 {
293     int dev_descr_len, config_descr_len;
294     int interface, nb_interfaces, nb_configurations;
295     int ret, i;
296
297     if (configuration == 0) /* address state - ignore */
298         return 1;
299
300     dprintf("husb: claiming interfaces. config %d\n", configuration);
301
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];
307
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]);
312
313         if (dev->descr[i+1] != USB_DT_CONFIG) {
314             i += dev->descr[i];
315             continue;
316         }
317         config_descr_len = dev->descr[i];
318
319         printf("husb: config #%d need %d\n", dev->descr[i + 5], configuration); 
320
321         if (configuration < 0 || configuration == dev->descr[i + 5]) {
322             configuration = dev->descr[i + 5];
323             break;
324         }
325
326         i += config_descr_len;
327     }
328
329     if (i >= dev->descr_len) {
330         fprintf(stderr, "husb: update iface failed. no matching configuration\n");
331         goto fail;
332     }
333     nb_interfaces = dev->descr[i + 4];
334
335 #ifdef USBDEVFS_DISCONNECT
336     /* earlier Linux 2.4 do not support that */
337     {
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;
346             }
347         }
348     }
349 #endif
350
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");
359             }
360         fail:
361             return 0;
362         }
363     }
364
365     printf("husb: %d interfaces claimed for configuration %d\n",
366            nb_interfaces, configuration);
367
368     dev->ninterfaces   = nb_interfaces;
369     dev->configuration = configuration;
370     return 1;
371 }
372
373 static int usb_host_release_interfaces(USBHostDevice *s)
374 {
375     int ret, i;
376
377     dprintf("husb: releasing interfaces\n");
378
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;
384         }
385     }
386
387     return 1;
388 }
389
390 static void usb_host_handle_reset(USBDevice *dev)
391 {
392     USBHostDevice *s = (USBHostDevice *) dev;
393
394     dprintf("husb: reset device %u.%u\n", s->bus_num, s->addr);
395
396     ioctl(s->fd, USBDEVFS_RESET);
397
398     usb_host_claim_interfaces(s, s->configuration);
399 }
400
401 static void usb_host_handle_destroy(USBDevice *dev)
402 {
403     USBHostDevice *s = (USBHostDevice *)dev;
404
405     s->closing = 1;
406
407     qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
408
409     hostdev_unlink(s);
410
411     async_complete(s);
412
413     if (s->fd >= 0)
414         close(s->fd);
415
416     qemu_free(s);
417 }
418
419 static int usb_linux_update_endp_table(USBHostDevice *s);
420
421 static int usb_host_handle_data(USBHostDevice *s, USBPacket *p)
422 {
423     struct usbdevfs_urb *urb;
424     AsyncURB *aurb;
425     int ret;
426
427     aurb = async_alloc();
428     if (!aurb) {
429         dprintf("husb: async malloc failed\n");
430         return USB_RET_NAK;
431     }
432     aurb->hdev   = s;
433     aurb->packet = p;
434
435     urb = &aurb->urb;
436
437     if (p->pid == USB_TOKEN_IN)
438         urb->endpoint = p->devep | 0x80;
439     else
440         urb->endpoint = p->devep;
441
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;
448         }
449         clear_halt(s, p->devep);
450     }
451
452     urb->buffer        = p->data;
453     urb->buffer_length = p->len;
454
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;
464     }
465
466     urb->usercontext = s;
467
468     ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
469
470     dprintf("husb: data submit. ep 0x%x len %u aurb %p\n", urb->endpoint, p->len, aurb);
471
472     if (ret < 0) {
473         dprintf("husb: submit failed. errno %d\n", errno);
474         async_free(aurb);
475
476         switch(errno) {
477         case ETIMEDOUT:
478             return USB_RET_NAK;
479         case EPIPE:
480         default:
481             return USB_RET_STALL;
482         }
483     }
484
485     usb_defer_packet(p, async_cancel, aurb);
486     return USB_RET_ASYNC;
487 }
488
489 static int ctrl_error(void)
490 {
491     if (errno == ETIMEDOUT)
492         return USB_RET_NAK;
493     else 
494         return USB_RET_STALL;
495 }
496
497 static int usb_host_set_address(USBHostDevice *s, int addr)
498 {
499     dprintf("husb: ctrl set addr %u\n", addr);
500     s->dev.addr = addr;
501     return 0;
502 }
503
504 static int usb_host_set_config(USBHostDevice *s, int config)
505 {
506     usb_host_release_interfaces(s);
507
508     int ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
509  
510     dprintf("husb: ctrl set config %d ret %d errno %d\n", config, ret, errno);
511     
512     if (ret < 0)
513         return ctrl_error();
514  
515     usb_host_claim_interfaces(s, config);
516     return 0;
517 }
518
519 static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
520 {
521     struct usbdevfs_setinterface si;
522     int ret;
523
524     si.interface  = iface;
525     si.altsetting = alt;
526     ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
527     
528     dprintf("husb: ctrl set iface %d altset %d ret %d errno %d\n", 
529         iface, alt, ret, errno);
530     
531     if (ret < 0)
532         return ctrl_error();
533
534     usb_linux_update_endp_table(s);
535     return 0;
536 }
537
538 static int usb_host_handle_control(USBHostDevice *s, USBPacket *p)
539 {
540     struct usbdevfs_urb *urb;
541     AsyncURB *aurb;
542     int ret, value, index;
543
544     /* 
545      * Process certain standard device requests.
546      * These are infrequent and are processed synchronously.
547      */
548     value = le16_to_cpu(s->ctrl.req.wValue);
549     index = le16_to_cpu(s->ctrl.req.wIndex);
550
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);
554
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);
559
560         case USB_REQ_SET_CONFIGURATION:
561             return usb_host_set_config(s, value & 0xff);
562         }
563     }
564
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);
568
569     /* The rest are asynchronous */
570
571     aurb = async_alloc();
572     if (!aurb) {
573         dprintf("husb: async malloc failed\n");
574         return USB_RET_NAK;
575     }
576     aurb->hdev   = s;
577     aurb->packet = p;
578
579     /* 
580      * Setup ctrl transfer.
581      *
582      * s->ctrl is layed out such that data buffer immediately follows
583      * 'req' struct which is exactly what usbdevfs expects.
584      */ 
585     urb = &aurb->urb;
586
587     urb->type     = USBDEVFS_URB_TYPE_CONTROL;
588     urb->endpoint = p->devep;
589
590     urb->buffer        = &s->ctrl.req;
591     urb->buffer_length = 8 + s->ctrl.len;
592
593     urb->usercontext = s;
594
595     ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
596
597     dprintf("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb);
598
599     if (ret < 0) {
600         dprintf("husb: submit failed. errno %d\n", errno);
601         async_free(aurb);
602
603         switch(errno) {
604         case ETIMEDOUT:
605             return USB_RET_NAK;
606         case EPIPE:
607         default:
608             return USB_RET_STALL;
609         }
610     }
611
612     usb_defer_packet(p, async_cancel, aurb);
613     return USB_RET_ASYNC;
614 }
615
616 static int do_token_setup(USBDevice *dev, USBPacket *p)
617 {
618     USBHostDevice *s = (USBHostDevice *) dev;
619     int ret = 0;
620
621     if (p->len != 8)
622         return USB_RET_STALL;
623  
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;
628
629     if (s->ctrl.req.bRequestType & USB_DIR_IN) {
630         ret = usb_host_handle_control(s, p);
631         if (ret < 0)
632             return ret;
633
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;
642     }
643
644     return ret;
645 }
646
647 static int do_token_in(USBDevice *dev, USBPacket *p)
648 {
649     USBHostDevice *s = (USBHostDevice *) dev;
650     int ret = 0;
651
652     if (p->devep != 0)
653         return usb_host_handle_data(s, p);
654
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;
661
662             s->ctrl.state = CTRL_STATE_IDLE;
663             return ret > 0 ? 0 : ret;
664         }
665
666         return 0;
667
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;
678         }
679
680         s->ctrl.state = CTRL_STATE_IDLE;
681         return USB_RET_STALL;
682
683     default:
684         return USB_RET_STALL;
685     }
686 }
687
688 static int do_token_out(USBDevice *dev, USBPacket *p)
689 {
690     USBHostDevice *s = (USBHostDevice *) dev;
691
692     if (p->devep != 0)
693         return usb_host_handle_data(s, p);
694
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 */
702         }
703         return 0;
704
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;
715         }
716
717         s->ctrl.state = CTRL_STATE_IDLE;
718         return USB_RET_STALL;
719
720     default:
721         return USB_RET_STALL;
722     }
723 }
724
725 /*
726  * Packet handler.
727  * Called by the HC (host controller).
728  *
729  * Returns length of the transaction or one of the USB_RET_XXX codes.
730  */
731 static int usb_host_handle_packet(USBDevice *s, USBPacket *p)
732 {
733     switch(p->pid) {
734     case USB_MSG_ATTACH:
735         s->state = USB_STATE_ATTACHED;
736         return 0;
737
738     case USB_MSG_DETACH:
739         s->state = USB_STATE_NOTATTACHED;
740         return 0;
741
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;
748     }
749
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;
753
754     switch (p->pid) {
755     case USB_TOKEN_SETUP:
756         return do_token_setup(s, p);
757
758     case USB_TOKEN_IN:
759         return do_token_in(s, p);
760
761     case USB_TOKEN_OUT:
762         return do_token_out(s, p);
763  
764     default:
765         return USB_RET_STALL;
766     }
767 }
768
769 /* returns 1 on problem encountered or 0 for success */
770 static int usb_linux_update_endp_table(USBHostDevice *s)
771 {
772     uint8_t *descriptors;
773     uint8_t devep, type, configuration, alt_interface;
774     struct usbdevfs_ctrltransfer ct;
775     int interface, ret, length, i;
776
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;
784
785     ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
786     if (ret < 0) {
787         perror("usb_linux_update_endp_table");
788         return 1;
789     }
790
791     /* in address state */
792     if (configuration == 0)
793         return 1;
794
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;
800
801     if (descriptors[i + 1] != USB_DT_CONFIG ||
802         descriptors[i + 5] != configuration) {
803         dprintf("invalid descriptor data - configuration\n");
804         return 1;
805     }
806     i += descriptors[i];
807
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;
814         }
815
816         interface = descriptors[i + 2];
817
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;
825
826         ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
827         if (ret < 0) {
828             perror("usb_linux_update_endp_table");
829             return 1;
830         }
831
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;
837         }
838
839         /* advance to the endpoints */
840         while (i < length && descriptors[i +1] != USB_DT_ENDPOINT)
841             i += descriptors[i];
842
843         if (i >= length)
844             break;
845
846         while (i < length) {
847             if (descriptors[i + 1] != USB_DT_ENDPOINT)
848                 break;
849
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;
867             }
868             s->endp_table[(devep & 0xf) - 1].type = type;
869             s->endp_table[(devep & 0xf) - 1].halted = 0;
870
871             i += descriptors[i];
872         }
873     }
874     return 0;
875 }
876
877 static USBDevice *usb_host_device_open_addr(int bus_num, int addr, const char *prod_name)
878 {
879     int fd = -1, ret;
880     USBHostDevice *dev = NULL;
881     struct usbdevfs_connectinfo ci;
882     char buf[1024];
883
884     dev = qemu_mallocz(sizeof(USBHostDevice));
885     if (!dev)
886         goto fail;
887
888     dev->bus_num = bus_num;
889     dev->addr = addr;
890
891     printf("husb: open device %d.%d\n", bus_num, addr);
892
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;
899     }
900
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;
906     }
907
908 #ifdef DEBUG
909     {
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");
915     }
916 #endif
917
918     dev->fd = fd;
919
920     /* 
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.
925      */
926     if (!usb_host_claim_interfaces(dev, -1))
927         goto fail;
928
929     ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
930     if (ret < 0) {
931         perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
932         goto fail;
933     }
934
935     printf("husb: grabbed usb device %d.%d\n", bus_num, addr);
936
937     ret = usb_linux_update_endp_table(dev);
938     if (ret)
939         goto fail;
940
941     if (ci.slow)
942         dev->dev.speed = USB_SPEED_LOW;
943     else
944         dev->dev.speed = USB_SPEED_HIGH;
945
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;
949
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);
956
957     /* USB devio uses 'write' flag to check for async completions */
958     qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);
959
960     hostdev_link(dev);
961
962     return (USBDevice *) dev;
963
964 fail:
965     if (dev)
966         qemu_free(dev);
967
968     close(fd);
969     return NULL;
970 }
971
972 static int usb_host_auto_add(const char *spec);
973 static int usb_host_auto_del(const char *spec);
974
975 USBDevice *usb_host_device_open(const char *devname)
976 {
977     int bus_num, addr;
978     char product_name[PRODUCT_NAME_SZ];
979
980     if (strstr(devname, "auto:")) {
981         usb_host_auto_add(devname);
982         return NULL;
983     }
984
985     if (usb_host_find_device(&bus_num, &addr, product_name, sizeof(product_name),
986                              devname) < 0)
987         return NULL;
988
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;
992     }
993
994     return usb_host_device_open_addr(bus_num, addr, product_name);
995 }
996
997 int usb_host_device_close(const char *devname)
998 {
999     char product_name[PRODUCT_NAME_SZ];
1000     int bus_num, addr;
1001     USBHostDevice *s;
1002
1003     if (strstr(devname, "auto:"))
1004         return usb_host_auto_del(devname);
1005
1006     if (usb_host_find_device(&bus_num, &addr, product_name, sizeof(product_name),
1007                              devname) < 0)
1008         return -1;
1009  
1010     s = hostdev_find(bus_num, addr);
1011     if (s) {
1012         usb_device_del_addr(0, s->dev.addr);
1013         return 0;
1014     }
1015
1016     return -1;
1017 }
1018  
1019 static int get_tag_value(char *buf, int buf_size,
1020                          const char *str, const char *tag,
1021                          const char *stopchars)
1022 {
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++;
1036     }
1037     *q = '\0';
1038     return q - buf;
1039 }
1040
1041 static int usb_host_scan(void *opaque, USBScanFunc *func)
1042 {
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];
1049
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;
1054     }
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;
1070             }
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);
1105         }
1106     fail: ;
1107     }
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);
1112     }
1113  the_end:
1114     fclose(f);
1115     return ret;
1116 }
1117
1118 struct USBAutoFilter {
1119     struct USBAutoFilter *next;
1120     int bus_num;
1121     int addr;
1122     int vendor_id;
1123     int product_id;
1124 };
1125
1126 static QEMUTimer *usb_auto_timer;
1127 static struct USBAutoFilter *usb_auto_filter;
1128
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)
1132 {
1133     struct USBAutoFilter *f;
1134     struct USBDevice *dev;
1135
1136     /* Ignore hubs */
1137     if (class_id == 9)
1138         return 0;
1139
1140     for (f = usb_auto_filter; f; f = f->next) {
1141         if (f->bus_num >= 0 && f->bus_num != bus_num)
1142             continue;
1143
1144         if (f->addr >= 0 && f->addr != addr)
1145             continue;
1146
1147         if (f->vendor_id >= 0 && f->vendor_id != vendor_id)
1148             continue;
1149
1150         if (f->product_id >= 0 && f->product_id != product_id)
1151             continue;
1152
1153         /* We got a match */
1154
1155         /* Allredy attached ? */
1156         if (hostdev_find(bus_num, addr))
1157             return 0;
1158
1159         dprintf("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1160
1161         dev = usb_host_device_open_addr(bus_num, addr, product_name);
1162         if (dev)
1163             usb_device_add_dev(dev);
1164     }
1165
1166     return 0;
1167 }
1168
1169 static void usb_host_auto_timer(void *unused)
1170 {
1171     usb_host_scan(NULL, usb_host_auto_scan);
1172     qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000);
1173 }
1174
1175 /*
1176  * Autoconnect filter
1177  * Format:
1178  *    auto:bus:dev[:vid:pid]
1179  *    auto:bus.dev[:vid:pid]
1180  *
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)
1185  *
1186  *    See 'lsusb' output.
1187  */
1188 static int parse_filter(const char *spec, struct USBAutoFilter *f)
1189 {
1190     enum { BUS, DEV, VID, PID, DONE };
1191     const char *p = spec;
1192     int i;
1193
1194     f->bus_num    = -1;
1195     f->addr       = -1;
1196     f->vendor_id  = -1;
1197     f->product_id = -1;
1198
1199     for (i = BUS; i < DONE; i++) {
1200         p = strpbrk(p, ":.");
1201         if (!p) break;
1202         p++;
1203  
1204         if (*p == '*')
1205             continue;
1206
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;
1212         }
1213     }
1214
1215     if (i < DEV) {
1216         fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1217         return -1;
1218     }
1219
1220     return 0;
1221 }
1222
1223 static int match_filter(const struct USBAutoFilter *f1, 
1224                         const struct USBAutoFilter *f2)
1225 {
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;
1230 }
1231
1232 static int usb_host_auto_add(const char *spec)
1233 {
1234     struct USBAutoFilter filter, *f;
1235
1236     if (parse_filter(spec, &filter) < 0)
1237         return -1;
1238
1239     f = qemu_mallocz(sizeof(*f));
1240     if (!f) {
1241         fprintf(stderr, "husb: failed to allocate auto filter\n");
1242         return -1;
1243     }
1244
1245     *f = filter; 
1246
1247     if (!usb_auto_filter) {
1248         /*
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.
1253          */
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;
1259         }
1260
1261         /* Check for new devices every two seconds */
1262         qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000);
1263     }
1264
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);
1267
1268     f->next = usb_auto_filter;
1269     usb_auto_filter = f;
1270
1271     return 0;
1272 }
1273
1274 static int usb_host_auto_del(const char *spec)
1275 {
1276     struct USBAutoFilter *pf = usb_auto_filter;
1277     struct USBAutoFilter **prev = &usb_auto_filter;
1278     struct USBAutoFilter filter;
1279
1280     if (parse_filter(spec, &filter) < 0)
1281         return -1;
1282
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);
1287
1288             *prev = pf->next;
1289
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);
1294             }
1295
1296             return 0;
1297         }
1298
1299         prev = &pf->next;
1300         pf   = pf->next;
1301     }
1302
1303     return -1;
1304 }
1305
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;
1313
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)
1318 {
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;
1330     }
1331 }
1332
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)
1339 {
1340     const char *p;
1341     int ret;
1342     FindDeviceState fs;
1343
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;
1354     }
1355
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;
1366         }
1367     }
1368     return -1;
1369 }
1370
1371 /**********************/
1372 /* USB host device info */
1373
1374 struct usb_class_info {
1375     int class;
1376     const char *class_name;
1377 };
1378
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 }
1394 };
1395
1396 static const char *usb_class_str(uint8_t class)
1397 {
1398     const struct usb_class_info *p;
1399     for(p = usb_class_info; p->class != -1; p++) {
1400         if (p->class == class)
1401             break;
1402     }
1403     return p->class_name;
1404 }
1405
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)
1410 {
1411     const char *class_str, *speed_str;
1412
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;
1426     }
1427
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");
1439 }
1440
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)
1446 {
1447     usb_info_device(bus_num, addr, class_id, vendor_id, product_id,
1448                     product_name, speed);
1449     return 0;
1450 }
1451
1452 static void dec2str(int val, char *str, size_t size)
1453 {
1454     if (val == -1)
1455         snprintf(str, size, "*");
1456     else
1457         snprintf(str, size, "%d", val); 
1458 }
1459
1460 static void hex2str(int val, char *str, size_t size)
1461 {
1462     if (val == -1)
1463         snprintf(str, size, "*");
1464     else
1465         snprintf(str, size, "%x", val);
1466 }
1467
1468 void usb_host_info(void)
1469 {
1470     struct USBAutoFilter *f;
1471
1472     usb_host_scan(NULL, usb_host_info_device);
1473
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);
1483     }
1484 }
1485
1486 #else
1487
1488 #include "hw/usb.h"
1489
1490 void usb_host_info(void)
1491 {
1492     term_printf("USB host devices not supported\n");
1493 }
1494
1495 /* XXX: modify configure to compile the right host driver */
1496 USBDevice *usb_host_device_open(const char *devname)
1497 {
1498     return NULL;
1499 }
1500
1501 int usb_host_device_close(const char *devname)
1502 {
1503     return 0;
1504 }
1505
1506 #endif