usb_linux.c revision 13f797da7f190e9ea52f2f3d235210b8a4963b21
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
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];
272                        int result;
273
274                        memset(buffer, 0, sizeof(buffer));
275                        memset(&ctrl, 0, sizeof(ctrl));
276
277                        ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE;
278                        ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
279                        ctrl.wValue = (USB_DT_STRING << 8) | device->iSerialNumber;
280                        ctrl.wIndex = 0;
281                        ctrl.wLength = sizeof(buffer);
282                        ctrl.data = buffer;
283
284                        result = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
285                        if (result > 0) {
286                            int i;
287                                // skip first word, and copy the rest to the serial string, changing shorts to bytes.
288                            result /= 2;
289                            for (i = 1; i < result; i++)
290                                serial[i - 1] = buffer[i];
291                            serial[i - 1] = 0;
292                        }
293                    }
294
295                    register_device_callback(devname, local_ep_in, local_ep_out,
296                            interface->bInterfaceNumber, serial, zero_mask);
297
298                    found_device = 1;
299                    break;
300                } else {
301                        // skip to next interface
302                    bufptr += (interface->bNumEndpoints * USB_DT_ENDPOINT_SIZE);
303                }
304            } // end of for
305
306            adb_close(fd);
307        } // end of devdir while
308        closedir(devdir);
309    } //end of busdir while
310    closedir(busdir);
311
312    return found_device;
313}
314
315void usb_cleanup()
316{
317}
318
319static int usb_bulk_write(usb_handle *h, const void *data, int len)
320{
321    struct usbdevfs_urb *urb = &h->urb_out;
322    int res;
323
324    memset(urb, 0, sizeof(*urb));
325    urb->type = USBDEVFS_URB_TYPE_BULK;
326    urb->endpoint = h->ep_out;
327    urb->status = -1;
328    urb->buffer = (void*) data;
329    urb->buffer_length = len;
330
331    D("++ write ++\n");
332
333    adb_mutex_lock(&h->lock);
334    if(h->dead) {
335        res = -1;
336        goto fail;
337    }
338    do {
339        res = ioctl(h->desc, USBDEVFS_SUBMITURB, urb);
340    } while((res < 0) && (errno == EINTR));
341
342    if(res < 0) {
343        goto fail;
344    }
345
346    res = -1;
347    h->urb_out_busy = 1;
348    for(;;) {
349        adb_cond_wait(&h->notify, &h->lock);
350        if(h->dead) {
351            break;
352        }
353        if(h->urb_out_busy == 0) {
354            if(urb->status == 0) {
355                res = urb->actual_length;
356            }
357            break;
358        }
359    }
360fail:
361    adb_mutex_unlock(&h->lock);
362    D("-- write --\n");
363    return res;
364}
365
366static int usb_bulk_read(usb_handle *h, void *data, int len)
367{
368    struct usbdevfs_urb *urb = &h->urb_in;
369    struct usbdevfs_urb *out = NULL;
370    int res;
371
372    memset(urb, 0, sizeof(*urb));
373    urb->type = USBDEVFS_URB_TYPE_BULK;
374    urb->endpoint = h->ep_in;
375    urb->status = -1;
376    urb->buffer = data;
377    urb->buffer_length = len;
378
379
380    adb_mutex_lock(&h->lock);
381    if(h->dead) {
382        res = -1;
383        goto fail;
384    }
385    do {
386        res = ioctl(h->desc, USBDEVFS_SUBMITURB, urb);
387    } while((res < 0) && (errno == EINTR));
388
389    if(res < 0) {
390        goto fail;
391    }
392
393    h->urb_in_busy = 1;
394    for(;;) {
395        D("[ reap urb - wait ]\n");
396        h->reaper_thread = pthread_self();
397        adb_mutex_unlock(&h->lock);
398        res = ioctl(h->desc, USBDEVFS_REAPURB, &out);
399        adb_mutex_lock(&h->lock);
400        h->reaper_thread = 0;
401        if(h->dead) {
402            res = -1;
403            break;
404        }
405        if(res < 0) {
406            if(errno == EINTR) {
407                continue;
408            }
409            D("[ reap urb - error ]\n");
410            break;
411        }
412        D("[ urb @%p status = %d, actual = %d ]\n",
413            out, out->status, out->actual_length);
414
415        if(out == &h->urb_in) {
416            D("[ reap urb - IN complete ]\n");
417            h->urb_in_busy = 0;
418            if(urb->status == 0) {
419                res = urb->actual_length;
420            } else {
421                res = -1;
422            }
423            break;
424        }
425        if(out == &h->urb_out) {
426            D("[ reap urb - OUT compelete ]\n");
427            h->urb_out_busy = 0;
428            adb_cond_broadcast(&h->notify);
429        }
430    }
431fail:
432    adb_mutex_unlock(&h->lock);
433    return res;
434}
435
436
437int usb_write(usb_handle *h, const void *_data, int len)
438{
439    unsigned char *data = (unsigned char*) _data;
440    int n;
441    int need_zero = 0;
442
443    if(h->zero_mask) {
444            /* if we need 0-markers and our transfer
445            ** is an even multiple of the packet size,
446            ** we make note of it
447            */
448        if(!(len & h->zero_mask)) {
449            need_zero = 1;
450        }
451    }
452
453    while(len > 0) {
454        int xfer = (len > 4096) ? 4096 : len;
455
456        n = usb_bulk_write(h, data, xfer);
457        if(n != xfer) {
458            D("ERROR: n = %d, errno = %d (%s)\n",
459                n, errno, strerror(errno));
460            return -1;
461        }
462
463        len -= xfer;
464        data += xfer;
465    }
466
467    if(need_zero){
468        n = usb_bulk_write(h, _data, 0);
469        return n;
470    }
471
472    return 0;
473}
474
475int usb_read(usb_handle *h, void *_data, int len)
476{
477    unsigned char *data = (unsigned char*) _data;
478    int n;
479
480    D("++ usb_read ++\n");
481    while(len > 0) {
482        int xfer = (len > 4096) ? 4096 : len;
483
484        D("[ usb read %d fd = %d], fname=%s\n", xfer, h->desc, h->fname);
485        n = usb_bulk_read(h, data, xfer);
486        D("[ usb read %d ] = %d, fname=%s\n", xfer, n, h->fname);
487        if(n != xfer) {
488            if((errno == ETIMEDOUT) && (h->desc != -1)) {
489                D("[ timeout ]\n");
490                if(n > 0){
491                    data += n;
492                    len -= n;
493                }
494                continue;
495            }
496            D("ERROR: n = %d, errno = %d (%s)\n",
497                n, errno, strerror(errno));
498            return -1;
499        }
500
501        len -= xfer;
502        data += xfer;
503    }
504
505    D("-- usb_read --\n");
506    return 0;
507}
508
509void usb_kick(usb_handle *h)
510{
511    D("[ kicking %p (fd = %d) ]\n", h, h->desc);
512    adb_mutex_lock(&h->lock);
513    if(h->dead == 0) {
514        h->dead = 1;
515
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    }
537    adb_mutex_unlock(&h->lock);
538}
539
540int usb_close(usb_handle *h)
541{
542    D("[ usb close ... ]\n");
543    adb_mutex_lock(&usb_lock);
544    h->next->prev = h->prev;
545    h->prev->next = h->next;
546    h->prev = 0;
547    h->next = 0;
548
549    adb_close(h->desc);
550    D("[ usb closed %p (fd = %d) ]\n", h, h->desc);
551    adb_mutex_unlock(&usb_lock);
552
553    free(h);
554    return 0;
555}
556
557static void register_device(const char *dev_name,
558                            unsigned char ep_in, unsigned char ep_out,
559                            int interface,
560                            const char *serial, unsigned zero_mask)
561{
562    usb_handle* usb = 0;
563    int n = 0;
564
565        /* Since Linux will not reassign the device ID (and dev_name)
566        ** as long as the device is open, we can add to the list here
567        ** once we open it and remove from the list when we're finally
568        ** closed and everything will work out fine.
569        **
570        ** If we have a usb_handle on the list 'o handles with a matching
571        ** name, we have no further work to do.
572        */
573    adb_mutex_lock(&usb_lock);
574    for(usb = handle_list.next; usb != &handle_list; usb = usb->next){
575        if(!strcmp(usb->fname, dev_name)) {
576            adb_mutex_unlock(&usb_lock);
577            return;
578        }
579    }
580    adb_mutex_unlock(&usb_lock);
581
582    D("[ usb located new device %s (%d/%d/%d) ]\n",
583        dev_name, ep_in, ep_out, interface);
584    usb = calloc(1, sizeof(usb_handle));
585    strcpy(usb->fname, dev_name);
586    usb->ep_in = ep_in;
587    usb->ep_out = ep_out;
588    usb->zero_mask = zero_mask;
589
590    adb_cond_init(&usb->notify, 0);
591    adb_mutex_init(&usb->lock, 0);
592    /* initialize mark to 1 so we don't get garbage collected after the device scan */
593    usb->mark = 1;
594    usb->reaper_thread = 0;
595
596    usb->desc = unix_open(usb->fname, O_RDWR);
597    if(usb->desc < 0) goto fail;
598    D("[ usb open %s fd = %d]\n", usb->fname, usb->desc);
599    n = ioctl(usb->desc, USBDEVFS_CLAIMINTERFACE, &interface);
600    if(n != 0) goto fail;
601
602        /* add to the end of the active handles */
603    adb_mutex_lock(&usb_lock);
604    usb->next = &handle_list;
605    usb->prev = handle_list.prev;
606    usb->prev->next = usb;
607    usb->next->prev = usb;
608    adb_mutex_unlock(&usb_lock);
609
610    register_usb_transport(usb, serial);
611    return;
612
613fail:
614    D("[ usb open %s error=%d, err_str = %s]\n",
615        usb->fname,  errno, strerror(errno));
616    if(usb->desc >= 0) {
617        adb_close(usb->desc);
618    }
619    free(usb);
620}
621
622void* device_poll_thread(void* unused)
623{
624    D("Created device thread\n");
625    for(;;) {
626            /* XXX use inotify */
627        find_usb_device("/dev/bus/usb", register_device);
628        kick_disconnected_devices();
629        sleep(1);
630    }
631    return NULL;
632}
633
634static void sigalrm_handler(int signo)
635{
636    // don't need to do anything here
637}
638
639void usb_init()
640{
641    adb_thread_t tid;
642    struct sigaction    actions;
643
644    memset(&actions, 0, sizeof(actions));
645    sigemptyset(&actions.sa_mask);
646    actions.sa_flags = 0;
647    actions.sa_handler = sigalrm_handler;
648    sigaction(SIGALRM,& actions, NULL);
649
650    if(adb_thread_create(&tid, device_poll_thread, NULL)){
651        fatal_errno("cannot create input thread");
652    }
653}
654
655