blob: 537122d1a6d47ad2271f7032745520ea3e9eab39 [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <stdio.h>
18#include <stdlib.h>
19#include <unistd.h>
20#include <string.h>
21
22#include <sys/ioctl.h>
23#include <sys/types.h>
24#include <dirent.h>
25#include <fcntl.h>
26#include <errno.h>
27#include <ctype.h>
28
29#include <linux/usbdevice_fs.h>
30#include <linux/version.h>
31#if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20)
32#include <linux/usb/ch9.h>
33#else
34#include <linux/usb_ch9.h>
35#endif
36#include <asm/byteorder.h>
37
38#include "sysdeps.h"
39
40#define TRACE_TAG TRACE_USB
41#include "adb.h"
42
43
44/* usb scan debugging is waaaay too verbose */
45#define DBGX(x...)
46
47static adb_mutex_t usb_lock = ADB_MUTEX_INITIALIZER;
48
49struct usb_handle
50{
51 usb_handle *prev;
52 usb_handle *next;
53
54 char fname[64];
55 int desc;
56 unsigned char ep_in;
57 unsigned char ep_out;
58
59 unsigned zero_mask;
60
61 struct usbdevfs_urb urb_in;
62 struct usbdevfs_urb urb_out;
63
64 int urb_in_busy;
65 int urb_out_busy;
66 int dead;
67
68 adb_cond_t notify;
69 adb_mutex_t lock;
70
71 // for garbage collecting disconnected devices
72 int mark;
73
74 // ID of thread currently in REAPURB
75 pthread_t reaper_thread;
76};
77
78static usb_handle handle_list = {
79 .prev = &handle_list,
80 .next = &handle_list,
81};
82
83static int known_device(const char *dev_name)
84{
85 usb_handle *usb;
86
87 adb_mutex_lock(&usb_lock);
88 for(usb = handle_list.next; usb != &handle_list; usb = usb->next){
89 if(!strcmp(usb->fname, dev_name)) {
90 // set mark flag to indicate this device is still alive
91 usb->mark = 1;
92 adb_mutex_unlock(&usb_lock);
93 return 1;
94 }
95 }
96 adb_mutex_unlock(&usb_lock);
97 return 0;
98}
99
100static void kick_disconnected_devices()
101{
102 usb_handle *usb;
103
104 adb_mutex_lock(&usb_lock);
105 // kick any devices in the device list that were not found in the device scan
106 for(usb = handle_list.next; usb != &handle_list; usb = usb->next){
107 if (usb->mark == 0) {
108 usb_kick(usb);
109 } else {
110 usb->mark = 0;
111 }
112 }
113 adb_mutex_unlock(&usb_lock);
114
115}
116
117static void register_device(const char *dev_name, unsigned char ep_in, unsigned char ep_out,
118 int ifc, const char *serial, unsigned zero_mask);
119
120static inline int badname(const char *name)
121{
122 while(*name) {
123 if(!isdigit(*name++)) return 1;
124 }
125 return 0;
126}
127
128static int find_usb_device(const char *base,
129 void (*register_device_callback) (const char *, unsigned char, unsigned char, int, const char *, unsigned))
130{
131 char busname[32], devname[32];
132 unsigned char local_ep_in, local_ep_out;
133 DIR *busdir , *devdir ;
134 struct dirent *de;
135 int fd ;
136 int found_device = 0;
137 char serial[256];
138
139 busdir = opendir(base);
140 if(busdir == 0) return 0;
141
142 while((de = readdir(busdir)) != 0) {
143 if(badname(de->d_name)) continue;
144
145 snprintf(busname, sizeof busname, "%s/%s", base, de->d_name);
146 devdir = opendir(busname);
147 if(devdir == 0) continue;
148
149// DBGX("[ scanning %s ]\n", busname);
150 while((de = readdir(devdir))) {
151 unsigned char devdesc[256];
152 unsigned char* bufptr = devdesc;
153 struct usb_device_descriptor* device;
154 struct usb_config_descriptor* config;
155 struct usb_interface_descriptor* interface;
156 struct usb_endpoint_descriptor *ep1, *ep2;
157 unsigned zero_mask = 0;
158 unsigned vid, pid;
159 int i, interfaces;
160 size_t desclength;
161
162 if(badname(de->d_name)) continue;
163 snprintf(devname, sizeof devname, "%s/%s", busname, de->d_name);
164
165 if(known_device(devname)) {
166 DBGX("skipping %s\n", devname);
167 continue;
168 }
169
170// DBGX("[ scanning %s ]\n", devname);
171 if((fd = unix_open(devname, O_RDWR)) < 0) {
172 continue;
173 }
174
175 desclength = adb_read(fd, devdesc, sizeof(devdesc));
176
177 // should have device and configuration descriptors, and atleast two endpoints
178 if (desclength < USB_DT_DEVICE_SIZE + USB_DT_CONFIG_SIZE) {
179 D("desclength %d is too small\n", desclength);
180 adb_close(fd);
181 continue;
182 }
183
184 device = (struct usb_device_descriptor*)bufptr;
185 bufptr += USB_DT_DEVICE_SIZE;
186
187 if((device->bLength != USB_DT_DEVICE_SIZE) || (device->bDescriptorType != USB_DT_DEVICE)) {
188 adb_close(fd);
189 continue;
190 }
191
192 vid = __le16_to_cpu(device->idVendor);
193 pid = __le16_to_cpu(device->idProduct);
194 pid = devdesc[10] | (devdesc[11] << 8);
195 DBGX("[ %s is V:%04x P:%04x ]\n", devname, vid, pid);
196
197 // should have config descriptor next
198 config = (struct usb_config_descriptor *)bufptr;
199 bufptr += USB_DT_CONFIG_SIZE;
200 if (config->bLength != USB_DT_CONFIG_SIZE || config->bDescriptorType != USB_DT_CONFIG) {
201 D("usb_config_descriptor not found\n");
202 adb_close(fd);
203 continue;
204 }
205
206 // loop through all the interfaces and look for the ADB interface
207 interfaces = config->bNumInterfaces;
208 for (i = 0; i < interfaces; i++) {
209 if (bufptr + USB_DT_ENDPOINT_SIZE > devdesc + desclength)
210 break;
211
212 interface = (struct usb_interface_descriptor *)bufptr;
213 bufptr += USB_DT_INTERFACE_SIZE;
214 if (interface->bLength != USB_DT_INTERFACE_SIZE ||
215 interface->bDescriptorType != USB_DT_INTERFACE) {
216 D("usb_interface_descriptor not found\n");
217 break;
218 }
219
220 DBGX("bInterfaceClass: %d, bInterfaceSubClass: %d,"
221 "bInterfaceProtocol: %d, bNumEndpoints: %d\n",
222 interface->bInterfaceClass, interface->bInterfaceSubClass,
223 interface->bInterfaceProtocol, interface->bNumEndpoints);
224
225 if (interface->bNumEndpoints == 2 &&
226 is_adb_interface(vid, pid, interface->bInterfaceClass,
227 interface->bInterfaceSubClass, interface->bInterfaceProtocol)) {
228
229 DBGX("looking for bulk endpoints\n");
230 // looks like ADB...
231 ep1 = (struct usb_endpoint_descriptor *)bufptr;
232 bufptr += USB_DT_ENDPOINT_SIZE;
233 ep2 = (struct usb_endpoint_descriptor *)bufptr;
234 bufptr += USB_DT_ENDPOINT_SIZE;
235
236 if (bufptr > devdesc + desclength ||
237 ep1->bLength != USB_DT_ENDPOINT_SIZE ||
238 ep1->bDescriptorType != USB_DT_ENDPOINT ||
239 ep2->bLength != USB_DT_ENDPOINT_SIZE ||
240 ep2->bDescriptorType != USB_DT_ENDPOINT) {
241 D("endpoints not found\n");
242 break;
243 }
244
245 // both endpoints should be bulk
246 if (ep1->bmAttributes != USB_ENDPOINT_XFER_BULK ||
247 ep2->bmAttributes != USB_ENDPOINT_XFER_BULK) {
248 D("bulk endpoints not found\n");
249 continue;
250 }
251
252 /* aproto 01 needs 0 termination */
253 if(interface->bInterfaceProtocol == 0x01) {
254 zero_mask = ep1->wMaxPacketSize - 1;
255 }
256
257 // we have a match. now we just need to figure out which is in and which is out.
258 if (ep1->bEndpointAddress & USB_ENDPOINT_DIR_MASK) {
259 local_ep_in = ep1->bEndpointAddress;
260 local_ep_out = ep2->bEndpointAddress;
261 } else {
262 local_ep_in = ep2->bEndpointAddress;
263 local_ep_out = ep1->bEndpointAddress;
264 }
265
266 // read the device's serial number
267 serial[0] = 0;
268 memset(serial, 0, sizeof(serial));
269 if (device->iSerialNumber) {
270 struct usbdevfs_ctrltransfer ctrl;
271 __u16 buffer[128];
Mike Lockwood3d9b2652009-07-08 09:43:49 -0400272 __u16 languages[128];
273 int i, result;
274 int languageCount = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800275
Mike Lockwood3d9b2652009-07-08 09:43:49 -0400276 memset(languages, 0, sizeof(languages));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800277 memset(&ctrl, 0, sizeof(ctrl));
278
Mike Lockwood3d9b2652009-07-08 09:43:49 -0400279 // read list of supported languages
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800280 ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE;
281 ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
Mike Lockwood3d9b2652009-07-08 09:43:49 -0400282 ctrl.wValue = (USB_DT_STRING << 8) | 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800283 ctrl.wIndex = 0;
Mike Lockwood3d9b2652009-07-08 09:43:49 -0400284 ctrl.wLength = sizeof(languages);
285 ctrl.data = languages;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800286
287 result = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
Mike Lockwood3d9b2652009-07-08 09:43:49 -0400288 if (result > 0)
289 languageCount = (result - 2) / 2;
290
291 for (i = 1; i <= languageCount; i++) {
292 memset(buffer, 0, sizeof(buffer));
293 memset(&ctrl, 0, sizeof(ctrl));
294
295 ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE;
296 ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
297 ctrl.wValue = (USB_DT_STRING << 8) | device->iSerialNumber;
298 ctrl.wIndex = languages[i];
299 ctrl.wLength = sizeof(buffer);
300 ctrl.data = buffer;
301
302 result = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
303 if (result > 0) {
304 int i;
305 // skip first word, and copy the rest to the serial string, changing shorts to bytes.
306 result /= 2;
307 for (i = 1; i < result; i++)
308 serial[i - 1] = buffer[i];
309 serial[i - 1] = 0;
310 break;
311 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800312 }
313 }
314
315 register_device_callback(devname, local_ep_in, local_ep_out,
316 interface->bInterfaceNumber, serial, zero_mask);
317
318 found_device = 1;
319 break;
320 } else {
Xavier Ducrohetde6f62a2009-07-24 14:14:56 -0700321 // seek next interface descriptor
322 if (i < interfaces - 1) {
323 while (bufptr[1] != USB_DT_INTERFACE) {
324 bufptr += bufptr[0];
325 }
326 }
327 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800328 } // end of for
329
330 adb_close(fd);
331 } // end of devdir while
332 closedir(devdir);
333 } //end of busdir while
334 closedir(busdir);
335
336 return found_device;
337}
338
339void usb_cleanup()
340{
341}
342
343static int usb_bulk_write(usb_handle *h, const void *data, int len)
344{
345 struct usbdevfs_urb *urb = &h->urb_out;
346 int res;
347
348 memset(urb, 0, sizeof(*urb));
349 urb->type = USBDEVFS_URB_TYPE_BULK;
350 urb->endpoint = h->ep_out;
351 urb->status = -1;
352 urb->buffer = (void*) data;
353 urb->buffer_length = len;
354
355 D("++ write ++\n");
356
357 adb_mutex_lock(&h->lock);
358 if(h->dead) {
359 res = -1;
360 goto fail;
361 }
362 do {
363 res = ioctl(h->desc, USBDEVFS_SUBMITURB, urb);
364 } while((res < 0) && (errno == EINTR));
365
366 if(res < 0) {
367 goto fail;
368 }
369
370 res = -1;
371 h->urb_out_busy = 1;
372 for(;;) {
373 adb_cond_wait(&h->notify, &h->lock);
374 if(h->dead) {
375 break;
376 }
377 if(h->urb_out_busy == 0) {
378 if(urb->status == 0) {
379 res = urb->actual_length;
380 }
381 break;
382 }
383 }
384fail:
385 adb_mutex_unlock(&h->lock);
386 D("-- write --\n");
387 return res;
388}
389
390static int usb_bulk_read(usb_handle *h, void *data, int len)
391{
392 struct usbdevfs_urb *urb = &h->urb_in;
393 struct usbdevfs_urb *out = NULL;
394 int res;
395
396 memset(urb, 0, sizeof(*urb));
397 urb->type = USBDEVFS_URB_TYPE_BULK;
398 urb->endpoint = h->ep_in;
399 urb->status = -1;
400 urb->buffer = data;
401 urb->buffer_length = len;
402
403
404 adb_mutex_lock(&h->lock);
405 if(h->dead) {
406 res = -1;
407 goto fail;
408 }
409 do {
410 res = ioctl(h->desc, USBDEVFS_SUBMITURB, urb);
411 } while((res < 0) && (errno == EINTR));
412
413 if(res < 0) {
414 goto fail;
415 }
416
417 h->urb_in_busy = 1;
418 for(;;) {
419 D("[ reap urb - wait ]\n");
420 h->reaper_thread = pthread_self();
421 adb_mutex_unlock(&h->lock);
422 res = ioctl(h->desc, USBDEVFS_REAPURB, &out);
423 adb_mutex_lock(&h->lock);
424 h->reaper_thread = 0;
425 if(h->dead) {
426 res = -1;
427 break;
428 }
429 if(res < 0) {
430 if(errno == EINTR) {
431 continue;
432 }
433 D("[ reap urb - error ]\n");
434 break;
435 }
436 D("[ urb @%p status = %d, actual = %d ]\n",
437 out, out->status, out->actual_length);
438
439 if(out == &h->urb_in) {
440 D("[ reap urb - IN complete ]\n");
441 h->urb_in_busy = 0;
442 if(urb->status == 0) {
443 res = urb->actual_length;
444 } else {
445 res = -1;
446 }
447 break;
448 }
449 if(out == &h->urb_out) {
450 D("[ reap urb - OUT compelete ]\n");
451 h->urb_out_busy = 0;
452 adb_cond_broadcast(&h->notify);
453 }
454 }
455fail:
456 adb_mutex_unlock(&h->lock);
457 return res;
458}
459
460
461int usb_write(usb_handle *h, const void *_data, int len)
462{
463 unsigned char *data = (unsigned char*) _data;
464 int n;
465 int need_zero = 0;
466
467 if(h->zero_mask) {
468 /* if we need 0-markers and our transfer
469 ** is an even multiple of the packet size,
470 ** we make note of it
471 */
472 if(!(len & h->zero_mask)) {
473 need_zero = 1;
474 }
475 }
476
477 while(len > 0) {
478 int xfer = (len > 4096) ? 4096 : len;
479
480 n = usb_bulk_write(h, data, xfer);
481 if(n != xfer) {
482 D("ERROR: n = %d, errno = %d (%s)\n",
483 n, errno, strerror(errno));
484 return -1;
485 }
486
487 len -= xfer;
488 data += xfer;
489 }
490
491 if(need_zero){
492 n = usb_bulk_write(h, _data, 0);
493 return n;
494 }
495
496 return 0;
497}
498
499int usb_read(usb_handle *h, void *_data, int len)
500{
501 unsigned char *data = (unsigned char*) _data;
502 int n;
503
504 D("++ usb_read ++\n");
505 while(len > 0) {
506 int xfer = (len > 4096) ? 4096 : len;
507
508 D("[ usb read %d fd = %d], fname=%s\n", xfer, h->desc, h->fname);
509 n = usb_bulk_read(h, data, xfer);
510 D("[ usb read %d ] = %d, fname=%s\n", xfer, n, h->fname);
511 if(n != xfer) {
512 if((errno == ETIMEDOUT) && (h->desc != -1)) {
513 D("[ timeout ]\n");
514 if(n > 0){
515 data += n;
516 len -= n;
517 }
518 continue;
519 }
520 D("ERROR: n = %d, errno = %d (%s)\n",
521 n, errno, strerror(errno));
522 return -1;
523 }
524
525 len -= xfer;
526 data += xfer;
527 }
528
529 D("-- usb_read --\n");
530 return 0;
531}
532
533void usb_kick(usb_handle *h)
534{
535 D("[ kicking %p (fd = %d) ]\n", h, h->desc);
536 adb_mutex_lock(&h->lock);
537 if(h->dead == 0) {
538 h->dead = 1;
539
540 /* HACK ALERT!
541 ** Sometimes we get stuck in ioctl(USBDEVFS_REAPURB).
542 ** This is a workaround for that problem.
543 */
544 if (h->reaper_thread) {
545 pthread_kill(h->reaper_thread, SIGALRM);
546 }
547
548 /* cancel any pending transactions
549 ** these will quietly fail if the txns are not active,
550 ** but this ensures that a reader blocked on REAPURB
551 ** will get unblocked
552 */
553 ioctl(h->desc, USBDEVFS_DISCARDURB, &h->urb_in);
554 ioctl(h->desc, USBDEVFS_DISCARDURB, &h->urb_out);
555 h->urb_in.status = -ENODEV;
556 h->urb_out.status = -ENODEV;
557 h->urb_in_busy = 0;
558 h->urb_out_busy = 0;
559 adb_cond_broadcast(&h->notify);
560 }
561 adb_mutex_unlock(&h->lock);
562}
563
564int usb_close(usb_handle *h)
565{
566 D("[ usb close ... ]\n");
567 adb_mutex_lock(&usb_lock);
568 h->next->prev = h->prev;
569 h->prev->next = h->next;
570 h->prev = 0;
571 h->next = 0;
572
573 adb_close(h->desc);
574 D("[ usb closed %p (fd = %d) ]\n", h, h->desc);
575 adb_mutex_unlock(&usb_lock);
576
577 free(h);
578 return 0;
579}
580
581static void register_device(const char *dev_name,
582 unsigned char ep_in, unsigned char ep_out,
583 int interface,
584 const char *serial, unsigned zero_mask)
585{
586 usb_handle* usb = 0;
587 int n = 0;
588
589 /* Since Linux will not reassign the device ID (and dev_name)
590 ** as long as the device is open, we can add to the list here
591 ** once we open it and remove from the list when we're finally
592 ** closed and everything will work out fine.
593 **
594 ** If we have a usb_handle on the list 'o handles with a matching
595 ** name, we have no further work to do.
596 */
597 adb_mutex_lock(&usb_lock);
598 for(usb = handle_list.next; usb != &handle_list; usb = usb->next){
599 if(!strcmp(usb->fname, dev_name)) {
600 adb_mutex_unlock(&usb_lock);
601 return;
602 }
603 }
604 adb_mutex_unlock(&usb_lock);
605
606 D("[ usb located new device %s (%d/%d/%d) ]\n",
607 dev_name, ep_in, ep_out, interface);
608 usb = calloc(1, sizeof(usb_handle));
609 strcpy(usb->fname, dev_name);
610 usb->ep_in = ep_in;
611 usb->ep_out = ep_out;
612 usb->zero_mask = zero_mask;
613
614 adb_cond_init(&usb->notify, 0);
615 adb_mutex_init(&usb->lock, 0);
616 /* initialize mark to 1 so we don't get garbage collected after the device scan */
617 usb->mark = 1;
618 usb->reaper_thread = 0;
619
620 usb->desc = unix_open(usb->fname, O_RDWR);
621 if(usb->desc < 0) goto fail;
622 D("[ usb open %s fd = %d]\n", usb->fname, usb->desc);
623 n = ioctl(usb->desc, USBDEVFS_CLAIMINTERFACE, &interface);
624 if(n != 0) goto fail;
625
626 /* add to the end of the active handles */
627 adb_mutex_lock(&usb_lock);
628 usb->next = &handle_list;
629 usb->prev = handle_list.prev;
630 usb->prev->next = usb;
631 usb->next->prev = usb;
632 adb_mutex_unlock(&usb_lock);
633
634 register_usb_transport(usb, serial);
635 return;
636
637fail:
638 D("[ usb open %s error=%d, err_str = %s]\n",
639 usb->fname, errno, strerror(errno));
640 if(usb->desc >= 0) {
641 adb_close(usb->desc);
642 }
643 free(usb);
644}
645
646void* device_poll_thread(void* unused)
647{
648 D("Created device thread\n");
649 for(;;) {
650 /* XXX use inotify */
651 find_usb_device("/dev/bus/usb", register_device);
652 kick_disconnected_devices();
653 sleep(1);
654 }
655 return NULL;
656}
657
658static void sigalrm_handler(int signo)
659{
660 // don't need to do anything here
661}
662
663void usb_init()
664{
665 adb_thread_t tid;
666 struct sigaction actions;
667
668 memset(&actions, 0, sizeof(actions));
669 sigemptyset(&actions.sa_mask);
670 actions.sa_flags = 0;
671 actions.sa_handler = sigalrm_handler;
672 sigaction(SIGALRM,& actions, NULL);
673
674 if(adb_thread_create(&tid, device_poll_thread, NULL)){
675 fatal_errno("cannot create input thread");
676 }
677}
678