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