]> git.proxmox.com Git - qemu.git/blame - usb-linux.c
husb: Make control transactions asynchronous (Max Krasnyansky)
[qemu.git] / usb-linux.c
CommitLineData
bb36d470
FB
1/*
2 * Linux host USB redirector
3 *
4 * Copyright (c) 2005 Fabrice Bellard
5fafdf24 5 *
64838171
AL
6 * Copyright (c) 2008 Max Krasnyansky
7 * Support for host device auto connect & disconnect
8 * Magor rewrite to support fully async operation
4b096fc9 9 *
bb36d470
FB
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 */
446ab128 28
87ecb68b 29#include "qemu-common.h"
1f3870ab 30#include "qemu-timer.h"
87ecb68b 31#include "console.h"
bb36d470
FB
32
33#if defined(__linux__)
34#include <dirent.h>
35#include <sys/ioctl.h>
b9dc033c 36#include <signal.h>
bb36d470 37
446ab128
AL
38#include <linux/usb/ch9.h>
39#include <linux/usbdevice_fs.h>
40#include <linux/version.h>
41#include "hw/usb.h"
bb36d470 42
a594cfbf 43typedef int USBScanFunc(void *opaque, int bus_num, int addr, int class_id,
5fafdf24 44 int vendor_id, int product_id,
a594cfbf 45 const char *product_name, int speed);
5fafdf24 46static int usb_host_find_device(int *pbus_num, int *paddr,
1f6e24e7 47 char *product_name, int product_name_size,
a594cfbf 48 const char *devname);
a594cfbf 49//#define DEBUG
64838171
AL
50
51#ifdef DEBUG
52#define dprintf printf
53#else
54#define dprintf(...)
55#endif
bb36d470
FB
56
57#define USBDEVFS_PATH "/proc/bus/usb"
1f6e24e7 58#define PRODUCT_NAME_SZ 32
b9dc033c 59#define MAX_ENDPOINTS 16
bb36d470 60
b9dc033c
AZ
61/* endpoint association data */
62struct endp_data {
63 uint8_t type;
64838171 64 uint8_t halted;
b9dc033c
AZ
65};
66
446ab128
AL
67enum {
68 CTRL_STATE_IDLE = 0,
69 CTRL_STATE_SETUP,
70 CTRL_STATE_DATA,
71 CTRL_STATE_ACK
72};
73
74/*
75 * Control transfer state.
76 * Note that 'buffer' _must_ follow 'req' field because
77 * we need contigious buffer when we submit control URB.
78 */
79struct ctrl_struct {
80 uint16_t len;
81 uint16_t offset;
82 uint8_t state;
83 struct usb_ctrlrequest req;
84 uint8_t buffer[1024];
85};
86
bb36d470
FB
87typedef struct USBHostDevice {
88 USBDevice dev;
64838171
AL
89 int fd;
90
91 uint8_t descr[1024];
92 int descr_len;
93 int configuration;
446ab128 94 int ninterfaces;
24772c1e 95 int closing;
64838171 96
446ab128 97 struct ctrl_struct ctrl;
b9dc033c 98 struct endp_data endp_table[MAX_ENDPOINTS];
4b096fc9 99
4b096fc9
AL
100 /* Host side address */
101 int bus_num;
102 int addr;
103
104 struct USBHostDevice *next;
bb36d470
FB
105} USBHostDevice;
106
64838171
AL
107static int is_isoc(USBHostDevice *s, int ep)
108{
109 return s->endp_table[ep - 1].type == USBDEVFS_URB_TYPE_ISO;
110}
111
112static int is_halted(USBHostDevice *s, int ep)
113{
114 return s->endp_table[ep - 1].halted;
115}
116
117static void clear_halt(USBHostDevice *s, int ep)
118{
119 s->endp_table[ep - 1].halted = 0;
120}
121
122static void set_halt(USBHostDevice *s, int ep)
123{
124 s->endp_table[ep - 1].halted = 1;
125}
126
4b096fc9
AL
127static USBHostDevice *hostdev_list;
128
129static void hostdev_link(USBHostDevice *dev)
130{
131 dev->next = hostdev_list;
132 hostdev_list = dev;
133}
134
135static void hostdev_unlink(USBHostDevice *dev)
136{
137 USBHostDevice *pdev = hostdev_list;
138 USBHostDevice **prev = &hostdev_list;
139
140 while (pdev) {
141 if (pdev == dev) {
142 *prev = dev->next;
143 return;
144 }
145
146 prev = &pdev->next;
147 pdev = pdev->next;
148 }
149}
150
151static USBHostDevice *hostdev_find(int bus_num, int addr)
152{
153 USBHostDevice *s = hostdev_list;
154 while (s) {
155 if (s->bus_num == bus_num && s->addr == addr)
156 return s;
157 s = s->next;
158 }
159 return NULL;
160}
161
64838171
AL
162/*
163 * Async URB state.
164 * We always allocate one isoc descriptor even for bulk transfers
165 * to simplify allocation and casts.
166 */
167typedef struct AsyncURB
168{
169 struct usbdevfs_urb urb;
170 struct usbdevfs_iso_packet_desc isocpd;
b9dc033c 171
64838171
AL
172 USBPacket *packet;
173 USBHostDevice *hdev;
174} AsyncURB;
b9dc033c 175
64838171 176static AsyncURB *async_alloc(void)
b9dc033c 177{
64838171 178 return (AsyncURB *) qemu_mallocz(sizeof(AsyncURB));
b9dc033c
AZ
179}
180
64838171 181static void async_free(AsyncURB *aurb)
b9dc033c 182{
64838171
AL
183 qemu_free(aurb);
184}
b9dc033c 185
446ab128
AL
186static void async_complete_ctrl(USBHostDevice *s, USBPacket *p)
187{
188 switch(s->ctrl.state) {
189 case CTRL_STATE_SETUP:
190 if (p->len < s->ctrl.len)
191 s->ctrl.len = p->len;
192 s->ctrl.state = CTRL_STATE_DATA;
193 p->len = 8;
194 break;
195
196 case CTRL_STATE_ACK:
197 s->ctrl.state = CTRL_STATE_IDLE;
198 p->len = 0;
199 break;
200
201 default:
202 break;
203 }
204}
205
64838171
AL
206static void async_complete(void *opaque)
207{
208 USBHostDevice *s = opaque;
209 AsyncURB *aurb;
210
211 while (1) {
212 USBPacket *p;
b9dc033c 213
64838171
AL
214 int r = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &aurb);
215 if (r < 0) {
216 if (errno == EAGAIN)
217 return;
218
24772c1e 219 if (errno == ENODEV && !s->closing) {
64838171
AL
220 printf("husb: device %d.%d disconnected\n", s->bus_num, s->addr);
221 usb_device_del_addr(0, s->dev.addr);
222 return;
223 }
224
225 dprintf("husb: async. reap urb failed errno %d\n", errno);
226 return;
b9dc033c 227 }
64838171
AL
228
229 p = aurb->packet;
230
231 dprintf("husb: async completed. aurb %p status %d alen %d\n",
232 aurb, aurb->urb.status, aurb->urb.actual_length);
233
234 if (p) {
235 switch (aurb->urb.status) {
236 case 0:
237 p->len = aurb->urb.actual_length;
446ab128
AL
238 if (aurb->urb.type == USBDEVFS_URB_TYPE_CONTROL)
239 async_complete_ctrl(s, p);
64838171
AL
240 break;
241
242 case -EPIPE:
243 set_halt(s, p->devep);
244 /* fall through */
245 default:
246 p->len = USB_RET_NAK;
247 break;
248 }
249
250 usb_packet_complete(p);
251 }
252
253 async_free(aurb);
b9dc033c 254 }
b9dc033c
AZ
255}
256
64838171 257static void async_cancel(USBPacket *unused, void *opaque)
b9dc033c 258{
64838171
AL
259 AsyncURB *aurb = opaque;
260 USBHostDevice *s = aurb->hdev;
b9dc033c 261
64838171
AL
262 dprintf("husb: async cancel. aurb %p\n", aurb);
263
264 /* Mark it as dead (see async_complete above) */
265 aurb->packet = NULL;
b9dc033c 266
64838171
AL
267 int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
268 if (r < 0) {
269 dprintf("husb: async. discard urb failed errno %d\n", errno);
b9dc033c 270 }
b9dc033c
AZ
271}
272
446ab128 273static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
b9dc033c
AZ
274{
275 int dev_descr_len, config_descr_len;
276 int interface, nb_interfaces, nb_configurations;
277 int ret, i;
278
279 if (configuration == 0) /* address state - ignore */
280 return 1;
281
446ab128
AL
282 dprintf("husb: claiming interfaces. config %d\n", configuration);
283
b9dc033c
AZ
284 i = 0;
285 dev_descr_len = dev->descr[0];
286 if (dev_descr_len > dev->descr_len)
287 goto fail;
288 nb_configurations = dev->descr[17];
289
290 i += dev_descr_len;
291 while (i < dev->descr_len) {
64838171 292 dprintf("husb: i is %d, descr_len is %d, dl %d, dt %d\n", i, dev->descr_len,
b9dc033c 293 dev->descr[i], dev->descr[i+1]);
64838171 294
b9dc033c
AZ
295 if (dev->descr[i+1] != USB_DT_CONFIG) {
296 i += dev->descr[i];
297 continue;
298 }
299 config_descr_len = dev->descr[i];
300
64838171 301 printf("husb: config #%d need %d\n", dev->descr[i + 5], configuration);
1f3870ab 302
446ab128
AL
303 if (configuration < 0 || configuration == dev->descr[i + 5]) {
304 configuration = dev->descr[i + 5];
b9dc033c 305 break;
446ab128 306 }
b9dc033c
AZ
307
308 i += config_descr_len;
309 }
310
311 if (i >= dev->descr_len) {
0d380648 312 fprintf(stderr, "husb: update iface failed. no matching configuration\n");
b9dc033c
AZ
313 goto fail;
314 }
315 nb_interfaces = dev->descr[i + 4];
316
317#ifdef USBDEVFS_DISCONNECT
318 /* earlier Linux 2.4 do not support that */
319 {
320 struct usbdevfs_ioctl ctrl;
321 for (interface = 0; interface < nb_interfaces; interface++) {
322 ctrl.ioctl_code = USBDEVFS_DISCONNECT;
323 ctrl.ifno = interface;
324 ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
325 if (ret < 0 && errno != ENODATA) {
326 perror("USBDEVFS_DISCONNECT");
327 goto fail;
328 }
329 }
330 }
331#endif
332
333 /* XXX: only grab if all interfaces are free */
334 for (interface = 0; interface < nb_interfaces; interface++) {
335 ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
336 if (ret < 0) {
337 if (errno == EBUSY) {
64838171 338 printf("husb: update iface. device already grabbed\n");
b9dc033c 339 } else {
64838171 340 perror("husb: failed to claim interface");
b9dc033c
AZ
341 }
342 fail:
343 return 0;
344 }
345 }
346
64838171 347 printf("husb: %d interfaces claimed for configuration %d\n",
b9dc033c 348 nb_interfaces, configuration);
b9dc033c 349
446ab128
AL
350 dev->ninterfaces = nb_interfaces;
351 dev->configuration = configuration;
352 return 1;
353}
354
355static int usb_host_release_interfaces(USBHostDevice *s)
356{
357 int ret, i;
358
359 dprintf("husb: releasing interfaces\n");
360
361 for (i = 0; i < s->ninterfaces; i++) {
362 ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
363 if (ret < 0) {
364 perror("husb: failed to release interface");
365 return 0;
366 }
367 }
368
b9dc033c
AZ
369 return 1;
370}
371
059809e4 372static void usb_host_handle_reset(USBDevice *dev)
bb36d470 373{
446ab128 374 USBHostDevice *s = (USBHostDevice *) dev;
64838171
AL
375
376 dprintf("husb: reset device %u.%u\n", s->bus_num, s->addr);
377
bb36d470 378 ioctl(s->fd, USBDEVFS_RESET);
446ab128
AL
379
380 usb_host_claim_interfaces(s, s->configuration);
5fafdf24 381}
bb36d470 382
059809e4
FB
383static void usb_host_handle_destroy(USBDevice *dev)
384{
385 USBHostDevice *s = (USBHostDevice *)dev;
386
24772c1e
AL
387 s->closing = 1;
388
64838171 389 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1f3870ab 390
4b096fc9
AL
391 hostdev_unlink(s);
392
64838171
AL
393 async_complete(s);
394
059809e4
FB
395 if (s->fd >= 0)
396 close(s->fd);
1f3870ab 397
059809e4
FB
398 qemu_free(s);
399}
400
b9dc033c
AZ
401static int usb_linux_update_endp_table(USBHostDevice *s);
402
446ab128 403static int usb_host_handle_data(USBHostDevice *s, USBPacket *p)
bb36d470 404{
64838171 405 struct usbdevfs_urb *urb;
446ab128 406 AsyncURB *aurb;
bb36d470
FB
407 int ret;
408
64838171
AL
409 aurb = async_alloc();
410 if (!aurb) {
411 dprintf("husb: async malloc failed\n");
412 return USB_RET_NAK;
b9dc033c 413 }
64838171
AL
414 aurb->hdev = s;
415 aurb->packet = p;
416
417 urb = &aurb->urb;
b9dc033c 418
4d611c9a 419 if (p->pid == USB_TOKEN_IN)
64838171
AL
420 urb->endpoint = p->devep | 0x80;
421 else
422 urb->endpoint = p->devep;
423
424 if (is_halted(s, p->devep)) {
425 ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &urb->endpoint);
426 if (ret < 0) {
427 dprintf("husb: failed to clear halt. ep 0x%x errno %d\n",
428 urb->endpoint, errno);
bb36d470 429 return USB_RET_NAK;
bb36d470 430 }
64838171 431 clear_halt(s, p->devep);
4d043a09
AZ
432 }
433
64838171
AL
434 urb->buffer = p->data;
435 urb->buffer_length = p->len;
b9dc033c 436
64838171
AL
437 if (is_isoc(s, p->devep)) {
438 /* Setup ISOC transfer */
439 urb->type = USBDEVFS_URB_TYPE_ISO;
440 urb->flags = USBDEVFS_URB_ISO_ASAP;
441 urb->number_of_packets = 1;
442 urb->iso_frame_desc[0].length = p->len;
443 } else {
444 /* Setup bulk transfer */
445 urb->type = USBDEVFS_URB_TYPE_BULK;
b9dc033c
AZ
446 }
447
64838171 448 urb->usercontext = s;
b9dc033c 449
64838171 450 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
b9dc033c 451
64838171 452 dprintf("husb: data submit. ep 0x%x len %u aurb %p\n", urb->endpoint, p->len, aurb);
b9dc033c 453
64838171
AL
454 if (ret < 0) {
455 dprintf("husb: submit failed. errno %d\n", errno);
456 async_free(aurb);
b9dc033c 457
b9dc033c
AZ
458 switch(errno) {
459 case ETIMEDOUT:
460 return USB_RET_NAK;
461 case EPIPE:
462 default:
463 return USB_RET_STALL;
464 }
465 }
64838171
AL
466
467 usb_defer_packet(p, async_cancel, aurb);
b9dc033c 468 return USB_RET_ASYNC;
b9dc033c
AZ
469}
470
446ab128
AL
471static int ctrl_error(void)
472{
473 if (errno == ETIMEDOUT)
474 return USB_RET_NAK;
475 else
476 return USB_RET_STALL;
477}
478
479static int usb_host_set_address(USBHostDevice *s, int addr)
480{
481 dprintf("husb: ctrl set addr %u\n", addr);
482 s->dev.addr = addr;
483 return 0;
484}
485
486static int usb_host_set_config(USBHostDevice *s, int config)
487{
488 usb_host_release_interfaces(s);
489
490 int ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
491
492 dprintf("husb: ctrl set config %d ret %d errno %d\n", config, ret, errno);
493
494 if (ret < 0)
495 return ctrl_error();
496
497 usb_host_claim_interfaces(s, config);
498 return 0;
499}
500
501static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
502{
503 struct usbdevfs_setinterface si;
504 int ret;
505
506 si.interface = iface;
507 si.altsetting = alt;
508 ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
509
510 dprintf("husb: ctrl set iface %d altset %d ret %d errno %d\n",
511 iface, alt, ret, errno);
512
513 if (ret < 0)
514 return ctrl_error();
515
516 usb_linux_update_endp_table(s);
517 return 0;
518}
519
520static int usb_host_handle_control(USBHostDevice *s, USBPacket *p)
521{
522 struct usbdevfs_urb *urb;
523 AsyncURB *aurb;
524 int ret, value, index;
525
526 /*
527 * Process certain standard device requests.
528 * These are infrequent and are processed synchronously.
529 */
530 value = le16_to_cpu(s->ctrl.req.wValue);
531 index = le16_to_cpu(s->ctrl.req.wIndex);
532
533 dprintf("husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\n",
534 s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index,
535 s->ctrl.len);
536
537 if (s->ctrl.req.bRequestType == 0) {
538 switch (s->ctrl.req.bRequest) {
539 case USB_REQ_SET_ADDRESS:
540 return usb_host_set_address(s, value);
541
542 case USB_REQ_SET_CONFIGURATION:
543 return usb_host_set_config(s, value & 0xff);
544 }
545 }
546
547 if (s->ctrl.req.bRequestType == 1 &&
548 s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE)
549 return usb_host_set_interface(s, index, value);
550
551 /* The rest are asynchronous */
552
553 aurb = async_alloc();
554 if (!aurb) {
555 dprintf("husb: async malloc failed\n");
556 return USB_RET_NAK;
557 }
558 aurb->hdev = s;
559 aurb->packet = p;
560
561 /*
562 * Setup ctrl transfer.
563 *
564 * s->ctrl is layed out such that data buffer immediately follows
565 * 'req' struct which is exactly what usbdevfs expects.
566 */
567 urb = &aurb->urb;
568
569 urb->type = USBDEVFS_URB_TYPE_CONTROL;
570 urb->endpoint = p->devep;
571
572 urb->buffer = &s->ctrl.req;
573 urb->buffer_length = 8 + s->ctrl.len;
574
575 urb->usercontext = s;
576
577 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
578
579 dprintf("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb);
580
581 if (ret < 0) {
582 dprintf("husb: submit failed. errno %d\n", errno);
583 async_free(aurb);
584
585 switch(errno) {
586 case ETIMEDOUT:
587 return USB_RET_NAK;
588 case EPIPE:
589 default:
590 return USB_RET_STALL;
591 }
592 }
593
594 usb_defer_packet(p, async_cancel, aurb);
595 return USB_RET_ASYNC;
596}
597
598static int do_token_setup(USBDevice *dev, USBPacket *p)
599{
600 USBHostDevice *s = (USBHostDevice *) dev;
601 int ret = 0;
602
603 if (p->len != 8)
604 return USB_RET_STALL;
605
606 memcpy(&s->ctrl.req, p->data, 8);
607 s->ctrl.len = le16_to_cpu(s->ctrl.req.wLength);
608 s->ctrl.offset = 0;
609 s->ctrl.state = CTRL_STATE_SETUP;
610
611 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
612 ret = usb_host_handle_control(s, p);
613 if (ret < 0)
614 return ret;
615
616 if (ret < s->ctrl.len)
617 s->ctrl.len = ret;
618 s->ctrl.state = CTRL_STATE_DATA;
619 } else {
620 if (s->ctrl.len == 0)
621 s->ctrl.state = CTRL_STATE_ACK;
622 else
623 s->ctrl.state = CTRL_STATE_DATA;
624 }
625
626 return ret;
627}
628
629static int do_token_in(USBDevice *dev, USBPacket *p)
630{
631 USBHostDevice *s = (USBHostDevice *) dev;
632 int ret = 0;
633
634 if (p->devep != 0)
635 return usb_host_handle_data(s, p);
636
637 switch(s->ctrl.state) {
638 case CTRL_STATE_ACK:
639 if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
640 ret = usb_host_handle_control(s, p);
641 if (ret == USB_RET_ASYNC)
642 return USB_RET_ASYNC;
643
644 s->ctrl.state = CTRL_STATE_IDLE;
645 return ret > 0 ? 0 : ret;
646 }
647
648 return 0;
649
650 case CTRL_STATE_DATA:
651 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
652 int len = s->ctrl.len - s->ctrl.offset;
653 if (len > p->len)
654 len = p->len;
655 memcpy(p->data, s->ctrl.buffer + s->ctrl.offset, len);
656 s->ctrl.offset += len;
657 if (s->ctrl.offset >= s->ctrl.len)
658 s->ctrl.state = CTRL_STATE_ACK;
659 return len;
660 }
661
662 s->ctrl.state = CTRL_STATE_IDLE;
663 return USB_RET_STALL;
664
665 default:
666 return USB_RET_STALL;
667 }
668}
669
670static int do_token_out(USBDevice *dev, USBPacket *p)
671{
672 USBHostDevice *s = (USBHostDevice *) dev;
673
674 if (p->devep != 0)
675 return usb_host_handle_data(s, p);
676
677 switch(s->ctrl.state) {
678 case CTRL_STATE_ACK:
679 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
680 s->ctrl.state = CTRL_STATE_IDLE;
681 /* transfer OK */
682 } else {
683 /* ignore additional output */
684 }
685 return 0;
686
687 case CTRL_STATE_DATA:
688 if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
689 int len = s->ctrl.len - s->ctrl.offset;
690 if (len > p->len)
691 len = p->len;
692 memcpy(s->ctrl.buffer + s->ctrl.offset, p->data, len);
693 s->ctrl.offset += len;
694 if (s->ctrl.offset >= s->ctrl.len)
695 s->ctrl.state = CTRL_STATE_ACK;
696 return len;
697 }
698
699 s->ctrl.state = CTRL_STATE_IDLE;
700 return USB_RET_STALL;
701
702 default:
703 return USB_RET_STALL;
704 }
705}
706
707/*
708 * Packet handler.
709 * Called by the HC (host controller).
710 *
711 * Returns length of the transaction or one of the USB_RET_XXX codes.
712 */
713int usb_host_handle_packet(USBDevice *s, USBPacket *p)
714{
715 switch(p->pid) {
716 case USB_MSG_ATTACH:
717 s->state = USB_STATE_ATTACHED;
718 return 0;
719
720 case USB_MSG_DETACH:
721 s->state = USB_STATE_NOTATTACHED;
722 return 0;
723
724 case USB_MSG_RESET:
725 s->remote_wakeup = 0;
726 s->addr = 0;
727 s->state = USB_STATE_DEFAULT;
728 s->handle_reset(s);
729 return 0;
730 }
731
732 /* Rest of the PIDs must match our address */
733 if (s->state < USB_STATE_DEFAULT || p->devaddr != s->addr)
734 return USB_RET_NODEV;
735
736 switch (p->pid) {
737 case USB_TOKEN_SETUP:
738 return do_token_setup(s, p);
739
740 case USB_TOKEN_IN:
741 return do_token_in(s, p);
742
743 case USB_TOKEN_OUT:
744 return do_token_out(s, p);
745
746 default:
747 return USB_RET_STALL;
748 }
749}
750
b9dc033c
AZ
751/* returns 1 on problem encountered or 0 for success */
752static int usb_linux_update_endp_table(USBHostDevice *s)
753{
754 uint8_t *descriptors;
755 uint8_t devep, type, configuration, alt_interface;
446ab128 756 struct usbdevfs_ctrltransfer ct;
b9dc033c
AZ
757 int interface, ret, length, i;
758
759 ct.bRequestType = USB_DIR_IN;
760 ct.bRequest = USB_REQ_GET_CONFIGURATION;
761 ct.wValue = 0;
762 ct.wIndex = 0;
763 ct.wLength = 1;
764 ct.data = &configuration;
765 ct.timeout = 50;
766
767 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
768 if (ret < 0) {
769 perror("usb_linux_update_endp_table");
770 return 1;
771 }
772
773 /* in address state */
774 if (configuration == 0)
775 return 1;
776
777 /* get the desired configuration, interface, and endpoint descriptors
778 * from device description */
779 descriptors = &s->descr[18];
780 length = s->descr_len - 18;
781 i = 0;
782
783 if (descriptors[i + 1] != USB_DT_CONFIG ||
784 descriptors[i + 5] != configuration) {
64838171 785 dprintf("invalid descriptor data - configuration\n");
b9dc033c
AZ
786 return 1;
787 }
788 i += descriptors[i];
789
790 while (i < length) {
791 if (descriptors[i + 1] != USB_DT_INTERFACE ||
792 (descriptors[i + 1] == USB_DT_INTERFACE &&
793 descriptors[i + 4] == 0)) {
794 i += descriptors[i];
795 continue;
796 }
797
798 interface = descriptors[i + 2];
799
800 ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
801 ct.bRequest = USB_REQ_GET_INTERFACE;
802 ct.wValue = 0;
803 ct.wIndex = interface;
804 ct.wLength = 1;
805 ct.data = &alt_interface;
806 ct.timeout = 50;
807
808 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
809 if (ret < 0) {
810 perror("usb_linux_update_endp_table");
811 return 1;
812 }
813
814 /* the current interface descriptor is the active interface
815 * and has endpoints */
816 if (descriptors[i + 3] != alt_interface) {
817 i += descriptors[i];
818 continue;
819 }
820
821 /* advance to the endpoints */
822 while (i < length && descriptors[i +1] != USB_DT_ENDPOINT)
823 i += descriptors[i];
824
825 if (i >= length)
826 break;
827
828 while (i < length) {
829 if (descriptors[i + 1] != USB_DT_ENDPOINT)
830 break;
831
832 devep = descriptors[i + 2];
833 switch (descriptors[i + 3] & 0x3) {
834 case 0x00:
835 type = USBDEVFS_URB_TYPE_CONTROL;
836 break;
837 case 0x01:
838 type = USBDEVFS_URB_TYPE_ISO;
839 break;
840 case 0x02:
841 type = USBDEVFS_URB_TYPE_BULK;
842 break;
843 case 0x03:
844 type = USBDEVFS_URB_TYPE_INTERRUPT;
845 break;
846 default:
64838171 847 dprintf("usb_host: malformed endpoint type\n");
b9dc033c
AZ
848 type = USBDEVFS_URB_TYPE_BULK;
849 }
850 s->endp_table[(devep & 0xf) - 1].type = type;
64838171 851 s->endp_table[(devep & 0xf) - 1].halted = 0;
b9dc033c
AZ
852
853 i += descriptors[i];
854 }
855 }
856 return 0;
857}
858
4b096fc9 859static USBDevice *usb_host_device_open_addr(int bus_num, int addr, const char *prod_name)
bb36d470 860{
b9dc033c
AZ
861 int fd = -1, ret;
862 USBHostDevice *dev = NULL;
bb36d470 863 struct usbdevfs_connectinfo ci;
a594cfbf 864 char buf[1024];
1f3870ab 865
b9dc033c
AZ
866 dev = qemu_mallocz(sizeof(USBHostDevice));
867 if (!dev)
868 goto fail;
869
4b096fc9
AL
870 dev->bus_num = bus_num;
871 dev->addr = addr;
872
64838171 873 printf("husb: open device %d.%d\n", bus_num, addr);
3b46e624 874
5fafdf24 875 snprintf(buf, sizeof(buf), USBDEVFS_PATH "/%03d/%03d",
a594cfbf 876 bus_num, addr);
b9dc033c 877 fd = open(buf, O_RDWR | O_NONBLOCK);
bb36d470 878 if (fd < 0) {
a594cfbf 879 perror(buf);
1f3870ab 880 goto fail;
bb36d470
FB
881 }
882
b9dc033c
AZ
883 /* read the device description */
884 dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
885 if (dev->descr_len <= 0) {
64838171 886 perror("husb: reading device data failed");
bb36d470
FB
887 goto fail;
888 }
3b46e624 889
b9dc033c 890#ifdef DEBUG
868bfe2b 891 {
b9dc033c
AZ
892 int x;
893 printf("=== begin dumping device descriptor data ===\n");
894 for (x = 0; x < dev->descr_len; x++)
895 printf("%02x ", dev->descr[x]);
896 printf("\n=== end dumping device descriptor data ===\n");
bb36d470 897 }
a594cfbf
FB
898#endif
899
b9dc033c 900 dev->fd = fd;
b9dc033c 901
446ab128
AL
902 /*
903 * Initial configuration is -1 which makes us claim first
904 * available config. We used to start with 1, which does not
905 * always work. I've seen devices where first config starts
906 * with 2.
907 */
908 if (!usb_host_claim_interfaces(dev, -1))
b9dc033c 909 goto fail;
bb36d470
FB
910
911 ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
912 if (ret < 0) {
046833ea 913 perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
bb36d470
FB
914 goto fail;
915 }
916
64838171 917 printf("husb: grabbed usb device %d.%d\n", bus_num, addr);
bb36d470 918
b9dc033c
AZ
919 ret = usb_linux_update_endp_table(dev);
920 if (ret)
bb36d470 921 goto fail;
b9dc033c 922
bb36d470
FB
923 if (ci.slow)
924 dev->dev.speed = USB_SPEED_LOW;
925 else
926 dev->dev.speed = USB_SPEED_HIGH;
bb36d470 927
446ab128
AL
928 dev->dev.handle_packet = usb_host_handle_packet;
929 dev->dev.handle_reset = usb_host_handle_reset;
059809e4 930 dev->dev.handle_destroy = usb_host_handle_destroy;
1f6e24e7 931
4b096fc9 932 if (!prod_name || prod_name[0] == '\0')
1f6e24e7 933 snprintf(dev->dev.devname, sizeof(dev->dev.devname),
4b096fc9 934 "host:%d.%d", bus_num, addr);
1f6e24e7
FB
935 else
936 pstrcpy(dev->dev.devname, sizeof(dev->dev.devname),
4b096fc9 937 prod_name);
1f6e24e7 938
64838171
AL
939 /* USB devio uses 'write' flag to check for async completions */
940 qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);
1f3870ab 941
4b096fc9
AL
942 hostdev_link(dev);
943
64838171 944 return (USBDevice *) dev;
4b096fc9 945
b9dc033c 946fail:
24772c1e 947 if (dev)
b9dc033c 948 qemu_free(dev);
24772c1e 949
b9dc033c
AZ
950 close(fd);
951 return NULL;
a594cfbf 952}
bb36d470 953
4b096fc9
AL
954USBDevice *usb_host_device_open(const char *devname)
955{
956 int bus_num, addr;
957 char product_name[PRODUCT_NAME_SZ];
958
959 if (usb_host_find_device(&bus_num, &addr,
960 product_name, sizeof(product_name),
961 devname) < 0)
962 return NULL;
963
964 if (hostdev_find(bus_num, addr)) {
64838171 965 term_printf("husb: host usb device %d.%d is already open\n", bus_num, addr);
4b096fc9
AL
966 return NULL;
967 }
968
969 return usb_host_device_open_addr(bus_num, addr, product_name);
970}
971
a594cfbf 972static int get_tag_value(char *buf, int buf_size,
5fafdf24 973 const char *str, const char *tag,
a594cfbf
FB
974 const char *stopchars)
975{
976 const char *p;
977 char *q;
978 p = strstr(str, tag);
979 if (!p)
980 return -1;
981 p += strlen(tag);
982 while (isspace(*p))
983 p++;
984 q = buf;
985 while (*p != '\0' && !strchr(stopchars, *p)) {
986 if ((q - buf) < (buf_size - 1))
987 *q++ = *p;
988 p++;
989 }
990 *q = '\0';
991 return q - buf;
bb36d470
FB
992}
993
a594cfbf 994static int usb_host_scan(void *opaque, USBScanFunc *func)
bb36d470 995{
a594cfbf
FB
996 FILE *f;
997 char line[1024];
bb36d470 998 char buf[1024];
a594cfbf
FB
999 int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
1000 int ret;
1001 char product_name[512];
3b46e624 1002
a594cfbf
FB
1003 f = fopen(USBDEVFS_PATH "/devices", "r");
1004 if (!f) {
64838171 1005 term_printf("husb: could not open %s\n", USBDEVFS_PATH "/devices");
a594cfbf
FB
1006 return 0;
1007 }
1008 device_count = 0;
1009 bus_num = addr = speed = class_id = product_id = vendor_id = 0;
1010 ret = 0;
bb36d470 1011 for(;;) {
a594cfbf 1012 if (fgets(line, sizeof(line), f) == NULL)
bb36d470 1013 break;
a594cfbf
FB
1014 if (strlen(line) > 0)
1015 line[strlen(line) - 1] = '\0';
1016 if (line[0] == 'T' && line[1] == ':') {
38ca0f6d
PB
1017 if (device_count && (vendor_id || product_id)) {
1018 /* New device. Add the previously discovered device. */
5fafdf24 1019 ret = func(opaque, bus_num, addr, class_id, vendor_id,
a594cfbf
FB
1020 product_id, product_name, speed);
1021 if (ret)
1022 goto the_end;
1023 }
1024 if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0)
1025 goto fail;
1026 bus_num = atoi(buf);
1027 if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0)
1028 goto fail;
1029 addr = atoi(buf);
1030 if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0)
1031 goto fail;
1032 if (!strcmp(buf, "480"))
1033 speed = USB_SPEED_HIGH;
1034 else if (!strcmp(buf, "1.5"))
1035 speed = USB_SPEED_LOW;
1036 else
1037 speed = USB_SPEED_FULL;
1038 product_name[0] = '\0';
1039 class_id = 0xff;
1040 device_count++;
1041 product_id = 0;
1042 vendor_id = 0;
1043 } else if (line[0] == 'P' && line[1] == ':') {
1044 if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0)
1045 goto fail;
1046 vendor_id = strtoul(buf, NULL, 16);
1047 if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0)
1048 goto fail;
1049 product_id = strtoul(buf, NULL, 16);
1050 } else if (line[0] == 'S' && line[1] == ':') {
1051 if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0)
1052 goto fail;
1053 pstrcpy(product_name, sizeof(product_name), buf);
1054 } else if (line[0] == 'D' && line[1] == ':') {
1055 if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0)
1056 goto fail;
1057 class_id = strtoul(buf, NULL, 16);
bb36d470 1058 }
a594cfbf
FB
1059 fail: ;
1060 }
38ca0f6d
PB
1061 if (device_count && (vendor_id || product_id)) {
1062 /* Add the last device. */
5fafdf24 1063 ret = func(opaque, bus_num, addr, class_id, vendor_id,
a594cfbf 1064 product_id, product_name, speed);
bb36d470 1065 }
a594cfbf
FB
1066 the_end:
1067 fclose(f);
1068 return ret;
bb36d470
FB
1069}
1070
4b096fc9
AL
1071struct USBAutoFilter {
1072 struct USBAutoFilter *next;
1073 int bus_num;
1074 int addr;
1075 int vendor_id;
1076 int product_id;
1077};
1078
1079static QEMUTimer *usb_auto_timer;
1080static struct USBAutoFilter *usb_auto_filter;
1081
1082static int usb_host_auto_scan(void *opaque, int bus_num, int addr,
1083 int class_id, int vendor_id, int product_id,
1084 const char *product_name, int speed)
1085{
1086 struct USBAutoFilter *f;
1087 struct USBDevice *dev;
1088
1089 /* Ignore hubs */
1090 if (class_id == 9)
1091 return 0;
1092
1093 for (f = usb_auto_filter; f; f = f->next) {
4b096fc9
AL
1094 if (f->bus_num >= 0 && f->bus_num != bus_num)
1095 continue;
1096
1097 if (f->addr >= 0 && f->addr != addr)
1098 continue;
1099
1100 if (f->vendor_id >= 0 && f->vendor_id != vendor_id)
1101 continue;
1102
1103 if (f->product_id >= 0 && f->product_id != product_id)
1104 continue;
1105
1106 /* We got a match */
1107
1108 /* Allredy attached ? */
1109 if (hostdev_find(bus_num, addr))
1110 return 0;
1111
64838171 1112 dprintf("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
4b096fc9
AL
1113
1114 dev = usb_host_device_open_addr(bus_num, addr, product_name);
1115 if (dev)
1116 usb_device_add_dev(dev);
1117 }
1118
1119 return 0;
1120}
1121
1122static void usb_host_auto_timer(void *unused)
1123{
1124 usb_host_scan(NULL, usb_host_auto_scan);
1125 qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000);
1126}
1127
1128/*
1129 * Add autoconnect filter
1130 * -1 means 'any' (device, vendor, etc)
1131 */
1132static void usb_host_auto_add(int bus_num, int addr, int vendor_id, int product_id)
1133{
1134 struct USBAutoFilter *f = qemu_mallocz(sizeof(*f));
1135 if (!f) {
0d380648
AL
1136 fprintf(stderr, "husb: failed to allocate auto filter\n");
1137 return;
4b096fc9
AL
1138 }
1139
1140 f->bus_num = bus_num;
1141 f->addr = addr;
1142 f->vendor_id = vendor_id;
1143 f->product_id = product_id;
1144
1145 if (!usb_auto_filter) {
1146 /*
1147 * First entry. Init and start the monitor.
1148 * Right now we're using timer to check for new devices.
1149 * If this turns out to be too expensive we can move that into a
1150 * separate thread.
1151 */
1152 usb_auto_timer = qemu_new_timer(rt_clock, usb_host_auto_timer, NULL);
1153 if (!usb_auto_timer) {
0d380648 1154 fprintf(stderr, "husb: failed to allocate auto scan timer\n");
4b096fc9
AL
1155 qemu_free(f);
1156 return;
1157 }
1158
1159 /* Check for new devices every two seconds */
1160 qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000);
1161 }
1162
64838171 1163 dprintf("husb: auto filter: bus_num %d addr %d vid %d pid %d\n",
4b096fc9
AL
1164 bus_num, addr, vendor_id, product_id);
1165
1166 f->next = usb_auto_filter;
1167 usb_auto_filter = f;
1168}
1169
a594cfbf
FB
1170typedef struct FindDeviceState {
1171 int vendor_id;
1172 int product_id;
1173 int bus_num;
1174 int addr;
1f6e24e7 1175 char product_name[PRODUCT_NAME_SZ];
a594cfbf
FB
1176} FindDeviceState;
1177
5fafdf24 1178static int usb_host_find_device_scan(void *opaque, int bus_num, int addr,
a594cfbf 1179 int class_id,
5fafdf24 1180 int vendor_id, int product_id,
a594cfbf 1181 const char *product_name, int speed)
bb36d470 1182{
a594cfbf 1183 FindDeviceState *s = opaque;
1f6e24e7
FB
1184 if ((vendor_id == s->vendor_id &&
1185 product_id == s->product_id) ||
1186 (bus_num == s->bus_num &&
1187 addr == s->addr)) {
1188 pstrcpy(s->product_name, PRODUCT_NAME_SZ, product_name);
a594cfbf
FB
1189 s->bus_num = bus_num;
1190 s->addr = addr;
1191 return 1;
1192 } else {
1193 return 0;
1194 }
1195}
bb36d470 1196
5fafdf24
TS
1197/* the syntax is :
1198 'bus.addr' (decimal numbers) or
a594cfbf 1199 'vendor_id:product_id' (hexa numbers) */
5fafdf24 1200static int usb_host_find_device(int *pbus_num, int *paddr,
1f6e24e7 1201 char *product_name, int product_name_size,
a594cfbf
FB
1202 const char *devname)
1203{
1204 const char *p;
1205 int ret;
1206 FindDeviceState fs;
1207
1208 p = strchr(devname, '.');
1209 if (p) {
1210 *pbus_num = strtoul(devname, NULL, 0);
4b096fc9
AL
1211
1212 if (*(p + 1) == '*') {
1213 usb_host_auto_add(*pbus_num, -1, -1, -1);
1214 return -1;
1215 }
1216
a594cfbf 1217 *paddr = strtoul(p + 1, NULL, 0);
1f6e24e7
FB
1218 fs.bus_num = *pbus_num;
1219 fs.addr = *paddr;
1220 ret = usb_host_scan(&fs, usb_host_find_device_scan);
1221 if (ret)
1222 pstrcpy(product_name, product_name_size, fs.product_name);
a594cfbf
FB
1223 return 0;
1224 }
1225 p = strchr(devname, ':');
1226 if (p) {
1227 fs.vendor_id = strtoul(devname, NULL, 16);
4b096fc9
AL
1228
1229 if (*(p + 1) == '*') {
1230 usb_host_auto_add(-1, -1, fs.vendor_id, -1);
1231 return -1;
1232 }
1233
a594cfbf
FB
1234 fs.product_id = strtoul(p + 1, NULL, 16);
1235 ret = usb_host_scan(&fs, usb_host_find_device_scan);
1236 if (ret) {
1237 *pbus_num = fs.bus_num;
1238 *paddr = fs.addr;
1f6e24e7 1239 pstrcpy(product_name, product_name_size, fs.product_name);
a594cfbf 1240 return 0;
bb36d470
FB
1241 }
1242 }
a594cfbf 1243 return -1;
bb36d470
FB
1244}
1245
a594cfbf
FB
1246/**********************/
1247/* USB host device info */
1248
1249struct usb_class_info {
1250 int class;
1251 const char *class_name;
1252};
1253
1254static const struct usb_class_info usb_class_info[] = {
1255 { USB_CLASS_AUDIO, "Audio"},
1256 { USB_CLASS_COMM, "Communication"},
1257 { USB_CLASS_HID, "HID"},
1258 { USB_CLASS_HUB, "Hub" },
1259 { USB_CLASS_PHYSICAL, "Physical" },
1260 { USB_CLASS_PRINTER, "Printer" },
1261 { USB_CLASS_MASS_STORAGE, "Storage" },
1262 { USB_CLASS_CDC_DATA, "Data" },
1263 { USB_CLASS_APP_SPEC, "Application Specific" },
1264 { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1265 { USB_CLASS_STILL_IMAGE, "Still Image" },
b9dc033c 1266 { USB_CLASS_CSCID, "Smart Card" },
a594cfbf
FB
1267 { USB_CLASS_CONTENT_SEC, "Content Security" },
1268 { -1, NULL }
1269};
1270
1271static const char *usb_class_str(uint8_t class)
bb36d470 1272{
a594cfbf
FB
1273 const struct usb_class_info *p;
1274 for(p = usb_class_info; p->class != -1; p++) {
1275 if (p->class == class)
1276 break;
bb36d470 1277 }
a594cfbf
FB
1278 return p->class_name;
1279}
1280
9596ebb7
PB
1281static void usb_info_device(int bus_num, int addr, int class_id,
1282 int vendor_id, int product_id,
1283 const char *product_name,
1284 int speed)
a594cfbf
FB
1285{
1286 const char *class_str, *speed_str;
1287
1288 switch(speed) {
5fafdf24
TS
1289 case USB_SPEED_LOW:
1290 speed_str = "1.5";
a594cfbf 1291 break;
5fafdf24
TS
1292 case USB_SPEED_FULL:
1293 speed_str = "12";
a594cfbf 1294 break;
5fafdf24
TS
1295 case USB_SPEED_HIGH:
1296 speed_str = "480";
a594cfbf
FB
1297 break;
1298 default:
5fafdf24 1299 speed_str = "?";
a594cfbf
FB
1300 break;
1301 }
1302
5fafdf24 1303 term_printf(" Device %d.%d, speed %s Mb/s\n",
a594cfbf
FB
1304 bus_num, addr, speed_str);
1305 class_str = usb_class_str(class_id);
5fafdf24 1306 if (class_str)
a594cfbf
FB
1307 term_printf(" %s:", class_str);
1308 else
1309 term_printf(" Class %02x:", class_id);
1310 term_printf(" USB device %04x:%04x", vendor_id, product_id);
1311 if (product_name[0] != '\0')
1312 term_printf(", %s", product_name);
1313 term_printf("\n");
1314}
1315
5fafdf24 1316static int usb_host_info_device(void *opaque, int bus_num, int addr,
a594cfbf 1317 int class_id,
5fafdf24 1318 int vendor_id, int product_id,
a594cfbf
FB
1319 const char *product_name,
1320 int speed)
1321{
1322 usb_info_device(bus_num, addr, class_id, vendor_id, product_id,
1323 product_name, speed);
1324 return 0;
1325}
1326
1327void usb_host_info(void)
1328{
1329 usb_host_scan(NULL, usb_host_info_device);
bb36d470
FB
1330}
1331
1332#else
1333
446ab128
AL
1334#include "hw/usb.h"
1335
a594cfbf
FB
1336void usb_host_info(void)
1337{
1338 term_printf("USB host devices not supported\n");
1339}
1340
bb36d470 1341/* XXX: modify configure to compile the right host driver */
a594cfbf 1342USBDevice *usb_host_device_open(const char *devname)
bb36d470
FB
1343{
1344 return NULL;
1345}
1346
1347#endif