]> rtime.felk.cvut.cz Git - lisovros/qemu_apohw.git/blob - usb-linux.c
usb-linux: Teach about super speed
[lisovros/qemu_apohw.git] / 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  * Copyright 2008 TJ <linux@tjworld.net>
11  *      Added flexible support for /dev/bus/usb /sys/bus/usb/devices in addition
12  *      to the legacy /proc/bus/usb USB device discovery and handling
13  *
14  * Permission is hereby granted, free of charge, to any person obtaining a copy
15  * of this software and associated documentation files (the "Software"), to deal
16  * in the Software without restriction, including without limitation the rights
17  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18  * copies of the Software, and to permit persons to whom the Software is
19  * furnished to do so, subject to the following conditions:
20  *
21  * The above copyright notice and this permission notice shall be included in
22  * all copies or substantial portions of the Software.
23  *
24  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
27  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30  * THE SOFTWARE.
31  */
32
33 #include "qemu-common.h"
34 #include "qemu-timer.h"
35 #include "monitor.h"
36 #include "sysemu.h"
37
38 #include <dirent.h>
39 #include <sys/ioctl.h>
40
41 #include <linux/usbdevice_fs.h>
42 #include <linux/version.h>
43 #include "hw/usb.h"
44
45 /* We redefine it to avoid version problems */
46 struct usb_ctrltransfer {
47     uint8_t  bRequestType;
48     uint8_t  bRequest;
49     uint16_t wValue;
50     uint16_t wIndex;
51     uint16_t wLength;
52     uint32_t timeout;
53     void *data;
54 };
55
56 typedef int USBScanFunc(void *opaque, int bus_num, int addr, char *port,
57                         int class_id, int vendor_id, int product_id,
58                         const char *product_name, int speed);
59
60 //#define DEBUG
61
62 #ifdef DEBUG
63 #define DPRINTF printf
64 #else
65 #define DPRINTF(...)
66 #endif
67
68 #define USBDBG_DEVOPENED "husb: opened %s/devices\n"
69
70 #define USBPROCBUS_PATH "/proc/bus/usb"
71 #define PRODUCT_NAME_SZ 32
72 #define MAX_ENDPOINTS 15
73 #define MAX_PORTLEN 16
74 #define USBDEVBUS_PATH "/dev/bus/usb"
75 #define USBSYSBUS_PATH "/sys/bus/usb"
76
77 static char *usb_host_device_path;
78
79 #define USB_FS_NONE 0
80 #define USB_FS_PROC 1
81 #define USB_FS_DEV 2
82 #define USB_FS_SYS 3
83
84 static int usb_fs_type;
85
86 /* endpoint association data */
87 #define ISO_FRAME_DESC_PER_URB 32
88 #define ISO_URB_COUNT 3
89 #define INVALID_EP_TYPE 255
90
91 /* devio.c limits single requests to 16k */
92 #define MAX_USBFS_BUFFER_SIZE 16384
93
94 typedef struct AsyncURB AsyncURB;
95
96 struct endp_data {
97     uint8_t type;
98     uint8_t halted;
99     uint8_t iso_started;
100     AsyncURB *iso_urb;
101     int iso_urb_idx;
102     int iso_buffer_used;
103     int max_packet_size;
104 };
105
106 struct USBAutoFilter {
107     uint32_t bus_num;
108     uint32_t addr;
109     char     *port;
110     uint32_t vendor_id;
111     uint32_t product_id;
112 };
113
114 typedef struct USBHostDevice {
115     USBDevice dev;
116     int       fd;
117
118     uint8_t   descr[1024];
119     int       descr_len;
120     int       configuration;
121     int       ninterfaces;
122     int       closing;
123     Notifier  exit;
124
125     struct endp_data endp_table[MAX_ENDPOINTS];
126     QLIST_HEAD(, AsyncURB) aurbs;
127
128     /* Host side address */
129     int bus_num;
130     int addr;
131     char port[MAX_PORTLEN];
132     struct USBAutoFilter match;
133
134     QTAILQ_ENTRY(USBHostDevice) next;
135 } USBHostDevice;
136
137 static QTAILQ_HEAD(, USBHostDevice) hostdevs = QTAILQ_HEAD_INITIALIZER(hostdevs);
138
139 static int usb_host_close(USBHostDevice *dev);
140 static int parse_filter(const char *spec, struct USBAutoFilter *f);
141 static void usb_host_auto_check(void *unused);
142 static int usb_host_read_file(char *line, size_t line_size,
143                             const char *device_file, const char *device_name);
144
145 static int is_isoc(USBHostDevice *s, int ep)
146 {
147     return s->endp_table[ep - 1].type == USBDEVFS_URB_TYPE_ISO;
148 }
149
150 static int is_valid(USBHostDevice *s, int ep)
151 {
152     return s->endp_table[ep - 1].type != INVALID_EP_TYPE;
153 }
154
155 static int is_halted(USBHostDevice *s, int ep)
156 {
157     return s->endp_table[ep - 1].halted;
158 }
159
160 static void clear_halt(USBHostDevice *s, int ep)
161 {
162     s->endp_table[ep - 1].halted = 0;
163 }
164
165 static void set_halt(USBHostDevice *s, int ep)
166 {
167     s->endp_table[ep - 1].halted = 1;
168 }
169
170 static int is_iso_started(USBHostDevice *s, int ep)
171 {
172     return s->endp_table[ep - 1].iso_started;
173 }
174
175 static void clear_iso_started(USBHostDevice *s, int ep)
176 {
177     s->endp_table[ep - 1].iso_started = 0;
178 }
179
180 static void set_iso_started(USBHostDevice *s, int ep)
181 {
182     s->endp_table[ep - 1].iso_started = 1;
183 }
184
185 static void set_iso_urb(USBHostDevice *s, int ep, AsyncURB *iso_urb)
186 {
187     s->endp_table[ep - 1].iso_urb = iso_urb;
188 }
189
190 static AsyncURB *get_iso_urb(USBHostDevice *s, int ep)
191 {
192     return s->endp_table[ep - 1].iso_urb;
193 }
194
195 static void set_iso_urb_idx(USBHostDevice *s, int ep, int i)
196 {
197     s->endp_table[ep - 1].iso_urb_idx = i;
198 }
199
200 static int get_iso_urb_idx(USBHostDevice *s, int ep)
201 {
202     return s->endp_table[ep - 1].iso_urb_idx;
203 }
204
205 static void set_iso_buffer_used(USBHostDevice *s, int ep, int i)
206 {
207     s->endp_table[ep - 1].iso_buffer_used = i;
208 }
209
210 static int get_iso_buffer_used(USBHostDevice *s, int ep)
211 {
212     return s->endp_table[ep - 1].iso_buffer_used;
213 }
214
215 static void set_max_packet_size(USBHostDevice *s, int ep, uint8_t *descriptor)
216 {
217     int raw = descriptor[4] + (descriptor[5] << 8);
218     int size, microframes;
219
220     size = raw & 0x7ff;
221     switch ((raw >> 11) & 3) {
222     case 1:  microframes = 2; break;
223     case 2:  microframes = 3; break;
224     default: microframes = 1; break;
225     }
226     DPRINTF("husb: max packet size: 0x%x -> %d x %d\n",
227             raw, microframes, size);
228     s->endp_table[ep - 1].max_packet_size = size * microframes;
229 }
230
231 static int get_max_packet_size(USBHostDevice *s, int ep)
232 {
233     return s->endp_table[ep - 1].max_packet_size;
234 }
235
236 /*
237  * Async URB state.
238  * We always allocate iso packet descriptors even for bulk transfers
239  * to simplify allocation and casts.
240  */
241 struct AsyncURB
242 {
243     struct usbdevfs_urb urb;
244     struct usbdevfs_iso_packet_desc isocpd[ISO_FRAME_DESC_PER_URB];
245     USBHostDevice *hdev;
246     QLIST_ENTRY(AsyncURB) next;
247
248     /* For regular async urbs */
249     USBPacket     *packet;
250     int more; /* large transfer, more urbs follow */
251
252     /* For buffered iso handling */
253     int iso_frame_idx; /* -1 means in flight */
254 };
255
256 static AsyncURB *async_alloc(USBHostDevice *s)
257 {
258     AsyncURB *aurb = qemu_mallocz(sizeof(AsyncURB));
259     aurb->hdev = s;
260     QLIST_INSERT_HEAD(&s->aurbs, aurb, next);
261     return aurb;
262 }
263
264 static void async_free(AsyncURB *aurb)
265 {
266     QLIST_REMOVE(aurb, next);
267     qemu_free(aurb);
268 }
269
270 static void do_disconnect(USBHostDevice *s)
271 {
272     printf("husb: device %d.%d disconnected\n",
273            s->bus_num, s->addr);
274     usb_host_close(s);
275     usb_host_auto_check(NULL);
276 }
277
278 static void async_complete(void *opaque)
279 {
280     USBHostDevice *s = opaque;
281     AsyncURB *aurb;
282
283     while (1) {
284         USBPacket *p;
285
286         int r = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &aurb);
287         if (r < 0) {
288             if (errno == EAGAIN) {
289                 return;
290             }
291             if (errno == ENODEV && !s->closing) {
292                 do_disconnect(s);
293                 return;
294             }
295
296             DPRINTF("husb: async. reap urb failed errno %d\n", errno);
297             return;
298         }
299
300         DPRINTF("husb: async completed. aurb %p status %d alen %d\n",
301                 aurb, aurb->urb.status, aurb->urb.actual_length);
302
303         /* If this is a buffered iso urb mark it as complete and don't do
304            anything else (it is handled further in usb_host_handle_iso_data) */
305         if (aurb->iso_frame_idx == -1) {
306             if (aurb->urb.status == -EPIPE) {
307                 set_halt(s, aurb->urb.endpoint & 0xf);
308             }
309             aurb->iso_frame_idx = 0;
310             continue;
311         }
312
313         p = aurb->packet;
314
315         if (p) {
316             switch (aurb->urb.status) {
317             case 0:
318                 p->len += aurb->urb.actual_length;
319                 break;
320
321             case -EPIPE:
322                 set_halt(s, p->devep);
323                 p->len = USB_RET_STALL;
324                 break;
325
326             default:
327                 p->len = USB_RET_NAK;
328                 break;
329             }
330
331             if (aurb->urb.type == USBDEVFS_URB_TYPE_CONTROL) {
332                 usb_generic_async_ctrl_complete(&s->dev, p);
333             } else if (!aurb->more) {
334                 usb_packet_complete(&s->dev, p);
335             }
336         }
337
338         async_free(aurb);
339     }
340 }
341
342 static void usb_host_async_cancel(USBDevice *dev, USBPacket *p)
343 {
344     USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
345     AsyncURB *aurb;
346
347     QLIST_FOREACH(aurb, &s->aurbs, next) {
348         if (p != aurb->packet) {
349             continue;
350         }
351
352         DPRINTF("husb: async cancel: packet %p, aurb %p\n", p, aurb);
353
354         /* Mark it as dead (see async_complete above) */
355         aurb->packet = NULL;
356
357         int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
358         if (r < 0) {
359             DPRINTF("husb: async. discard urb failed errno %d\n", errno);
360         }
361     }
362 }
363
364 static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
365 {
366     const char *op = NULL;
367     int dev_descr_len, config_descr_len;
368     int interface, nb_interfaces;
369     int ret, i;
370
371     if (configuration == 0) /* address state - ignore */
372         return 1;
373
374     DPRINTF("husb: claiming interfaces. config %d\n", configuration);
375
376     i = 0;
377     dev_descr_len = dev->descr[0];
378     if (dev_descr_len > dev->descr_len) {
379         goto fail;
380     }
381
382     i += dev_descr_len;
383     while (i < dev->descr_len) {
384         DPRINTF("husb: i is %d, descr_len is %d, dl %d, dt %d\n",
385                 i, dev->descr_len,
386                dev->descr[i], dev->descr[i+1]);
387
388         if (dev->descr[i+1] != USB_DT_CONFIG) {
389             i += dev->descr[i];
390             continue;
391         }
392         config_descr_len = dev->descr[i];
393
394         printf("husb: config #%d need %d\n", dev->descr[i + 5], configuration);
395
396         if (configuration < 0 || configuration == dev->descr[i + 5]) {
397             configuration = dev->descr[i + 5];
398             break;
399         }
400
401         i += config_descr_len;
402     }
403
404     if (i >= dev->descr_len) {
405         fprintf(stderr,
406                 "husb: update iface failed. no matching configuration\n");
407         goto fail;
408     }
409     nb_interfaces = dev->descr[i + 4];
410
411 #ifdef USBDEVFS_DISCONNECT
412     /* earlier Linux 2.4 do not support that */
413     {
414         struct usbdevfs_ioctl ctrl;
415         for (interface = 0; interface < nb_interfaces; interface++) {
416             ctrl.ioctl_code = USBDEVFS_DISCONNECT;
417             ctrl.ifno = interface;
418             ctrl.data = 0;
419             op = "USBDEVFS_DISCONNECT";
420             ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
421             if (ret < 0 && errno != ENODATA) {
422                 goto fail;
423             }
424         }
425     }
426 #endif
427
428     /* XXX: only grab if all interfaces are free */
429     for (interface = 0; interface < nb_interfaces; interface++) {
430         op = "USBDEVFS_CLAIMINTERFACE";
431         ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
432         if (ret < 0) {
433             if (errno == EBUSY) {
434                 printf("husb: update iface. device already grabbed\n");
435             } else {
436                 perror("husb: failed to claim interface");
437             }
438             goto fail;
439         }
440     }
441
442     printf("husb: %d interfaces claimed for configuration %d\n",
443            nb_interfaces, configuration);
444
445     dev->ninterfaces   = nb_interfaces;
446     dev->configuration = configuration;
447     return 1;
448
449 fail:
450     if (errno == ENODEV) {
451         do_disconnect(dev);
452     }
453     perror(op);
454     return 0;
455 }
456
457 static int usb_host_release_interfaces(USBHostDevice *s)
458 {
459     int ret, i;
460
461     DPRINTF("husb: releasing interfaces\n");
462
463     for (i = 0; i < s->ninterfaces; i++) {
464         ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
465         if (ret < 0) {
466             perror("husb: failed to release interface");
467             return 0;
468         }
469     }
470
471     return 1;
472 }
473
474 static void usb_host_handle_reset(USBDevice *dev)
475 {
476     USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
477
478     DPRINTF("husb: reset device %u.%u\n", s->bus_num, s->addr);
479
480     ioctl(s->fd, USBDEVFS_RESET);
481
482     usb_host_claim_interfaces(s, s->configuration);
483 }
484
485 static void usb_host_handle_destroy(USBDevice *dev)
486 {
487     USBHostDevice *s = (USBHostDevice *)dev;
488
489     usb_host_close(s);
490     QTAILQ_REMOVE(&hostdevs, s, next);
491     qemu_remove_exit_notifier(&s->exit);
492 }
493
494 static int usb_linux_update_endp_table(USBHostDevice *s);
495
496 /* iso data is special, we need to keep enough urbs in flight to make sure
497    that the controller never runs out of them, otherwise the device will
498    likely suffer a buffer underrun / overrun. */
499 static AsyncURB *usb_host_alloc_iso(USBHostDevice *s, uint8_t ep, int in)
500 {
501     AsyncURB *aurb;
502     int i, j, len = get_max_packet_size(s, ep);
503
504     aurb = qemu_mallocz(ISO_URB_COUNT * sizeof(*aurb));
505     for (i = 0; i < ISO_URB_COUNT; i++) {
506         aurb[i].urb.endpoint      = ep;
507         aurb[i].urb.buffer_length = ISO_FRAME_DESC_PER_URB * len;
508         aurb[i].urb.buffer        = qemu_malloc(aurb[i].urb.buffer_length);
509         aurb[i].urb.type          = USBDEVFS_URB_TYPE_ISO;
510         aurb[i].urb.flags         = USBDEVFS_URB_ISO_ASAP;
511         aurb[i].urb.number_of_packets = ISO_FRAME_DESC_PER_URB;
512         for (j = 0 ; j < ISO_FRAME_DESC_PER_URB; j++)
513             aurb[i].urb.iso_frame_desc[j].length = len;
514         if (in) {
515             aurb[i].urb.endpoint |= 0x80;
516             /* Mark as fully consumed (idle) */
517             aurb[i].iso_frame_idx = ISO_FRAME_DESC_PER_URB;
518         }
519     }
520     set_iso_urb(s, ep, aurb);
521
522     return aurb;
523 }
524
525 static void usb_host_stop_n_free_iso(USBHostDevice *s, uint8_t ep)
526 {
527     AsyncURB *aurb;
528     int i, ret, killed = 0, free = 1;
529
530     aurb = get_iso_urb(s, ep);
531     if (!aurb) {
532         return;
533     }
534
535     for (i = 0; i < ISO_URB_COUNT; i++) {
536         /* in flight? */
537         if (aurb[i].iso_frame_idx == -1) {
538             ret = ioctl(s->fd, USBDEVFS_DISCARDURB, &aurb[i]);
539             if (ret < 0) {
540                 printf("husb: discard isoc in urb failed errno %d\n", errno);
541                 free = 0;
542                 continue;
543             }
544             killed++;
545         }
546     }
547
548     /* Make sure any urbs we've killed are reaped before we free them */
549     if (killed) {
550         async_complete(s);
551     }
552
553     for (i = 0; i < ISO_URB_COUNT; i++) {
554         qemu_free(aurb[i].urb.buffer);
555     }
556
557     if (free)
558         qemu_free(aurb);
559     else
560         printf("husb: leaking iso urbs because of discard failure\n");
561     set_iso_urb(s, ep, NULL);
562     set_iso_urb_idx(s, ep, 0);
563     clear_iso_started(s, ep);
564 }
565
566 static int urb_status_to_usb_ret(int status)
567 {
568     switch (status) {
569     case -EPIPE:
570         return USB_RET_STALL;
571     default:
572         return USB_RET_NAK;
573     }
574 }
575
576 static int usb_host_handle_iso_data(USBHostDevice *s, USBPacket *p, int in)
577 {
578     AsyncURB *aurb;
579     int i, j, ret, max_packet_size, offset, len = 0;
580
581     max_packet_size = get_max_packet_size(s, p->devep);
582     if (max_packet_size == 0)
583         return USB_RET_NAK;
584
585     aurb = get_iso_urb(s, p->devep);
586     if (!aurb) {
587         aurb = usb_host_alloc_iso(s, p->devep, in);
588     }
589
590     i = get_iso_urb_idx(s, p->devep);
591     j = aurb[i].iso_frame_idx;
592     if (j >= 0 && j < ISO_FRAME_DESC_PER_URB) {
593         if (in) {
594             /* Check urb status  */
595             if (aurb[i].urb.status) {
596                 len = urb_status_to_usb_ret(aurb[i].urb.status);
597                 /* Move to the next urb */
598                 aurb[i].iso_frame_idx = ISO_FRAME_DESC_PER_URB - 1;
599             /* Check frame status */
600             } else if (aurb[i].urb.iso_frame_desc[j].status) {
601                 len = urb_status_to_usb_ret(
602                                         aurb[i].urb.iso_frame_desc[j].status);
603             /* Check the frame fits */
604             } else if (aurb[i].urb.iso_frame_desc[j].actual_length > p->len) {
605                 printf("husb: received iso data is larger then packet\n");
606                 len = USB_RET_NAK;
607             /* All good copy data over */
608             } else {
609                 len = aurb[i].urb.iso_frame_desc[j].actual_length;
610                 memcpy(p->data,
611                        aurb[i].urb.buffer +
612                            j * aurb[i].urb.iso_frame_desc[0].length,
613                        len);
614             }
615         } else {
616             len = p->len;
617             offset = (j == 0) ? 0 : get_iso_buffer_used(s, p->devep);
618
619             /* Check the frame fits */
620             if (len > max_packet_size) {
621                 printf("husb: send iso data is larger then max packet size\n");
622                 return USB_RET_NAK;
623             }
624
625             /* All good copy data over */
626             memcpy(aurb[i].urb.buffer + offset, p->data, len);
627             aurb[i].urb.iso_frame_desc[j].length = len;
628             offset += len;
629             set_iso_buffer_used(s, p->devep, offset);
630
631             /* Start the stream once we have buffered enough data */
632             if (!is_iso_started(s, p->devep) && i == 1 && j == 8) {
633                 set_iso_started(s, p->devep);
634             }
635         }
636         aurb[i].iso_frame_idx++;
637         if (aurb[i].iso_frame_idx == ISO_FRAME_DESC_PER_URB) {
638             i = (i + 1) % ISO_URB_COUNT;
639             set_iso_urb_idx(s, p->devep, i);
640         }
641     } else {
642         if (in) {
643             set_iso_started(s, p->devep);
644         } else {
645             DPRINTF("hubs: iso out error no free buffer, dropping packet\n");
646         }
647     }
648
649     if (is_iso_started(s, p->devep)) {
650         /* (Re)-submit all fully consumed / filled urbs */
651         for (i = 0; i < ISO_URB_COUNT; i++) {
652             if (aurb[i].iso_frame_idx == ISO_FRAME_DESC_PER_URB) {
653                 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, &aurb[i]);
654                 if (ret < 0) {
655                     printf("husb error submitting iso urb %d: %d\n", i, errno);
656                     if (!in || len == 0) {
657                         switch(errno) {
658                         case ETIMEDOUT:
659                             len = USB_RET_NAK;
660                             break;
661                         case EPIPE:
662                         default:
663                             len = USB_RET_STALL;
664                         }
665                     }
666                     break;
667                 }
668                 aurb[i].iso_frame_idx = -1;
669             }
670         }
671     }
672
673     return len;
674 }
675
676 static int usb_host_handle_data(USBDevice *dev, USBPacket *p)
677 {
678     USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
679     struct usbdevfs_urb *urb;
680     AsyncURB *aurb;
681     int ret, rem;
682     uint8_t *pbuf;
683     uint8_t ep;
684
685     if (!is_valid(s, p->devep)) {
686         return USB_RET_NAK;
687     }
688
689     if (p->pid == USB_TOKEN_IN) {
690         ep = p->devep | 0x80;
691     } else {
692         ep = p->devep;
693     }
694
695     if (is_halted(s, p->devep)) {
696         ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &ep);
697         if (ret < 0) {
698             DPRINTF("husb: failed to clear halt. ep 0x%x errno %d\n",
699                    ep, errno);
700             return USB_RET_NAK;
701         }
702         clear_halt(s, p->devep);
703     }
704
705     if (is_isoc(s, p->devep)) {
706         return usb_host_handle_iso_data(s, p, p->pid == USB_TOKEN_IN);
707     }
708
709     rem = p->len;
710     pbuf = p->data;
711     p->len = 0;
712     while (rem) {
713         aurb = async_alloc(s);
714         aurb->packet = p;
715
716         urb = &aurb->urb;
717         urb->endpoint      = ep;
718         urb->type          = USBDEVFS_URB_TYPE_BULK;
719         urb->usercontext   = s;
720         urb->buffer        = pbuf;
721
722         if (rem > MAX_USBFS_BUFFER_SIZE) {
723             urb->buffer_length = MAX_USBFS_BUFFER_SIZE;
724             aurb->more         = 1;
725         } else {
726             urb->buffer_length = rem;
727             aurb->more         = 0;
728         }
729         pbuf += urb->buffer_length;
730         rem  -= urb->buffer_length;
731
732         ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
733
734         DPRINTF("husb: data submit: ep 0x%x, len %u, more %d, packet %p, aurb %p\n",
735                 urb->endpoint, urb->buffer_length, aurb->more, p, aurb);
736
737         if (ret < 0) {
738             DPRINTF("husb: submit failed. errno %d\n", errno);
739             async_free(aurb);
740
741             switch(errno) {
742             case ETIMEDOUT:
743                 return USB_RET_NAK;
744             case EPIPE:
745             default:
746                 return USB_RET_STALL;
747             }
748         }
749     }
750
751     return USB_RET_ASYNC;
752 }
753
754 static int ctrl_error(void)
755 {
756     if (errno == ETIMEDOUT) {
757         return USB_RET_NAK;
758     } else {
759         return USB_RET_STALL;
760     }
761 }
762
763 static int usb_host_set_address(USBHostDevice *s, int addr)
764 {
765     DPRINTF("husb: ctrl set addr %u\n", addr);
766     s->dev.addr = addr;
767     return 0;
768 }
769
770 static int usb_host_set_config(USBHostDevice *s, int config)
771 {
772     usb_host_release_interfaces(s);
773
774     int ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
775
776     DPRINTF("husb: ctrl set config %d ret %d errno %d\n", config, ret, errno);
777
778     if (ret < 0) {
779         return ctrl_error();
780     }
781     usb_host_claim_interfaces(s, config);
782     return 0;
783 }
784
785 static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
786 {
787     struct usbdevfs_setinterface si;
788     int i, ret;
789
790     for (i = 1; i <= MAX_ENDPOINTS; i++) {
791         if (is_isoc(s, i)) {
792             usb_host_stop_n_free_iso(s, i);
793         }
794     }
795
796     si.interface  = iface;
797     si.altsetting = alt;
798     ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
799
800     DPRINTF("husb: ctrl set iface %d altset %d ret %d errno %d\n",
801             iface, alt, ret, errno);
802
803     if (ret < 0) {
804         return ctrl_error();
805     }
806     usb_linux_update_endp_table(s);
807     return 0;
808 }
809
810 static int usb_host_handle_control(USBDevice *dev, USBPacket *p,
811                int request, int value, int index, int length, uint8_t *data)
812 {
813     USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
814     struct usbdevfs_urb *urb;
815     AsyncURB *aurb;
816     int ret;
817
818     /*
819      * Process certain standard device requests.
820      * These are infrequent and are processed synchronously.
821      */
822
823     /* Note request is (bRequestType << 8) | bRequest */
824     DPRINTF("husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\n",
825             request >> 8, request & 0xff, value, index, length);
826
827     switch (request) {
828     case DeviceOutRequest | USB_REQ_SET_ADDRESS:
829         return usb_host_set_address(s, value);
830
831     case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
832         return usb_host_set_config(s, value & 0xff);
833
834     case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
835         return usb_host_set_interface(s, index, value);
836     }
837
838     /* The rest are asynchronous */
839
840     if (length > sizeof(dev->data_buf)) {
841         fprintf(stderr, "husb: ctrl buffer too small (%d > %zu)\n",
842                 length, sizeof(dev->data_buf));
843         return USB_RET_STALL;
844     }
845
846     aurb = async_alloc(s);
847     aurb->packet = p;
848
849     /*
850      * Setup ctrl transfer.
851      *
852      * s->ctrl is laid out such that data buffer immediately follows
853      * 'req' struct which is exactly what usbdevfs expects.
854      */
855     urb = &aurb->urb;
856
857     urb->type     = USBDEVFS_URB_TYPE_CONTROL;
858     urb->endpoint = p->devep;
859
860     urb->buffer        = &dev->setup_buf;
861     urb->buffer_length = length + 8;
862
863     urb->usercontext = s;
864
865     ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
866
867     DPRINTF("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb);
868
869     if (ret < 0) {
870         DPRINTF("husb: submit failed. errno %d\n", errno);
871         async_free(aurb);
872
873         switch(errno) {
874         case ETIMEDOUT:
875             return USB_RET_NAK;
876         case EPIPE:
877         default:
878             return USB_RET_STALL;
879         }
880     }
881
882     return USB_RET_ASYNC;
883 }
884
885 static int usb_linux_get_configuration(USBHostDevice *s)
886 {
887     uint8_t configuration;
888     struct usb_ctrltransfer ct;
889     int ret;
890
891     if (usb_fs_type == USB_FS_SYS) {
892         char device_name[32], line[1024];
893         int configuration;
894
895         sprintf(device_name, "%d-%s", s->bus_num, s->port);
896
897         if (!usb_host_read_file(line, sizeof(line), "bConfigurationValue",
898                                 device_name)) {
899             goto usbdevfs;
900         }
901         if (sscanf(line, "%d", &configuration) != 1) {
902             goto usbdevfs;
903         }
904         return configuration;
905     }
906
907 usbdevfs:
908     ct.bRequestType = USB_DIR_IN;
909     ct.bRequest = USB_REQ_GET_CONFIGURATION;
910     ct.wValue = 0;
911     ct.wIndex = 0;
912     ct.wLength = 1;
913     ct.data = &configuration;
914     ct.timeout = 50;
915
916     ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
917     if (ret < 0) {
918         perror("usb_linux_get_configuration");
919         return -1;
920     }
921
922     /* in address state */
923     if (configuration == 0) {
924         return -1;
925     }
926
927     return configuration;
928 }
929
930 static uint8_t usb_linux_get_alt_setting(USBHostDevice *s,
931     uint8_t configuration, uint8_t interface)
932 {
933     uint8_t alt_setting;
934     struct usb_ctrltransfer ct;
935     int ret;
936
937     if (usb_fs_type == USB_FS_SYS) {
938         char device_name[64], line[1024];
939         int alt_setting;
940
941         sprintf(device_name, "%d-%s:%d.%d", s->bus_num, s->port,
942                 (int)configuration, (int)interface);
943
944         if (!usb_host_read_file(line, sizeof(line), "bAlternateSetting",
945                                 device_name)) {
946             goto usbdevfs;
947         }
948         if (sscanf(line, "%d", &alt_setting) != 1) {
949             goto usbdevfs;
950         }
951         return alt_setting;
952     }
953
954 usbdevfs:
955     ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
956     ct.bRequest = USB_REQ_GET_INTERFACE;
957     ct.wValue = 0;
958     ct.wIndex = interface;
959     ct.wLength = 1;
960     ct.data = &alt_setting;
961     ct.timeout = 50;
962     ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
963     if (ret < 0) {
964         /* Assume alt 0 on error */
965         return 0;
966     }
967
968     return alt_setting;
969 }
970
971 /* returns 1 on problem encountered or 0 for success */
972 static int usb_linux_update_endp_table(USBHostDevice *s)
973 {
974     uint8_t *descriptors;
975     uint8_t devep, type, configuration, alt_interface;
976     int interface, length, i;
977
978     for (i = 0; i < MAX_ENDPOINTS; i++)
979         s->endp_table[i].type = INVALID_EP_TYPE;
980
981     i = usb_linux_get_configuration(s);
982     if (i < 0)
983         return 1;
984     configuration = i;
985
986     /* get the desired configuration, interface, and endpoint descriptors
987      * from device description */
988     descriptors = &s->descr[18];
989     length = s->descr_len - 18;
990     i = 0;
991
992     if (descriptors[i + 1] != USB_DT_CONFIG ||
993         descriptors[i + 5] != configuration) {
994         DPRINTF("invalid descriptor data - configuration\n");
995         return 1;
996     }
997     i += descriptors[i];
998
999     while (i < length) {
1000         if (descriptors[i + 1] != USB_DT_INTERFACE ||
1001             (descriptors[i + 1] == USB_DT_INTERFACE &&
1002              descriptors[i + 4] == 0)) {
1003             i += descriptors[i];
1004             continue;
1005         }
1006
1007         interface = descriptors[i + 2];
1008         alt_interface = usb_linux_get_alt_setting(s, configuration, interface);
1009
1010         /* the current interface descriptor is the active interface
1011          * and has endpoints */
1012         if (descriptors[i + 3] != alt_interface) {
1013             i += descriptors[i];
1014             continue;
1015         }
1016
1017         /* advance to the endpoints */
1018         while (i < length && descriptors[i +1] != USB_DT_ENDPOINT) {
1019             i += descriptors[i];
1020         }
1021
1022         if (i >= length)
1023             break;
1024
1025         while (i < length) {
1026             if (descriptors[i + 1] != USB_DT_ENDPOINT) {
1027                 break;
1028             }
1029
1030             devep = descriptors[i + 2];
1031             switch (descriptors[i + 3] & 0x3) {
1032             case 0x00:
1033                 type = USBDEVFS_URB_TYPE_CONTROL;
1034                 break;
1035             case 0x01:
1036                 type = USBDEVFS_URB_TYPE_ISO;
1037                 set_max_packet_size(s, (devep & 0xf), descriptors + i);
1038                 break;
1039             case 0x02:
1040                 type = USBDEVFS_URB_TYPE_BULK;
1041                 break;
1042             case 0x03:
1043                 type = USBDEVFS_URB_TYPE_INTERRUPT;
1044                 break;
1045             default:
1046                 DPRINTF("usb_host: malformed endpoint type\n");
1047                 type = USBDEVFS_URB_TYPE_BULK;
1048             }
1049             s->endp_table[(devep & 0xf) - 1].type = type;
1050             s->endp_table[(devep & 0xf) - 1].halted = 0;
1051
1052             i += descriptors[i];
1053         }
1054     }
1055     return 0;
1056 }
1057
1058 static int usb_host_open(USBHostDevice *dev, int bus_num,
1059                         int addr, char *port, const char *prod_name, int speed)
1060 {
1061     int fd = -1, ret;
1062     char buf[1024];
1063
1064     if (dev->fd != -1) {
1065         goto fail;
1066     }
1067     printf("husb: open device %d.%d\n", bus_num, addr);
1068
1069     if (!usb_host_device_path) {
1070         perror("husb: USB Host Device Path not set");
1071         goto fail;
1072     }
1073     snprintf(buf, sizeof(buf), "%s/%03d/%03d", usb_host_device_path,
1074              bus_num, addr);
1075     fd = open(buf, O_RDWR | O_NONBLOCK);
1076     if (fd < 0) {
1077         perror(buf);
1078         goto fail;
1079     }
1080     DPRINTF("husb: opened %s\n", buf);
1081
1082     dev->bus_num = bus_num;
1083     dev->addr = addr;
1084     strcpy(dev->port, port);
1085     dev->fd = fd;
1086
1087     /* read the device description */
1088     dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
1089     if (dev->descr_len <= 0) {
1090         perror("husb: reading device data failed");
1091         goto fail;
1092     }
1093
1094 #ifdef DEBUG
1095     {
1096         int x;
1097         printf("=== begin dumping device descriptor data ===\n");
1098         for (x = 0; x < dev->descr_len; x++) {
1099             printf("%02x ", dev->descr[x]);
1100         }
1101         printf("\n=== end dumping device descriptor data ===\n");
1102     }
1103 #endif
1104
1105
1106     /*
1107      * Initial configuration is -1 which makes us claim first
1108      * available config. We used to start with 1, which does not
1109      * always work. I've seen devices where first config starts
1110      * with 2.
1111      */
1112     if (!usb_host_claim_interfaces(dev, -1)) {
1113         goto fail;
1114     }
1115
1116     ret = usb_linux_update_endp_table(dev);
1117     if (ret) {
1118         goto fail;
1119     }
1120
1121     if (speed == -1) {
1122         struct usbdevfs_connectinfo ci;
1123
1124         ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
1125         if (ret < 0) {
1126             perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
1127             goto fail;
1128         }
1129
1130         if (ci.slow) {
1131             speed = USB_SPEED_LOW;
1132         } else {
1133             speed = USB_SPEED_HIGH;
1134         }
1135     }
1136     dev->dev.speed = speed;
1137
1138     printf("husb: grabbed usb device %d.%d\n", bus_num, addr);
1139
1140     if (!prod_name || prod_name[0] == '\0') {
1141         snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1142                  "host:%d.%d", bus_num, addr);
1143     } else {
1144         pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1145                 prod_name);
1146     }
1147
1148     /* USB devio uses 'write' flag to check for async completions */
1149     qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);
1150
1151     usb_device_attach(&dev->dev);
1152     return 0;
1153
1154 fail:
1155     dev->fd = -1;
1156     if (fd != -1) {
1157         close(fd);
1158     }
1159     return -1;
1160 }
1161
1162 static int usb_host_close(USBHostDevice *dev)
1163 {
1164     int i;
1165
1166     if (dev->fd == -1) {
1167         return -1;
1168     }
1169
1170     qemu_set_fd_handler(dev->fd, NULL, NULL, NULL);
1171     dev->closing = 1;
1172     for (i = 1; i <= MAX_ENDPOINTS; i++) {
1173         if (is_isoc(dev, i)) {
1174             usb_host_stop_n_free_iso(dev, i);
1175         }
1176     }
1177     async_complete(dev);
1178     dev->closing = 0;
1179     usb_device_detach(&dev->dev);
1180     ioctl(dev->fd, USBDEVFS_RESET);
1181     close(dev->fd);
1182     dev->fd = -1;
1183     return 0;
1184 }
1185
1186 static void usb_host_exit_notifier(struct Notifier* n)
1187 {
1188     USBHostDevice *s = container_of(n, USBHostDevice, exit);
1189
1190     if (s->fd != -1) {
1191         ioctl(s->fd, USBDEVFS_RESET);
1192     }
1193 }
1194
1195 static int usb_host_initfn(USBDevice *dev)
1196 {
1197     USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1198
1199     dev->auto_attach = 0;
1200     s->fd = -1;
1201     QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1202     s->exit.notify = usb_host_exit_notifier;
1203     qemu_add_exit_notifier(&s->exit);
1204     usb_host_auto_check(NULL);
1205     return 0;
1206 }
1207
1208 static struct USBDeviceInfo usb_host_dev_info = {
1209     .product_desc   = "USB Host Device",
1210     .qdev.name      = "usb-host",
1211     .qdev.size      = sizeof(USBHostDevice),
1212     .init           = usb_host_initfn,
1213     .handle_packet  = usb_generic_handle_packet,
1214     .cancel_packet  = usb_host_async_cancel,
1215     .handle_data    = usb_host_handle_data,
1216     .handle_control = usb_host_handle_control,
1217     .handle_reset   = usb_host_handle_reset,
1218     .handle_destroy = usb_host_handle_destroy,
1219     .usbdevice_name = "host",
1220     .usbdevice_init = usb_host_device_open,
1221     .qdev.props     = (Property[]) {
1222         DEFINE_PROP_UINT32("hostbus",  USBHostDevice, match.bus_num,    0),
1223         DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr,       0),
1224         DEFINE_PROP_STRING("hostport", USBHostDevice, match.port),
1225         DEFINE_PROP_HEX32("vendorid",  USBHostDevice, match.vendor_id,  0),
1226         DEFINE_PROP_HEX32("productid", USBHostDevice, match.product_id, 0),
1227         DEFINE_PROP_END_OF_LIST(),
1228     },
1229 };
1230
1231 static void usb_host_register_devices(void)
1232 {
1233     usb_qdev_register(&usb_host_dev_info);
1234 }
1235 device_init(usb_host_register_devices)
1236
1237 USBDevice *usb_host_device_open(const char *devname)
1238 {
1239     struct USBAutoFilter filter;
1240     USBDevice *dev;
1241     char *p;
1242
1243     dev = usb_create(NULL /* FIXME */, "usb-host");
1244
1245     if (strstr(devname, "auto:")) {
1246         if (parse_filter(devname, &filter) < 0) {
1247             goto fail;
1248         }
1249     } else {
1250         if ((p = strchr(devname, '.'))) {
1251             filter.bus_num    = strtoul(devname, NULL, 0);
1252             filter.addr       = strtoul(p + 1, NULL, 0);
1253             filter.vendor_id  = 0;
1254             filter.product_id = 0;
1255         } else if ((p = strchr(devname, ':'))) {
1256             filter.bus_num    = 0;
1257             filter.addr       = 0;
1258             filter.vendor_id  = strtoul(devname, NULL, 16);
1259             filter.product_id = strtoul(p + 1, NULL, 16);
1260         } else {
1261             goto fail;
1262         }
1263     }
1264
1265     qdev_prop_set_uint32(&dev->qdev, "hostbus",   filter.bus_num);
1266     qdev_prop_set_uint32(&dev->qdev, "hostaddr",  filter.addr);
1267     qdev_prop_set_uint32(&dev->qdev, "vendorid",  filter.vendor_id);
1268     qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);
1269     qdev_init_nofail(&dev->qdev);
1270     return dev;
1271
1272 fail:
1273     qdev_free(&dev->qdev);
1274     return NULL;
1275 }
1276
1277 int usb_host_device_close(const char *devname)
1278 {
1279 #if 0
1280     char product_name[PRODUCT_NAME_SZ];
1281     int bus_num, addr;
1282     USBHostDevice *s;
1283
1284     if (strstr(devname, "auto:")) {
1285         return usb_host_auto_del(devname);
1286     }
1287     if (usb_host_find_device(&bus_num, &addr, product_name,
1288                                     sizeof(product_name), devname) < 0) {
1289         return -1;
1290     }
1291     s = hostdev_find(bus_num, addr);
1292     if (s) {
1293         usb_device_delete_addr(s->bus_num, s->dev.addr);
1294         return 0;
1295     }
1296 #endif
1297
1298     return -1;
1299 }
1300
1301 static int get_tag_value(char *buf, int buf_size,
1302                          const char *str, const char *tag,
1303                          const char *stopchars)
1304 {
1305     const char *p;
1306     char *q;
1307     p = strstr(str, tag);
1308     if (!p) {
1309         return -1;
1310     }
1311     p += strlen(tag);
1312     while (qemu_isspace(*p)) {
1313         p++;
1314     }
1315     q = buf;
1316     while (*p != '\0' && !strchr(stopchars, *p)) {
1317         if ((q - buf) < (buf_size - 1)) {
1318             *q++ = *p;
1319         }
1320         p++;
1321     }
1322     *q = '\0';
1323     return q - buf;
1324 }
1325
1326 /*
1327  * Use /proc/bus/usb/devices or /dev/bus/usb/devices file to determine
1328  * host's USB devices. This is legacy support since many distributions
1329  * are moving to /sys/bus/usb
1330  */
1331 static int usb_host_scan_dev(void *opaque, USBScanFunc *func)
1332 {
1333     FILE *f = NULL;
1334     char line[1024];
1335     char buf[1024];
1336     int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
1337     char product_name[512];
1338     int ret = 0;
1339
1340     if (!usb_host_device_path) {
1341         perror("husb: USB Host Device Path not set");
1342         goto the_end;
1343     }
1344     snprintf(line, sizeof(line), "%s/devices", usb_host_device_path);
1345     f = fopen(line, "r");
1346     if (!f) {
1347         perror("husb: cannot open devices file");
1348         goto the_end;
1349     }
1350
1351     device_count = 0;
1352     bus_num = addr = class_id = product_id = vendor_id = 0;
1353     speed = -1; /* Can't get the speed from /[proc|dev]/bus/usb/devices */
1354     for(;;) {
1355         if (fgets(line, sizeof(line), f) == NULL) {
1356             break;
1357         }
1358         if (strlen(line) > 0) {
1359             line[strlen(line) - 1] = '\0';
1360         }
1361         if (line[0] == 'T' && line[1] == ':') {
1362             if (device_count && (vendor_id || product_id)) {
1363                 /* New device.  Add the previously discovered device.  */
1364                 ret = func(opaque, bus_num, addr, 0, class_id, vendor_id,
1365                            product_id, product_name, speed);
1366                 if (ret) {
1367                     goto the_end;
1368                 }
1369             }
1370             if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0) {
1371                 goto fail;
1372             }
1373             bus_num = atoi(buf);
1374             if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0) {
1375                 goto fail;
1376             }
1377             addr = atoi(buf);
1378             if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0) {
1379                 goto fail;
1380             }
1381             if (!strcmp(buf, "5000")) {
1382                 speed = USB_SPEED_SUPER;
1383             } else if (!strcmp(buf, "480")) {
1384                 speed = USB_SPEED_HIGH;
1385             } else if (!strcmp(buf, "1.5")) {
1386                 speed = USB_SPEED_LOW;
1387             } else {
1388                 speed = USB_SPEED_FULL;
1389             }
1390             product_name[0] = '\0';
1391             class_id = 0xff;
1392             device_count++;
1393             product_id = 0;
1394             vendor_id = 0;
1395         } else if (line[0] == 'P' && line[1] == ':') {
1396             if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0) {
1397                 goto fail;
1398             }
1399             vendor_id = strtoul(buf, NULL, 16);
1400             if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0) {
1401                 goto fail;
1402             }
1403             product_id = strtoul(buf, NULL, 16);
1404         } else if (line[0] == 'S' && line[1] == ':') {
1405             if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0) {
1406                 goto fail;
1407             }
1408             pstrcpy(product_name, sizeof(product_name), buf);
1409         } else if (line[0] == 'D' && line[1] == ':') {
1410             if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0) {
1411                 goto fail;
1412             }
1413             class_id = strtoul(buf, NULL, 16);
1414         }
1415     fail: ;
1416     }
1417     if (device_count && (vendor_id || product_id)) {
1418         /* Add the last device.  */
1419         ret = func(opaque, bus_num, addr, 0, class_id, vendor_id,
1420                    product_id, product_name, speed);
1421     }
1422  the_end:
1423     if (f) {
1424         fclose(f);
1425     }
1426     return ret;
1427 }
1428
1429 /*
1430  * Read sys file-system device file
1431  *
1432  * @line address of buffer to put file contents in
1433  * @line_size size of line
1434  * @device_file path to device file (printf format string)
1435  * @device_name device being opened (inserted into device_file)
1436  *
1437  * @return 0 failed, 1 succeeded ('line' contains data)
1438  */
1439 static int usb_host_read_file(char *line, size_t line_size,
1440                               const char *device_file, const char *device_name)
1441 {
1442     FILE *f;
1443     int ret = 0;
1444     char filename[PATH_MAX];
1445
1446     snprintf(filename, PATH_MAX, USBSYSBUS_PATH "/devices/%s/%s", device_name,
1447              device_file);
1448     f = fopen(filename, "r");
1449     if (f) {
1450         ret = fgets(line, line_size, f) != NULL;
1451         fclose(f);
1452     }
1453
1454     return ret;
1455 }
1456
1457 /*
1458  * Use /sys/bus/usb/devices/ directory to determine host's USB
1459  * devices.
1460  *
1461  * This code is based on Robert Schiele's original patches posted to
1462  * the Novell bug-tracker https://bugzilla.novell.com/show_bug.cgi?id=241950
1463  */
1464 static int usb_host_scan_sys(void *opaque, USBScanFunc *func)
1465 {
1466     DIR *dir = NULL;
1467     char line[1024];
1468     int bus_num, addr, speed, class_id, product_id, vendor_id;
1469     int ret = 0;
1470     char port[MAX_PORTLEN];
1471     char product_name[512];
1472     struct dirent *de;
1473
1474     dir = opendir(USBSYSBUS_PATH "/devices");
1475     if (!dir) {
1476         perror("husb: cannot open devices directory");
1477         goto the_end;
1478     }
1479
1480     while ((de = readdir(dir))) {
1481         if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1482             if (sscanf(de->d_name, "%d-%7[0-9.]", &bus_num, port) < 2) {
1483                 continue;
1484             }
1485
1486             if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name)) {
1487                 goto the_end;
1488             }
1489             if (sscanf(line, "%d", &addr) != 1) {
1490                 goto the_end;
1491             }
1492             if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1493                                     de->d_name)) {
1494                 goto the_end;
1495             }
1496             if (sscanf(line, "%x", &class_id) != 1) {
1497                 goto the_end;
1498             }
1499
1500             if (!usb_host_read_file(line, sizeof(line), "idVendor",
1501                                     de->d_name)) {
1502                 goto the_end;
1503             }
1504             if (sscanf(line, "%x", &vendor_id) != 1) {
1505                 goto the_end;
1506             }
1507             if (!usb_host_read_file(line, sizeof(line), "idProduct",
1508                                     de->d_name)) {
1509                 goto the_end;
1510             }
1511             if (sscanf(line, "%x", &product_id) != 1) {
1512                 goto the_end;
1513             }
1514             if (!usb_host_read_file(line, sizeof(line), "product",
1515                                     de->d_name)) {
1516                 *product_name = 0;
1517             } else {
1518                 if (strlen(line) > 0) {
1519                     line[strlen(line) - 1] = '\0';
1520                 }
1521                 pstrcpy(product_name, sizeof(product_name), line);
1522             }
1523
1524             if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name)) {
1525                 goto the_end;
1526             }
1527             if (!strcmp(line, "5000\n")) {
1528                 speed = USB_SPEED_SUPER;
1529             } else if (!strcmp(line, "480\n")) {
1530                 speed = USB_SPEED_HIGH;
1531             } else if (!strcmp(line, "1.5\n")) {
1532                 speed = USB_SPEED_LOW;
1533             } else {
1534                 speed = USB_SPEED_FULL;
1535             }
1536
1537             ret = func(opaque, bus_num, addr, port, class_id, vendor_id,
1538                        product_id, product_name, speed);
1539             if (ret) {
1540                 goto the_end;
1541             }
1542         }
1543     }
1544  the_end:
1545     if (dir) {
1546         closedir(dir);
1547     }
1548     return ret;
1549 }
1550
1551 /*
1552  * Determine how to access the host's USB devices and call the
1553  * specific support function.
1554  */
1555 static int usb_host_scan(void *opaque, USBScanFunc *func)
1556 {
1557     Monitor *mon = cur_mon;
1558     FILE *f = NULL;
1559     DIR *dir = NULL;
1560     int ret = 0;
1561     const char *fs_type[] = {"unknown", "proc", "dev", "sys"};
1562     char devpath[PATH_MAX];
1563
1564     /* only check the host once */
1565     if (!usb_fs_type) {
1566         dir = opendir(USBSYSBUS_PATH "/devices");
1567         if (dir) {
1568             /* devices found in /dev/bus/usb/ (yes - not a mistake!) */
1569             strcpy(devpath, USBDEVBUS_PATH);
1570             usb_fs_type = USB_FS_SYS;
1571             closedir(dir);
1572             DPRINTF(USBDBG_DEVOPENED, USBSYSBUS_PATH);
1573             goto found_devices;
1574         }
1575         f = fopen(USBPROCBUS_PATH "/devices", "r");
1576         if (f) {
1577             /* devices found in /proc/bus/usb/ */
1578             strcpy(devpath, USBPROCBUS_PATH);
1579             usb_fs_type = USB_FS_PROC;
1580             fclose(f);
1581             DPRINTF(USBDBG_DEVOPENED, USBPROCBUS_PATH);
1582             goto found_devices;
1583         }
1584         /* try additional methods if an access method hasn't been found yet */
1585         f = fopen(USBDEVBUS_PATH "/devices", "r");
1586         if (f) {
1587             /* devices found in /dev/bus/usb/ */
1588             strcpy(devpath, USBDEVBUS_PATH);
1589             usb_fs_type = USB_FS_DEV;
1590             fclose(f);
1591             DPRINTF(USBDBG_DEVOPENED, USBDEVBUS_PATH);
1592             goto found_devices;
1593         }
1594     found_devices:
1595         if (!usb_fs_type) {
1596             if (mon) {
1597                 monitor_printf(mon, "husb: unable to access USB devices\n");
1598             }
1599             return -ENOENT;
1600         }
1601
1602         /* the module setting (used later for opening devices) */
1603         usb_host_device_path = qemu_mallocz(strlen(devpath)+1);
1604         strcpy(usb_host_device_path, devpath);
1605         if (mon) {
1606             monitor_printf(mon, "husb: using %s file-system with %s\n",
1607                            fs_type[usb_fs_type], usb_host_device_path);
1608         }
1609     }
1610
1611     switch (usb_fs_type) {
1612     case USB_FS_PROC:
1613     case USB_FS_DEV:
1614         ret = usb_host_scan_dev(opaque, func);
1615         break;
1616     case USB_FS_SYS:
1617         ret = usb_host_scan_sys(opaque, func);
1618         break;
1619     default:
1620         ret = -EINVAL;
1621         break;
1622     }
1623     return ret;
1624 }
1625
1626 static QEMUTimer *usb_auto_timer;
1627
1628 static int usb_host_auto_scan(void *opaque, int bus_num, int addr, char *port,
1629                               int class_id, int vendor_id, int product_id,
1630                               const char *product_name, int speed)
1631 {
1632     struct USBAutoFilter *f;
1633     struct USBHostDevice *s;
1634
1635     /* Ignore hubs */
1636     if (class_id == 9)
1637         return 0;
1638
1639     QTAILQ_FOREACH(s, &hostdevs, next) {
1640         f = &s->match;
1641
1642         if (f->bus_num > 0 && f->bus_num != bus_num) {
1643             continue;
1644         }
1645         if (f->addr > 0 && f->addr != addr) {
1646             continue;
1647         }
1648         if (f->port != NULL && (port == NULL || strcmp(f->port, port) != 0)) {
1649             continue;
1650         }
1651
1652         if (f->vendor_id > 0 && f->vendor_id != vendor_id) {
1653             continue;
1654         }
1655
1656         if (f->product_id > 0 && f->product_id != product_id) {
1657             continue;
1658         }
1659         /* We got a match */
1660
1661         /* Already attached ? */
1662         if (s->fd != -1) {
1663             return 0;
1664         }
1665         DPRINTF("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1666
1667         usb_host_open(s, bus_num, addr, port, product_name, speed);
1668     }
1669
1670     return 0;
1671 }
1672
1673 static void usb_host_auto_check(void *unused)
1674 {
1675     struct USBHostDevice *s;
1676     int unconnected = 0;
1677
1678     usb_host_scan(NULL, usb_host_auto_scan);
1679
1680     QTAILQ_FOREACH(s, &hostdevs, next) {
1681         if (s->fd == -1) {
1682             unconnected++;
1683         }
1684     }
1685
1686     if (unconnected == 0) {
1687         /* nothing to watch */
1688         if (usb_auto_timer) {
1689             qemu_del_timer(usb_auto_timer);
1690         }
1691         return;
1692     }
1693
1694     if (!usb_auto_timer) {
1695         usb_auto_timer = qemu_new_timer_ms(rt_clock, usb_host_auto_check, NULL);
1696         if (!usb_auto_timer) {
1697             return;
1698         }
1699     }
1700     qemu_mod_timer(usb_auto_timer, qemu_get_clock_ms(rt_clock) + 2000);
1701 }
1702
1703 /*
1704  * Autoconnect filter
1705  * Format:
1706  *    auto:bus:dev[:vid:pid]
1707  *    auto:bus.dev[:vid:pid]
1708  *
1709  *    bus  - bus number    (dec, * means any)
1710  *    dev  - device number (dec, * means any)
1711  *    vid  - vendor id     (hex, * means any)
1712  *    pid  - product id    (hex, * means any)
1713  *
1714  *    See 'lsusb' output.
1715  */
1716 static int parse_filter(const char *spec, struct USBAutoFilter *f)
1717 {
1718     enum { BUS, DEV, VID, PID, DONE };
1719     const char *p = spec;
1720     int i;
1721
1722     f->bus_num    = 0;
1723     f->addr       = 0;
1724     f->vendor_id  = 0;
1725     f->product_id = 0;
1726
1727     for (i = BUS; i < DONE; i++) {
1728         p = strpbrk(p, ":.");
1729         if (!p) {
1730             break;
1731         }
1732         p++;
1733
1734         if (*p == '*') {
1735             continue;
1736         }
1737         switch(i) {
1738         case BUS: f->bus_num = strtol(p, NULL, 10);    break;
1739         case DEV: f->addr    = strtol(p, NULL, 10);    break;
1740         case VID: f->vendor_id  = strtol(p, NULL, 16); break;
1741         case PID: f->product_id = strtol(p, NULL, 16); break;
1742         }
1743     }
1744
1745     if (i < DEV) {
1746         fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1747         return -1;
1748     }
1749
1750     return 0;
1751 }
1752
1753 /**********************/
1754 /* USB host device info */
1755
1756 struct usb_class_info {
1757     int class;
1758     const char *class_name;
1759 };
1760
1761 static const struct usb_class_info usb_class_info[] = {
1762     { USB_CLASS_AUDIO, "Audio"},
1763     { USB_CLASS_COMM, "Communication"},
1764     { USB_CLASS_HID, "HID"},
1765     { USB_CLASS_HUB, "Hub" },
1766     { USB_CLASS_PHYSICAL, "Physical" },
1767     { USB_CLASS_PRINTER, "Printer" },
1768     { USB_CLASS_MASS_STORAGE, "Storage" },
1769     { USB_CLASS_CDC_DATA, "Data" },
1770     { USB_CLASS_APP_SPEC, "Application Specific" },
1771     { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1772     { USB_CLASS_STILL_IMAGE, "Still Image" },
1773     { USB_CLASS_CSCID, "Smart Card" },
1774     { USB_CLASS_CONTENT_SEC, "Content Security" },
1775     { -1, NULL }
1776 };
1777
1778 static const char *usb_class_str(uint8_t class)
1779 {
1780     const struct usb_class_info *p;
1781     for(p = usb_class_info; p->class != -1; p++) {
1782         if (p->class == class) {
1783             break;
1784         }
1785     }
1786     return p->class_name;
1787 }
1788
1789 static void usb_info_device(Monitor *mon, int bus_num, int addr, char *port,
1790                             int class_id, int vendor_id, int product_id,
1791                             const char *product_name,
1792                             int speed)
1793 {
1794     const char *class_str, *speed_str;
1795
1796     switch(speed) {
1797     case USB_SPEED_LOW:
1798         speed_str = "1.5";
1799         break;
1800     case USB_SPEED_FULL:
1801         speed_str = "12";
1802         break;
1803     case USB_SPEED_HIGH:
1804         speed_str = "480";
1805         break;
1806     case USB_SPEED_SUPER:
1807         speed_str = "5000";
1808         break;
1809     default:
1810         speed_str = "?";
1811         break;
1812     }
1813
1814     monitor_printf(mon, "  Bus %d, Addr %d, Port %s, Speed %s Mb/s\n",
1815                    bus_num, addr, port, speed_str);
1816     class_str = usb_class_str(class_id);
1817     if (class_str) {
1818         monitor_printf(mon, "    %s:", class_str);
1819     } else {
1820         monitor_printf(mon, "    Class %02x:", class_id);
1821     }
1822     monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1823     if (product_name[0] != '\0') {
1824         monitor_printf(mon, ", %s", product_name);
1825     }
1826     monitor_printf(mon, "\n");
1827 }
1828
1829 static int usb_host_info_device(void *opaque, int bus_num, int addr,
1830                                 char *path, int class_id,
1831                                 int vendor_id, int product_id,
1832                                 const char *product_name,
1833                                 int speed)
1834 {
1835     Monitor *mon = opaque;
1836
1837     usb_info_device(mon, bus_num, addr, path, class_id, vendor_id, product_id,
1838                     product_name, speed);
1839     return 0;
1840 }
1841
1842 static void dec2str(int val, char *str, size_t size)
1843 {
1844     if (val == 0) {
1845         snprintf(str, size, "*");
1846     } else {
1847         snprintf(str, size, "%d", val);
1848     }
1849 }
1850
1851 static void hex2str(int val, char *str, size_t size)
1852 {
1853     if (val == 0) {
1854         snprintf(str, size, "*");
1855     } else {
1856         snprintf(str, size, "%04x", val);
1857     }
1858 }
1859
1860 void usb_host_info(Monitor *mon)
1861 {
1862     struct USBAutoFilter *f;
1863     struct USBHostDevice *s;
1864
1865     usb_host_scan(mon, usb_host_info_device);
1866
1867     if (QTAILQ_EMPTY(&hostdevs)) {
1868         return;
1869     }
1870
1871     monitor_printf(mon, "  Auto filters:\n");
1872     QTAILQ_FOREACH(s, &hostdevs, next) {
1873         char bus[10], addr[10], vid[10], pid[10];
1874         f = &s->match;
1875         dec2str(f->bus_num, bus, sizeof(bus));
1876         dec2str(f->addr, addr, sizeof(addr));
1877         hex2str(f->vendor_id, vid, sizeof(vid));
1878         hex2str(f->product_id, pid, sizeof(pid));
1879         monitor_printf(mon, "    Bus %s, Addr %s, Port %s, ID %s:%s\n",
1880                        bus, addr, f->port ? f->port : "*", vid, pid);
1881     }
1882 }