• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
47 static adb_mutex_t usb_lock = ADB_MUTEX_INITIALIZER;
48 
49 struct 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     unsigned writeable;
61 
62     struct usbdevfs_urb urb_in;
63     struct usbdevfs_urb urb_out;
64 
65     int urb_in_busy;
66     int urb_out_busy;
67     int dead;
68 
69     adb_cond_t notify;
70     adb_mutex_t lock;
71 
72     // for garbage collecting disconnected devices
73     int mark;
74 
75     // ID of thread currently in REAPURB
76     pthread_t reaper_thread;
77 };
78 
79 static usb_handle handle_list = {
80     .prev = &handle_list,
81     .next = &handle_list,
82 };
83 
known_device(const char * dev_name)84 static int known_device(const char *dev_name)
85 {
86     usb_handle *usb;
87 
88     adb_mutex_lock(&usb_lock);
89     for(usb = handle_list.next; usb != &handle_list; usb = usb->next){
90         if(!strcmp(usb->fname, dev_name)) {
91             // set mark flag to indicate this device is still alive
92             usb->mark = 1;
93             adb_mutex_unlock(&usb_lock);
94             return 1;
95         }
96     }
97     adb_mutex_unlock(&usb_lock);
98     return 0;
99 }
100 
kick_disconnected_devices()101 static void kick_disconnected_devices()
102 {
103     usb_handle *usb;
104 
105     adb_mutex_lock(&usb_lock);
106     // kick any devices in the device list that were not found in the device scan
107     for(usb = handle_list.next; usb != &handle_list; usb = usb->next){
108         if (usb->mark == 0) {
109             usb_kick(usb);
110         } else {
111             usb->mark = 0;
112         }
113     }
114     adb_mutex_unlock(&usb_lock);
115 
116 }
117 
118 static void register_device(const char *dev_name, unsigned char ep_in, unsigned char ep_out,
119                             int ifc, int serial_index, unsigned zero_mask);
120 
badname(const char * name)121 static inline int badname(const char *name)
122 {
123     while(*name) {
124         if(!isdigit(*name++)) return 1;
125     }
126     return 0;
127 }
128 
find_usb_device(const char * base,void (* register_device_callback)(const char *,unsigned char,unsigned char,int,int,unsigned))129 static void find_usb_device(const char *base,
130         void (*register_device_callback)
131                 (const char *, unsigned char, unsigned char, int, int, unsigned))
132 {
133     char busname[32], devname[32];
134     unsigned char local_ep_in, local_ep_out;
135     DIR *busdir , *devdir ;
136     struct dirent *de;
137     int fd ;
138 
139     busdir = opendir(base);
140     if(busdir == 0) return;
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_RDONLY)) < 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                     register_device_callback(devname, local_ep_in, local_ep_out,
267                             interface->bInterfaceNumber, device->iSerialNumber, zero_mask);
268 
269                     break;
270                 } else {
271                     // seek next interface descriptor
272                     bufptr += (USB_DT_ENDPOINT_SIZE * interface->bNumEndpoints);
273                  }
274             } // end of for
275 
276             adb_close(fd);
277         } // end of devdir while
278         closedir(devdir);
279     } //end of busdir while
280     closedir(busdir);
281 }
282 
usb_cleanup()283 void usb_cleanup()
284 {
285 }
286 
usb_bulk_write(usb_handle * h,const void * data,int len)287 static int usb_bulk_write(usb_handle *h, const void *data, int len)
288 {
289     struct usbdevfs_urb *urb = &h->urb_out;
290     int res;
291 
292     memset(urb, 0, sizeof(*urb));
293     urb->type = USBDEVFS_URB_TYPE_BULK;
294     urb->endpoint = h->ep_out;
295     urb->status = -1;
296     urb->buffer = (void*) data;
297     urb->buffer_length = len;
298 
299     D("++ write ++\n");
300 
301     adb_mutex_lock(&h->lock);
302     if(h->dead) {
303         res = -1;
304         goto fail;
305     }
306     do {
307         res = ioctl(h->desc, USBDEVFS_SUBMITURB, urb);
308     } while((res < 0) && (errno == EINTR));
309 
310     if(res < 0) {
311         goto fail;
312     }
313 
314     res = -1;
315     h->urb_out_busy = 1;
316     for(;;) {
317         adb_cond_wait(&h->notify, &h->lock);
318         if(h->dead) {
319             break;
320         }
321         if(h->urb_out_busy == 0) {
322             if(urb->status == 0) {
323                 res = urb->actual_length;
324             }
325             break;
326         }
327     }
328 fail:
329     adb_mutex_unlock(&h->lock);
330     D("-- write --\n");
331     return res;
332 }
333 
usb_bulk_read(usb_handle * h,void * data,int len)334 static int usb_bulk_read(usb_handle *h, void *data, int len)
335 {
336     struct usbdevfs_urb *urb = &h->urb_in;
337     struct usbdevfs_urb *out = NULL;
338     int res;
339 
340     memset(urb, 0, sizeof(*urb));
341     urb->type = USBDEVFS_URB_TYPE_BULK;
342     urb->endpoint = h->ep_in;
343     urb->status = -1;
344     urb->buffer = data;
345     urb->buffer_length = len;
346 
347 
348     adb_mutex_lock(&h->lock);
349     if(h->dead) {
350         res = -1;
351         goto fail;
352     }
353     do {
354         res = ioctl(h->desc, USBDEVFS_SUBMITURB, urb);
355     } while((res < 0) && (errno == EINTR));
356 
357     if(res < 0) {
358         goto fail;
359     }
360 
361     h->urb_in_busy = 1;
362     for(;;) {
363         D("[ reap urb - wait ]\n");
364         h->reaper_thread = pthread_self();
365         adb_mutex_unlock(&h->lock);
366         res = ioctl(h->desc, USBDEVFS_REAPURB, &out);
367         adb_mutex_lock(&h->lock);
368         h->reaper_thread = 0;
369         if(h->dead) {
370             res = -1;
371             break;
372         }
373         if(res < 0) {
374             if(errno == EINTR) {
375                 continue;
376             }
377             D("[ reap urb - error ]\n");
378             break;
379         }
380         D("[ urb @%p status = %d, actual = %d ]\n",
381             out, out->status, out->actual_length);
382 
383         if(out == &h->urb_in) {
384             D("[ reap urb - IN complete ]\n");
385             h->urb_in_busy = 0;
386             if(urb->status == 0) {
387                 res = urb->actual_length;
388             } else {
389                 res = -1;
390             }
391             break;
392         }
393         if(out == &h->urb_out) {
394             D("[ reap urb - OUT compelete ]\n");
395             h->urb_out_busy = 0;
396             adb_cond_broadcast(&h->notify);
397         }
398     }
399 fail:
400     adb_mutex_unlock(&h->lock);
401     return res;
402 }
403 
404 
usb_write(usb_handle * h,const void * _data,int len)405 int usb_write(usb_handle *h, const void *_data, int len)
406 {
407     unsigned char *data = (unsigned char*) _data;
408     int n;
409     int need_zero = 0;
410 
411     if(h->zero_mask) {
412             /* if we need 0-markers and our transfer
413             ** is an even multiple of the packet size,
414             ** we make note of it
415             */
416         if(!(len & h->zero_mask)) {
417             need_zero = 1;
418         }
419     }
420 
421     while(len > 0) {
422         int xfer = (len > 4096) ? 4096 : len;
423 
424         n = usb_bulk_write(h, data, xfer);
425         if(n != xfer) {
426             D("ERROR: n = %d, errno = %d (%s)\n",
427                 n, errno, strerror(errno));
428             return -1;
429         }
430 
431         len -= xfer;
432         data += xfer;
433     }
434 
435     if(need_zero){
436         n = usb_bulk_write(h, _data, 0);
437         return n;
438     }
439 
440     return 0;
441 }
442 
usb_read(usb_handle * h,void * _data,int len)443 int usb_read(usb_handle *h, void *_data, int len)
444 {
445     unsigned char *data = (unsigned char*) _data;
446     int n;
447 
448     D("++ usb_read ++\n");
449     while(len > 0) {
450         int xfer = (len > 4096) ? 4096 : len;
451 
452         D("[ usb read %d fd = %d], fname=%s\n", xfer, h->desc, h->fname);
453         n = usb_bulk_read(h, data, xfer);
454         D("[ usb read %d ] = %d, fname=%s\n", xfer, n, h->fname);
455         if(n != xfer) {
456             if((errno == ETIMEDOUT) && (h->desc != -1)) {
457                 D("[ timeout ]\n");
458                 if(n > 0){
459                     data += n;
460                     len -= n;
461                 }
462                 continue;
463             }
464             D("ERROR: n = %d, errno = %d (%s)\n",
465                 n, errno, strerror(errno));
466             return -1;
467         }
468 
469         len -= xfer;
470         data += xfer;
471     }
472 
473     D("-- usb_read --\n");
474     return 0;
475 }
476 
usb_kick(usb_handle * h)477 void usb_kick(usb_handle *h)
478 {
479     D("[ kicking %p (fd = %d) ]\n", h, h->desc);
480     adb_mutex_lock(&h->lock);
481     if(h->dead == 0) {
482         h->dead = 1;
483 
484         if (h->writeable) {
485             /* HACK ALERT!
486             ** Sometimes we get stuck in ioctl(USBDEVFS_REAPURB).
487             ** This is a workaround for that problem.
488             */
489             if (h->reaper_thread) {
490                 pthread_kill(h->reaper_thread, SIGALRM);
491             }
492 
493             /* cancel any pending transactions
494             ** these will quietly fail if the txns are not active,
495             ** but this ensures that a reader blocked on REAPURB
496             ** will get unblocked
497             */
498             ioctl(h->desc, USBDEVFS_DISCARDURB, &h->urb_in);
499             ioctl(h->desc, USBDEVFS_DISCARDURB, &h->urb_out);
500             h->urb_in.status = -ENODEV;
501             h->urb_out.status = -ENODEV;
502             h->urb_in_busy = 0;
503             h->urb_out_busy = 0;
504             adb_cond_broadcast(&h->notify);
505         } else {
506             unregister_usb_transport(h);
507         }
508     }
509     adb_mutex_unlock(&h->lock);
510 }
511 
usb_close(usb_handle * h)512 int usb_close(usb_handle *h)
513 {
514     D("[ usb close ... ]\n");
515     adb_mutex_lock(&usb_lock);
516     h->next->prev = h->prev;
517     h->prev->next = h->next;
518     h->prev = 0;
519     h->next = 0;
520 
521     adb_close(h->desc);
522     D("[ usb closed %p (fd = %d) ]\n", h, h->desc);
523     adb_mutex_unlock(&usb_lock);
524 
525     free(h);
526     return 0;
527 }
528 
register_device(const char * dev_name,unsigned char ep_in,unsigned char ep_out,int interface,int serial_index,unsigned zero_mask)529 static void register_device(const char *dev_name,
530                             unsigned char ep_in, unsigned char ep_out,
531                             int interface, int serial_index, unsigned zero_mask)
532 {
533     usb_handle* usb = 0;
534     int n = 0;
535     char serial[256];
536 
537         /* Since Linux will not reassign the device ID (and dev_name)
538         ** as long as the device is open, we can add to the list here
539         ** once we open it and remove from the list when we're finally
540         ** closed and everything will work out fine.
541         **
542         ** If we have a usb_handle on the list 'o handles with a matching
543         ** name, we have no further work to do.
544         */
545     adb_mutex_lock(&usb_lock);
546     for(usb = handle_list.next; usb != &handle_list; usb = usb->next){
547         if(!strcmp(usb->fname, dev_name)) {
548             adb_mutex_unlock(&usb_lock);
549             return;
550         }
551     }
552     adb_mutex_unlock(&usb_lock);
553 
554     D("[ usb located new device %s (%d/%d/%d) ]\n",
555         dev_name, ep_in, ep_out, interface);
556     usb = calloc(1, sizeof(usb_handle));
557     strcpy(usb->fname, dev_name);
558     usb->ep_in = ep_in;
559     usb->ep_out = ep_out;
560     usb->zero_mask = zero_mask;
561     usb->writeable = 1;
562 
563     adb_cond_init(&usb->notify, 0);
564     adb_mutex_init(&usb->lock, 0);
565     /* initialize mark to 1 so we don't get garbage collected after the device scan */
566     usb->mark = 1;
567     usb->reaper_thread = 0;
568 
569     usb->desc = unix_open(usb->fname, O_RDWR);
570     if(usb->desc < 0) {
571         /* if we fail, see if have read-only access */
572         usb->desc = unix_open(usb->fname, O_RDONLY);
573         if(usb->desc < 0) goto fail;
574         usb->writeable = 0;
575         D("[ usb open read-only %s fd = %d]\n", usb->fname, usb->desc);
576     } else {
577         D("[ usb open %s fd = %d]\n", usb->fname, usb->desc);
578         n = ioctl(usb->desc, USBDEVFS_CLAIMINTERFACE, &interface);
579         if(n != 0) goto fail;
580     }
581 
582         /* read the device's serial number */
583     serial[0] = 0;
584     memset(serial, 0, sizeof(serial));
585     if (serial_index) {
586         struct usbdevfs_ctrltransfer  ctrl;
587         __u16 buffer[128];
588         __u16 languages[128];
589         int i, result;
590         int languageCount = 0;
591 
592         memset(languages, 0, sizeof(languages));
593         memset(&ctrl, 0, sizeof(ctrl));
594 
595             // read list of supported languages
596         ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE;
597         ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
598         ctrl.wValue = (USB_DT_STRING << 8) | 0;
599         ctrl.wIndex = 0;
600         ctrl.wLength = sizeof(languages);
601         ctrl.data = languages;
602 
603         result = ioctl(usb->desc, USBDEVFS_CONTROL, &ctrl);
604         if (result > 0)
605             languageCount = (result - 2) / 2;
606 
607         for (i = 1; i <= languageCount; i++) {
608             memset(buffer, 0, sizeof(buffer));
609             memset(&ctrl, 0, sizeof(ctrl));
610 
611             ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE;
612             ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
613             ctrl.wValue = (USB_DT_STRING << 8) | serial_index;
614             ctrl.wIndex = languages[i];
615             ctrl.wLength = sizeof(buffer);
616             ctrl.data = buffer;
617 
618             result = ioctl(usb->desc, USBDEVFS_CONTROL, &ctrl);
619             if (result > 0) {
620                 int i;
621                 // skip first word, and copy the rest to the serial string, changing shorts to bytes.
622                 result /= 2;
623                 for (i = 1; i < result; i++)
624                     serial[i - 1] = buffer[i];
625                 serial[i - 1] = 0;
626                 break;
627             }
628         }
629     }
630 
631         /* add to the end of the active handles */
632     adb_mutex_lock(&usb_lock);
633     usb->next = &handle_list;
634     usb->prev = handle_list.prev;
635     usb->prev->next = usb;
636     usb->next->prev = usb;
637     adb_mutex_unlock(&usb_lock);
638 
639     register_usb_transport(usb, serial, usb->writeable);
640     return;
641 
642 fail:
643     D("[ usb open %s error=%d, err_str = %s]\n",
644         usb->fname,  errno, strerror(errno));
645     if(usb->desc >= 0) {
646         adb_close(usb->desc);
647     }
648     free(usb);
649 }
650 
device_poll_thread(void * unused)651 void* device_poll_thread(void* unused)
652 {
653     D("Created device thread\n");
654     for(;;) {
655             /* XXX use inotify */
656         find_usb_device("/dev/bus/usb", register_device);
657         kick_disconnected_devices();
658         sleep(1);
659     }
660     return NULL;
661 }
662 
sigalrm_handler(int signo)663 static void sigalrm_handler(int signo)
664 {
665     // don't need to do anything here
666 }
667 
usb_init()668 void usb_init()
669 {
670     adb_thread_t tid;
671     struct sigaction    actions;
672 
673     memset(&actions, 0, sizeof(actions));
674     sigemptyset(&actions.sa_mask);
675     actions.sa_flags = 0;
676     actions.sa_handler = sigalrm_handler;
677     sigaction(SIGALRM,& actions, NULL);
678 
679     if(adb_thread_create(&tid, device_poll_thread, NULL)){
680         fatal_errno("cannot create input thread");
681     }
682 }
683 
684