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, 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[4096];
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 = device->idVendor;
195            pid = device->idProduct;
196            DBGX("[ %s is V:%04x P:%04x ]\n", devname, vid, pid);
197
198                // should have config descriptor next
199            config = (struct usb_config_descriptor *)bufptr;
200            bufptr += USB_DT_CONFIG_SIZE;
201            if (config->bLength != USB_DT_CONFIG_SIZE || config->bDescriptorType != USB_DT_CONFIG) {
202                D("usb_config_descriptor not found\n");
203                adb_close(fd);
204                continue;
205            }
206
207                // loop through all the descriptors and look for the ADB interface
208            while (bufptr < bufend) {
209                unsigned char length = bufptr[0];
210                unsigned char type = bufptr[1];
211
212                if (type == USB_DT_INTERFACE) {
213                    interface = (struct usb_interface_descriptor *)bufptr;
214                    bufptr += length;
215
216                    if (length != USB_DT_INTERFACE_SIZE) {
217                        D("interface descriptor has wrong size\n");
218                        break;
219                    }
220
221                    DBGX("bInterfaceClass: %d,  bInterfaceSubClass: %d,"
222                         "bInterfaceProtocol: %d, bNumEndpoints: %d\n",
223                         interface->bInterfaceClass, interface->bInterfaceSubClass,
224                         interface->bInterfaceProtocol, interface->bNumEndpoints);
225
226                    if (interface->bNumEndpoints == 2 &&
227                            is_adb_interface(vid, pid, interface->bInterfaceClass,
228                            interface->bInterfaceSubClass, interface->bInterfaceProtocol))  {
229
230                        DBGX("looking for bulk endpoints\n");
231                            // looks like ADB...
232                        ep1 = (struct usb_endpoint_descriptor *)bufptr;
233                        bufptr += USB_DT_ENDPOINT_SIZE;
234                        ep2 = (struct usb_endpoint_descriptor *)bufptr;
235                        bufptr += USB_DT_ENDPOINT_SIZE;
236
237                        if (bufptr > devdesc + desclength ||
238                            ep1->bLength != USB_DT_ENDPOINT_SIZE ||
239                            ep1->bDescriptorType != USB_DT_ENDPOINT ||
240                            ep2->bLength != USB_DT_ENDPOINT_SIZE ||
241                            ep2->bDescriptorType != USB_DT_ENDPOINT) {
242                            D("endpoints not found\n");
243                            break;
244                        }
245
246                            // both endpoints should be bulk
247                        if (ep1->bmAttributes != USB_ENDPOINT_XFER_BULK ||
248                            ep2->bmAttributes != USB_ENDPOINT_XFER_BULK) {
249                            D("bulk endpoints not found\n");
250                            continue;
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                        break;
269                    }
270                } else {
271                    bufptr += length;
272                }
273            } // end of while
274
275            adb_close(fd);
276        } // end of devdir while
277        closedir(devdir);
278    } //end of busdir while
279    closedir(busdir);
280}
281
282void usb_cleanup()
283{
284}
285
286static int usb_bulk_write(usb_handle *h, const void *data, int len)
287{
288    struct usbdevfs_urb *urb = &h->urb_out;
289    int res;
290    struct timeval tv;
291    struct timespec ts;
292
293    memset(urb, 0, sizeof(*urb));
294    urb->type = USBDEVFS_URB_TYPE_BULK;
295    urb->endpoint = h->ep_out;
296    urb->status = -1;
297    urb->buffer = (void*) data;
298    urb->buffer_length = len;
299
300    D("++ write ++\n");
301
302    adb_mutex_lock(&h->lock);
303    if(h->dead) {
304        res = -1;
305        goto fail;
306    }
307    do {
308        res = ioctl(h->desc, USBDEVFS_SUBMITURB, urb);
309    } while((res < 0) && (errno == EINTR));
310
311    if(res < 0) {
312        goto fail;
313    }
314
315    res = -1;
316    h->urb_out_busy = 1;
317    for(;;) {
318        /* time out after five seconds */
319        gettimeofday(&tv, NULL);
320        ts.tv_sec = tv.tv_sec + 5;
321        ts.tv_nsec = tv.tv_usec * 1000L;
322        res = pthread_cond_timedwait(&h->notify, &h->lock, &ts);
323        if(res < 0 || h->dead) {
324            break;
325        }
326        if(h->urb_out_busy == 0) {
327            if(urb->status == 0) {
328                res = urb->actual_length;
329            }
330            break;
331        }
332    }
333fail:
334    adb_mutex_unlock(&h->lock);
335    D("-- write --\n");
336    return res;
337}
338
339static int usb_bulk_read(usb_handle *h, void *data, int len)
340{
341    struct usbdevfs_urb *urb = &h->urb_in;
342    struct usbdevfs_urb *out = NULL;
343    int res;
344
345    memset(urb, 0, sizeof(*urb));
346    urb->type = USBDEVFS_URB_TYPE_BULK;
347    urb->endpoint = h->ep_in;
348    urb->status = -1;
349    urb->buffer = data;
350    urb->buffer_length = len;
351
352
353    adb_mutex_lock(&h->lock);
354    if(h->dead) {
355        res = -1;
356        goto fail;
357    }
358    do {
359        res = ioctl(h->desc, USBDEVFS_SUBMITURB, urb);
360    } while((res < 0) && (errno == EINTR));
361
362    if(res < 0) {
363        goto fail;
364    }
365
366    h->urb_in_busy = 1;
367    for(;;) {
368        D("[ reap urb - wait ]\n");
369        h->reaper_thread = pthread_self();
370        adb_mutex_unlock(&h->lock);
371        res = ioctl(h->desc, USBDEVFS_REAPURB, &out);
372        int saved_errno = errno;
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(saved_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        ctrl.timeout = 1000;
609
610        result = ioctl(usb->desc, USBDEVFS_CONTROL, &ctrl);
611        if (result > 0)
612            languageCount = (result - 2) / 2;
613
614        for (i = 1; i <= languageCount; i++) {
615            memset(buffer, 0, sizeof(buffer));
616            memset(&ctrl, 0, sizeof(ctrl));
617
618            ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE;
619            ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
620            ctrl.wValue = (USB_DT_STRING << 8) | serial_index;
621            ctrl.wIndex = __le16_to_cpu(languages[i]);
622            ctrl.wLength = sizeof(buffer);
623            ctrl.data = buffer;
624            ctrl.timeout = 1000;
625
626            result = ioctl(usb->desc, USBDEVFS_CONTROL, &ctrl);
627            if (result > 0) {
628                int i;
629                // skip first word, and copy the rest to the serial string, changing shorts to bytes.
630                result /= 2;
631                for (i = 1; i < result; i++)
632                    serial[i - 1] = __le16_to_cpu(buffer[i]);
633                serial[i - 1] = 0;
634                break;
635            }
636        }
637    }
638
639        /* add to the end of the active handles */
640    adb_mutex_lock(&usb_lock);
641    usb->next = &handle_list;
642    usb->prev = handle_list.prev;
643    usb->prev->next = usb;
644    usb->next->prev = usb;
645    adb_mutex_unlock(&usb_lock);
646
647    register_usb_transport(usb, serial, usb->writeable);
648    return;
649
650fail:
651    D("[ usb open %s error=%d, err_str = %s]\n",
652        usb->fname,  errno, strerror(errno));
653    if(usb->desc >= 0) {
654        adb_close(usb->desc);
655    }
656    free(usb);
657}
658
659void* device_poll_thread(void* unused)
660{
661    D("Created device thread\n");
662    for(;;) {
663            /* XXX use inotify */
664        find_usb_device("/dev/bus/usb", register_device);
665        kick_disconnected_devices();
666        sleep(1);
667    }
668    return NULL;
669}
670
671static void sigalrm_handler(int signo)
672{
673    // don't need to do anything here
674}
675
676void usb_init()
677{
678    adb_thread_t tid;
679    struct sigaction    actions;
680
681    memset(&actions, 0, sizeof(actions));
682    sigemptyset(&actions.sa_mask);
683    actions.sa_flags = 0;
684    actions.sa_handler = sigalrm_handler;
685    sigaction(SIGALRM,& actions, NULL);
686
687    if(adb_thread_create(&tid, device_poll_thread, NULL)){
688        fatal_errno("cannot create input thread");
689    }
690}
691