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
48static adb_mutex_t usb_lock = ADB_MUTEX_INITIALIZER;
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, unsigned char ep_in, unsigned char ep_out,
120                            int ifc, int serial_index, unsigned zero_mask);
121
122static inline int badname(const char *name)
123{
124    while(*name) {
125        if(!isdigit(*name++)) return 1;
126    }
127    return 0;
128}
129
130static void find_usb_device(const char *base,
131        void (*register_device_callback)
132                (const char *, unsigned char, unsigned char, int, int, unsigned))
133{
134    char busname[32], devname[32];
135    unsigned char local_ep_in, local_ep_out;
136    DIR *busdir , *devdir ;
137    struct dirent *de;
138    int fd ;
139
140    busdir = opendir(base);
141    if(busdir == 0) return;
142
143    while((de = readdir(busdir)) != 0) {
144        if(badname(de->d_name)) continue;
145
146        snprintf(busname, sizeof busname, "%s/%s", base, de->d_name);
147        devdir = opendir(busname);
148        if(devdir == 0) continue;
149
150//        DBGX("[ scanning %s ]\n", busname);
151        while((de = readdir(devdir))) {
152            unsigned char devdesc[256];
153            unsigned char* bufptr = devdesc;
154            unsigned char* bufend;
155            struct usb_device_descriptor* device;
156            struct usb_config_descriptor* config;
157            struct usb_interface_descriptor* interface;
158            struct usb_endpoint_descriptor *ep1, *ep2;
159            unsigned zero_mask = 0;
160            unsigned vid, pid;
161            size_t desclength;
162
163            if(badname(de->d_name)) continue;
164            snprintf(devname, sizeof devname, "%s/%s", busname, de->d_name);
165
166            if(known_device(devname)) {
167                DBGX("skipping %s\n", devname);
168                continue;
169            }
170
171//            DBGX("[ scanning %s ]\n", devname);
172            if((fd = unix_open(devname, O_RDONLY)) < 0) {
173                continue;
174            }
175
176            desclength = adb_read(fd, devdesc, sizeof(devdesc));
177            bufend = bufptr + desclength;
178
179                // should have device and configuration descriptors, and atleast two endpoints
180            if (desclength < USB_DT_DEVICE_SIZE + USB_DT_CONFIG_SIZE) {
181                D("desclength %d is too small\n", desclength);
182                adb_close(fd);
183                continue;
184            }
185
186            device = (struct usb_device_descriptor*)bufptr;
187            bufptr += USB_DT_DEVICE_SIZE;
188
189            if((device->bLength != USB_DT_DEVICE_SIZE) || (device->bDescriptorType != USB_DT_DEVICE)) {
190                adb_close(fd);
191                continue;
192            }
193
194            vid = __le16_to_cpu(device->idVendor);
195            pid = __le16_to_cpu(device->idProduct);
196            pid = devdesc[10] | (devdesc[11] << 8);
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                        DBGX("looking for bulk endpoints\n");
232                            // looks like ADB...
233                        ep1 = (struct usb_endpoint_descriptor *)bufptr;
234                        bufptr += USB_DT_ENDPOINT_SIZE;
235                        ep2 = (struct usb_endpoint_descriptor *)bufptr;
236                        bufptr += USB_DT_ENDPOINT_SIZE;
237
238                        if (bufptr > devdesc + desclength ||
239                            ep1->bLength != USB_DT_ENDPOINT_SIZE ||
240                            ep1->bDescriptorType != USB_DT_ENDPOINT ||
241                            ep2->bLength != USB_DT_ENDPOINT_SIZE ||
242                            ep2->bDescriptorType != USB_DT_ENDPOINT) {
243                            D("endpoints not found\n");
244                            break;
245                        }
246
247                            // both endpoints should be bulk
248                        if (ep1->bmAttributes != USB_ENDPOINT_XFER_BULK ||
249                            ep2->bmAttributes != USB_ENDPOINT_XFER_BULK) {
250                            D("bulk endpoints not found\n");
251                            continue;
252                        }
253                            /* aproto 01 needs 0 termination */
254                        if(interface->bInterfaceProtocol == 0x01) {
255                            zero_mask = ep1->wMaxPacketSize - 1;
256                        }
257
258                            // we have a match.  now we just need to figure out which is in and which is out.
259                        if (ep1->bEndpointAddress & USB_ENDPOINT_DIR_MASK) {
260                            local_ep_in = ep1->bEndpointAddress;
261                            local_ep_out = ep2->bEndpointAddress;
262                        } else {
263                            local_ep_in = ep2->bEndpointAddress;
264                            local_ep_out = ep1->bEndpointAddress;
265                        }
266
267                        register_device_callback(devname, local_ep_in, local_ep_out,
268                                interface->bInterfaceNumber, device->iSerialNumber, zero_mask);
269                        break;
270                    }
271                } else {
272                    bufptr += length;
273                }
274            } // end of while
275
276            adb_close(fd);
277        } // end of devdir while
278        closedir(devdir);
279    } //end of busdir while
280    closedir(busdir);
281}
282
283void usb_cleanup()
284{
285}
286
287static 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    struct timeval tv;
292    struct timespec ts;
293
294    memset(urb, 0, sizeof(*urb));
295    urb->type = USBDEVFS_URB_TYPE_BULK;
296    urb->endpoint = h->ep_out;
297    urb->status = -1;
298    urb->buffer = (void*) data;
299    urb->buffer_length = len;
300
301    D("++ write ++\n");
302
303    adb_mutex_lock(&h->lock);
304    if(h->dead) {
305        res = -1;
306        goto fail;
307    }
308    do {
309        res = ioctl(h->desc, USBDEVFS_SUBMITURB, urb);
310    } while((res < 0) && (errno == EINTR));
311
312    if(res < 0) {
313        goto fail;
314    }
315
316    res = -1;
317    h->urb_out_busy = 1;
318    for(;;) {
319        /* time out after five seconds */
320        gettimeofday(&tv, NULL);
321        ts.tv_sec = tv.tv_sec + 5;
322        ts.tv_nsec = tv.tv_usec * 1000L;
323        res = pthread_cond_timedwait(&h->notify, &h->lock, &ts);
324        if(res < 0 || h->dead) {
325            break;
326        }
327        if(h->urb_out_busy == 0) {
328            if(urb->status == 0) {
329                res = urb->actual_length;
330            }
331            break;
332        }
333    }
334fail:
335    adb_mutex_unlock(&h->lock);
336    D("-- write --\n");
337    return res;
338}
339
340static int usb_bulk_read(usb_handle *h, void *data, int len)
341{
342    struct usbdevfs_urb *urb = &h->urb_in;
343    struct usbdevfs_urb *out = NULL;
344    int res;
345
346    memset(urb, 0, sizeof(*urb));
347    urb->type = USBDEVFS_URB_TYPE_BULK;
348    urb->endpoint = h->ep_in;
349    urb->status = -1;
350    urb->buffer = data;
351    urb->buffer_length = len;
352
353
354    adb_mutex_lock(&h->lock);
355    if(h->dead) {
356        res = -1;
357        goto fail;
358    }
359    do {
360        res = ioctl(h->desc, USBDEVFS_SUBMITURB, urb);
361    } while((res < 0) && (errno == EINTR));
362
363    if(res < 0) {
364        goto fail;
365    }
366
367    h->urb_in_busy = 1;
368    for(;;) {
369        D("[ reap urb - wait ]\n");
370        h->reaper_thread = pthread_self();
371        adb_mutex_unlock(&h->lock);
372        res = ioctl(h->desc, USBDEVFS_REAPURB, &out);
373        adb_mutex_lock(&h->lock);
374        h->reaper_thread = 0;
375        if(h->dead) {
376            res = -1;
377            break;
378        }
379        if(res < 0) {
380            if(errno == EINTR) {
381                continue;
382            }
383            D("[ reap urb - error ]\n");
384            break;
385        }
386        D("[ urb @%p status = %d, actual = %d ]\n",
387            out, out->status, out->actual_length);
388
389        if(out == &h->urb_in) {
390            D("[ reap urb - IN complete ]\n");
391            h->urb_in_busy = 0;
392            if(urb->status == 0) {
393                res = urb->actual_length;
394            } else {
395                res = -1;
396            }
397            break;
398        }
399        if(out == &h->urb_out) {
400            D("[ reap urb - OUT compelete ]\n");
401            h->urb_out_busy = 0;
402            adb_cond_broadcast(&h->notify);
403        }
404    }
405fail:
406    adb_mutex_unlock(&h->lock);
407    return res;
408}
409
410
411int usb_write(usb_handle *h, const void *_data, int len)
412{
413    unsigned char *data = (unsigned char*) _data;
414    int n;
415    int need_zero = 0;
416
417    if(h->zero_mask) {
418            /* if we need 0-markers and our transfer
419            ** is an even multiple of the packet size,
420            ** we make note of it
421            */
422        if(!(len & h->zero_mask)) {
423            need_zero = 1;
424        }
425    }
426
427    while(len > 0) {
428        int xfer = (len > 4096) ? 4096 : len;
429
430        n = usb_bulk_write(h, data, xfer);
431        if(n != xfer) {
432            D("ERROR: n = %d, errno = %d (%s)\n",
433                n, errno, strerror(errno));
434            return -1;
435        }
436
437        len -= xfer;
438        data += xfer;
439    }
440
441    if(need_zero){
442        n = usb_bulk_write(h, _data, 0);
443        return n;
444    }
445
446    return 0;
447}
448
449int usb_read(usb_handle *h, void *_data, int len)
450{
451    unsigned char *data = (unsigned char*) _data;
452    int n;
453
454    D("++ usb_read ++\n");
455    while(len > 0) {
456        int xfer = (len > 4096) ? 4096 : len;
457
458        D("[ usb read %d fd = %d], fname=%s\n", xfer, h->desc, h->fname);
459        n = usb_bulk_read(h, data, xfer);
460        D("[ usb read %d ] = %d, fname=%s\n", xfer, n, h->fname);
461        if(n != xfer) {
462            if((errno == ETIMEDOUT) && (h->desc != -1)) {
463                D("[ timeout ]\n");
464                if(n > 0){
465                    data += n;
466                    len -= n;
467                }
468                continue;
469            }
470            D("ERROR: n = %d, errno = %d (%s)\n",
471                n, errno, strerror(errno));
472            return -1;
473        }
474
475        len -= xfer;
476        data += xfer;
477    }
478
479    D("-- usb_read --\n");
480    return 0;
481}
482
483void usb_kick(usb_handle *h)
484{
485    D("[ kicking %p (fd = %d) ]\n", h, h->desc);
486    adb_mutex_lock(&h->lock);
487    if(h->dead == 0) {
488        h->dead = 1;
489
490        if (h->writeable) {
491            /* HACK ALERT!
492            ** Sometimes we get stuck in ioctl(USBDEVFS_REAPURB).
493            ** This is a workaround for that problem.
494            */
495            if (h->reaper_thread) {
496                pthread_kill(h->reaper_thread, SIGALRM);
497            }
498
499            /* cancel any pending transactions
500            ** these will quietly fail if the txns are not active,
501            ** but this ensures that a reader blocked on REAPURB
502            ** will get unblocked
503            */
504            ioctl(h->desc, USBDEVFS_DISCARDURB, &h->urb_in);
505            ioctl(h->desc, USBDEVFS_DISCARDURB, &h->urb_out);
506            h->urb_in.status = -ENODEV;
507            h->urb_out.status = -ENODEV;
508            h->urb_in_busy = 0;
509            h->urb_out_busy = 0;
510            adb_cond_broadcast(&h->notify);
511        } else {
512            unregister_usb_transport(h);
513        }
514    }
515    adb_mutex_unlock(&h->lock);
516}
517
518int usb_close(usb_handle *h)
519{
520    D("[ usb close ... ]\n");
521    adb_mutex_lock(&usb_lock);
522    h->next->prev = h->prev;
523    h->prev->next = h->next;
524    h->prev = 0;
525    h->next = 0;
526
527    adb_close(h->desc);
528    D("[ usb closed %p (fd = %d) ]\n", h, h->desc);
529    adb_mutex_unlock(&usb_lock);
530
531    free(h);
532    return 0;
533}
534
535static void register_device(const char *dev_name,
536                            unsigned char ep_in, unsigned char ep_out,
537                            int interface, int serial_index, unsigned zero_mask)
538{
539    usb_handle* usb = 0;
540    int n = 0;
541    char serial[256];
542
543        /* Since Linux will not reassign the device ID (and dev_name)
544        ** as long as the device is open, we can add to the list here
545        ** once we open it and remove from the list when we're finally
546        ** closed and everything will work out fine.
547        **
548        ** If we have a usb_handle on the list 'o handles with a matching
549        ** name, we have no further work to do.
550        */
551    adb_mutex_lock(&usb_lock);
552    for(usb = handle_list.next; usb != &handle_list; usb = usb->next){
553        if(!strcmp(usb->fname, dev_name)) {
554            adb_mutex_unlock(&usb_lock);
555            return;
556        }
557    }
558    adb_mutex_unlock(&usb_lock);
559
560    D("[ usb located new device %s (%d/%d/%d) ]\n",
561        dev_name, ep_in, ep_out, interface);
562    usb = calloc(1, sizeof(usb_handle));
563    strcpy(usb->fname, dev_name);
564    usb->ep_in = ep_in;
565    usb->ep_out = ep_out;
566    usb->zero_mask = zero_mask;
567    usb->writeable = 1;
568
569    adb_cond_init(&usb->notify, 0);
570    adb_mutex_init(&usb->lock, 0);
571    /* initialize mark to 1 so we don't get garbage collected after the device scan */
572    usb->mark = 1;
573    usb->reaper_thread = 0;
574
575    usb->desc = unix_open(usb->fname, O_RDWR);
576    if(usb->desc < 0) {
577        /* if we fail, see if have read-only access */
578        usb->desc = unix_open(usb->fname, O_RDONLY);
579        if(usb->desc < 0) goto fail;
580        usb->writeable = 0;
581        D("[ usb open read-only %s fd = %d]\n", usb->fname, usb->desc);
582    } else {
583        D("[ usb open %s fd = %d]\n", usb->fname, usb->desc);
584        n = ioctl(usb->desc, USBDEVFS_CLAIMINTERFACE, &interface);
585        if(n != 0) goto fail;
586    }
587
588        /* read the device's serial number */
589    serial[0] = 0;
590    memset(serial, 0, sizeof(serial));
591    if (serial_index) {
592        struct usbdevfs_ctrltransfer  ctrl;
593        __u16 buffer[128];
594        __u16 languages[128];
595        int i, result;
596        int languageCount = 0;
597
598        memset(languages, 0, sizeof(languages));
599        memset(&ctrl, 0, sizeof(ctrl));
600
601            // read list of supported languages
602        ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE;
603        ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
604        ctrl.wValue = (USB_DT_STRING << 8) | 0;
605        ctrl.wIndex = 0;
606        ctrl.wLength = sizeof(languages);
607        ctrl.data = languages;
608
609        result = ioctl(usb->desc, USBDEVFS_CONTROL, &ctrl);
610        if (result > 0)
611            languageCount = (result - 2) / 2;
612
613        for (i = 1; i <= languageCount; i++) {
614            memset(buffer, 0, sizeof(buffer));
615            memset(&ctrl, 0, sizeof(ctrl));
616
617            ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE;
618            ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
619            ctrl.wValue = (USB_DT_STRING << 8) | serial_index;
620            ctrl.wIndex = languages[i];
621            ctrl.wLength = sizeof(buffer);
622            ctrl.data = buffer;
623
624            result = ioctl(usb->desc, USBDEVFS_CONTROL, &ctrl);
625            if (result > 0) {
626                int i;
627                // skip first word, and copy the rest to the serial string, changing shorts to bytes.
628                result /= 2;
629                for (i = 1; i < result; i++)
630                    serial[i - 1] = buffer[i];
631                serial[i - 1] = 0;
632                break;
633            }
634        }
635    }
636
637        /* add to the end of the active handles */
638    adb_mutex_lock(&usb_lock);
639    usb->next = &handle_list;
640    usb->prev = handle_list.prev;
641    usb->prev->next = usb;
642    usb->next->prev = usb;
643    adb_mutex_unlock(&usb_lock);
644
645    register_usb_transport(usb, serial, usb->writeable);
646    return;
647
648fail:
649    D("[ usb open %s error=%d, err_str = %s]\n",
650        usb->fname,  errno, strerror(errno));
651    if(usb->desc >= 0) {
652        adb_close(usb->desc);
653    }
654    free(usb);
655}
656
657void* device_poll_thread(void* unused)
658{
659    D("Created device thread\n");
660    for(;;) {
661            /* XXX use inotify */
662        find_usb_device("/dev/bus/usb", register_device);
663        kick_disconnected_devices();
664        sleep(1);
665    }
666    return NULL;
667}
668
669static void sigalrm_handler(int signo)
670{
671    // don't need to do anything here
672}
673
674void usb_init()
675{
676    adb_thread_t tid;
677    struct sigaction    actions;
678
679    memset(&actions, 0, sizeof(actions));
680    sigemptyset(&actions.sa_mask);
681    actions.sa_flags = 0;
682    actions.sa_handler = sigalrm_handler;
683    sigaction(SIGALRM,& actions, NULL);
684
685    if(adb_thread_create(&tid, device_poll_thread, NULL)){
686        fatal_errno("cannot create input thread");
687    }
688}
689
690