Home | History | Annotate | Download | only in client
      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 #define TRACE_TAG USB
     18 
     19 #include "sysdeps.h"
     20 
     21 #include <ctype.h>
     22 #include <dirent.h>
     23 #include <errno.h>
     24 #include <fcntl.h>
     25 #include <linux/usb/ch9.h>
     26 #include <linux/usbdevice_fs.h>
     27 #include <linux/version.h>
     28 #include <stdio.h>
     29 #include <stdlib.h>
     30 #include <string.h>
     31 #include <sys/ioctl.h>
     32 #include <sys/time.h>
     33 #include <sys/types.h>
     34 #include <unistd.h>
     35 
     36 #include <chrono>
     37 #include <condition_variable>
     38 #include <list>
     39 #include <mutex>
     40 #include <string>
     41 #include <thread>
     42 
     43 #include <android-base/file.h>
     44 #include <android-base/stringprintf.h>
     45 #include <android-base/strings.h>
     46 
     47 #include "adb.h"
     48 #include "transport.h"
     49 #include "usb.h"
     50 
     51 using namespace std::chrono_literals;
     52 using namespace std::literals;
     53 
     54 /* usb scan debugging is waaaay too verbose */
     55 #define DBGX(x...)
     56 
     57 namespace native {
     58 struct usb_handle : public ::usb_handle {
     59     ~usb_handle() {
     60       if (fd != -1) unix_close(fd);
     61     }
     62 
     63     std::string path;
     64     int fd = -1;
     65     unsigned char ep_in;
     66     unsigned char ep_out;
     67 
     68     size_t max_packet_size;
     69     unsigned zero_mask;
     70     unsigned writeable = 1;
     71 
     72     usbdevfs_urb urb_in;
     73     usbdevfs_urb urb_out;
     74 
     75     bool urb_in_busy = false;
     76     bool urb_out_busy = false;
     77     bool dead = false;
     78 
     79     std::condition_variable cv;
     80     std::mutex mutex;
     81 
     82     // for garbage collecting disconnected devices
     83     bool mark;
     84 
     85     // ID of thread currently in REAPURB
     86     pthread_t reaper_thread = 0;
     87 };
     88 
     89 static auto& g_usb_handles_mutex = *new std::mutex();
     90 static auto& g_usb_handles = *new std::list<usb_handle*>();
     91 
     92 static int is_known_device(const char* dev_name) {
     93     std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
     94     for (usb_handle* usb : g_usb_handles) {
     95         if (usb->path == dev_name) {
     96             // set mark flag to indicate this device is still alive
     97             usb->mark = true;
     98             return 1;
     99         }
    100     }
    101     return 0;
    102 }
    103 
    104 static void kick_disconnected_devices() {
    105     std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
    106     // kick any devices in the device list that were not found in the device scan
    107     for (usb_handle* usb : g_usb_handles) {
    108         if (!usb->mark) {
    109             usb_kick(usb);
    110         } else {
    111             usb->mark = false;
    112         }
    113     }
    114 }
    115 
    116 static inline bool contains_non_digit(const char* name) {
    117     while (*name) {
    118         if (!isdigit(*name++)) return true;
    119     }
    120     return false;
    121 }
    122 
    123 static void find_usb_device(const std::string& base,
    124                             void (*register_device_callback)(const char*, const char*,
    125                                                              unsigned char, unsigned char, int, int,
    126                                                              unsigned, size_t)) {
    127     std::unique_ptr<DIR, int(*)(DIR*)> bus_dir(opendir(base.c_str()), closedir);
    128     if (!bus_dir) return;
    129 
    130     dirent* de;
    131     while ((de = readdir(bus_dir.get())) != 0) {
    132         if (contains_non_digit(de->d_name)) continue;
    133 
    134         std::string bus_name = base + "/" + de->d_name;
    135 
    136         std::unique_ptr<DIR, int(*)(DIR*)> dev_dir(opendir(bus_name.c_str()), closedir);
    137         if (!dev_dir) continue;
    138 
    139         while ((de = readdir(dev_dir.get()))) {
    140             unsigned char devdesc[4096];
    141             unsigned char* bufptr = devdesc;
    142             unsigned char* bufend;
    143             struct usb_device_descriptor* device;
    144             struct usb_config_descriptor* config;
    145             struct usb_interface_descriptor* interface;
    146             struct usb_endpoint_descriptor *ep1, *ep2;
    147             unsigned zero_mask = 0;
    148             size_t max_packet_size = 0;
    149             unsigned vid, pid;
    150 
    151             if (contains_non_digit(de->d_name)) continue;
    152 
    153             std::string dev_name = bus_name + "/" + de->d_name;
    154             if (is_known_device(dev_name.c_str())) {
    155                 continue;
    156             }
    157 
    158             int fd = unix_open(dev_name.c_str(), O_RDONLY | O_CLOEXEC);
    159             if (fd == -1) {
    160                 continue;
    161             }
    162 
    163             size_t desclength = unix_read(fd, devdesc, sizeof(devdesc));
    164             bufend = bufptr + desclength;
    165 
    166                 // should have device and configuration descriptors, and atleast two endpoints
    167             if (desclength < USB_DT_DEVICE_SIZE + USB_DT_CONFIG_SIZE) {
    168                 D("desclength %zu is too small", desclength);
    169                 unix_close(fd);
    170                 continue;
    171             }
    172 
    173             device = (struct usb_device_descriptor*)bufptr;
    174             bufptr += USB_DT_DEVICE_SIZE;
    175 
    176             if((device->bLength != USB_DT_DEVICE_SIZE) || (device->bDescriptorType != USB_DT_DEVICE)) {
    177                 unix_close(fd);
    178                 continue;
    179             }
    180 
    181             vid = device->idVendor;
    182             pid = device->idProduct;
    183             DBGX("[ %s is V:%04x P:%04x ]\n", dev_name.c_str(), vid, pid);
    184 
    185                 // should have config descriptor next
    186             config = (struct usb_config_descriptor *)bufptr;
    187             bufptr += USB_DT_CONFIG_SIZE;
    188             if (config->bLength != USB_DT_CONFIG_SIZE || config->bDescriptorType != USB_DT_CONFIG) {
    189                 D("usb_config_descriptor not found");
    190                 unix_close(fd);
    191                 continue;
    192             }
    193 
    194                 // loop through all the descriptors and look for the ADB interface
    195             while (bufptr < bufend) {
    196                 unsigned char length = bufptr[0];
    197                 unsigned char type = bufptr[1];
    198 
    199                 if (type == USB_DT_INTERFACE) {
    200                     interface = (struct usb_interface_descriptor *)bufptr;
    201                     bufptr += length;
    202 
    203                     if (length != USB_DT_INTERFACE_SIZE) {
    204                         D("interface descriptor has wrong size");
    205                         break;
    206                     }
    207 
    208                     DBGX("bInterfaceClass: %d,  bInterfaceSubClass: %d,"
    209                          "bInterfaceProtocol: %d, bNumEndpoints: %d\n",
    210                          interface->bInterfaceClass, interface->bInterfaceSubClass,
    211                          interface->bInterfaceProtocol, interface->bNumEndpoints);
    212 
    213                     if (interface->bNumEndpoints == 2 &&
    214                         is_adb_interface(interface->bInterfaceClass, interface->bInterfaceSubClass,
    215                                          interface->bInterfaceProtocol)) {
    216                         struct stat st;
    217                         char pathbuf[128];
    218                         char link[256];
    219                         char *devpath = nullptr;
    220 
    221                         DBGX("looking for bulk endpoints\n");
    222                             // looks like ADB...
    223                         ep1 = (struct usb_endpoint_descriptor *)bufptr;
    224                         bufptr += USB_DT_ENDPOINT_SIZE;
    225                             // For USB 3.0 SuperSpeed devices, skip potential
    226                             // USB 3.0 SuperSpeed Endpoint Companion descriptor
    227                         if (bufptr+2 <= devdesc + desclength &&
    228                             bufptr[0] == USB_DT_SS_EP_COMP_SIZE &&
    229                             bufptr[1] == USB_DT_SS_ENDPOINT_COMP) {
    230                             bufptr += USB_DT_SS_EP_COMP_SIZE;
    231                         }
    232                         ep2 = (struct usb_endpoint_descriptor *)bufptr;
    233                         bufptr += USB_DT_ENDPOINT_SIZE;
    234                         if (bufptr+2 <= devdesc + desclength &&
    235                             bufptr[0] == USB_DT_SS_EP_COMP_SIZE &&
    236                             bufptr[1] == USB_DT_SS_ENDPOINT_COMP) {
    237                             bufptr += USB_DT_SS_EP_COMP_SIZE;
    238                         }
    239 
    240                         if (bufptr > devdesc + desclength ||
    241                             ep1->bLength != USB_DT_ENDPOINT_SIZE ||
    242                             ep1->bDescriptorType != USB_DT_ENDPOINT ||
    243                             ep2->bLength != USB_DT_ENDPOINT_SIZE ||
    244                             ep2->bDescriptorType != USB_DT_ENDPOINT) {
    245                             D("endpoints not found");
    246                             break;
    247                         }
    248 
    249                             // both endpoints should be bulk
    250                         if (ep1->bmAttributes != USB_ENDPOINT_XFER_BULK ||
    251                             ep2->bmAttributes != USB_ENDPOINT_XFER_BULK) {
    252                             D("bulk endpoints not found");
    253                             continue;
    254                         }
    255                             /* aproto 01 needs 0 termination */
    256                         if (interface->bInterfaceProtocol == ADB_PROTOCOL) {
    257                             max_packet_size = ep1->wMaxPacketSize;
    258                             zero_mask = ep1->wMaxPacketSize - 1;
    259                         }
    260 
    261                             // we have a match.  now we just need to figure out which is in and which is out.
    262                         unsigned char local_ep_in, local_ep_out;
    263                         if (ep1->bEndpointAddress & USB_ENDPOINT_DIR_MASK) {
    264                             local_ep_in = ep1->bEndpointAddress;
    265                             local_ep_out = ep2->bEndpointAddress;
    266                         } else {
    267                             local_ep_in = ep2->bEndpointAddress;
    268                             local_ep_out = ep1->bEndpointAddress;
    269                         }
    270 
    271                             // Determine the device path
    272                         if (!fstat(fd, &st) && S_ISCHR(st.st_mode)) {
    273                             snprintf(pathbuf, sizeof(pathbuf), "/sys/dev/char/%d:%d",
    274                                      major(st.st_rdev), minor(st.st_rdev));
    275                             ssize_t link_len = readlink(pathbuf, link, sizeof(link) - 1);
    276                             if (link_len > 0) {
    277                                 link[link_len] = '\0';
    278                                 const char* slash = strrchr(link, '/');
    279                                 if (slash) {
    280                                     snprintf(pathbuf, sizeof(pathbuf),
    281                                              "usb:%s", slash + 1);
    282                                     devpath = pathbuf;
    283                                 }
    284                             }
    285                         }
    286 
    287                         register_device_callback(dev_name.c_str(), devpath, local_ep_in,
    288                                                  local_ep_out, interface->bInterfaceNumber,
    289                                                  device->iSerialNumber, zero_mask, max_packet_size);
    290                         break;
    291                     }
    292                 } else {
    293                     bufptr += length;
    294                 }
    295             } // end of while
    296 
    297             unix_close(fd);
    298         }
    299     }
    300 }
    301 
    302 static int usb_bulk_write(usb_handle* h, const void* data, int len) {
    303     std::unique_lock<std::mutex> lock(h->mutex);
    304     D("++ usb_bulk_write ++");
    305 
    306     usbdevfs_urb* urb = &h->urb_out;
    307     memset(urb, 0, sizeof(*urb));
    308     urb->type = USBDEVFS_URB_TYPE_BULK;
    309     urb->endpoint = h->ep_out;
    310     urb->status = -1;
    311     urb->buffer = const_cast<void*>(data);
    312     urb->buffer_length = len;
    313 
    314     if (h->dead) {
    315         errno = EINVAL;
    316         return -1;
    317     }
    318 
    319     if (TEMP_FAILURE_RETRY(ioctl(h->fd, USBDEVFS_SUBMITURB, urb)) == -1) {
    320         return -1;
    321     }
    322 
    323     h->urb_out_busy = true;
    324     while (true) {
    325         auto now = std::chrono::system_clock::now();
    326         if (h->cv.wait_until(lock, now + 5s) == std::cv_status::timeout || h->dead) {
    327             // TODO: call USBDEVFS_DISCARDURB?
    328             errno = ETIMEDOUT;
    329             return -1;
    330         }
    331         if (!h->urb_out_busy) {
    332             if (urb->status != 0) {
    333                 errno = -urb->status;
    334                 return -1;
    335             }
    336             return urb->actual_length;
    337         }
    338     }
    339 }
    340 
    341 static int usb_bulk_read(usb_handle* h, void* data, int len) {
    342     std::unique_lock<std::mutex> lock(h->mutex);
    343     D("++ usb_bulk_read ++");
    344 
    345     usbdevfs_urb* urb = &h->urb_in;
    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     if (h->dead) {
    354         errno = EINVAL;
    355         return -1;
    356     }
    357 
    358     if (TEMP_FAILURE_RETRY(ioctl(h->fd, USBDEVFS_SUBMITURB, urb)) == -1) {
    359         return -1;
    360     }
    361 
    362     h->urb_in_busy = true;
    363     while (true) {
    364         D("[ reap urb - wait ]");
    365         h->reaper_thread = pthread_self();
    366         int fd = h->fd;
    367         lock.unlock();
    368 
    369         // This ioctl must not have TEMP_FAILURE_RETRY because we send SIGALRM to break out.
    370         usbdevfs_urb* out = nullptr;
    371         int res = ioctl(fd, USBDEVFS_REAPURB, &out);
    372         int saved_errno = errno;
    373 
    374         lock.lock();
    375         h->reaper_thread = 0;
    376         if (h->dead) {
    377             errno = EINVAL;
    378             return -1;
    379         }
    380         if (res < 0) {
    381             if (saved_errno == EINTR) {
    382                 continue;
    383             }
    384             D("[ reap urb - error ]");
    385             errno = saved_errno;
    386             return -1;
    387         }
    388         D("[ urb @%p status = %d, actual = %d ]", out, out->status, out->actual_length);
    389 
    390         if (out == &h->urb_in) {
    391             D("[ reap urb - IN complete ]");
    392             h->urb_in_busy = false;
    393             if (urb->status != 0) {
    394                 errno = -urb->status;
    395                 return -1;
    396             }
    397             return urb->actual_length;
    398         }
    399         if (out == &h->urb_out) {
    400             D("[ reap urb - OUT compelete ]");
    401             h->urb_out_busy = false;
    402             h->cv.notify_all();
    403         }
    404     }
    405 }
    406 
    407 int usb_write(usb_handle *h, const void *_data, int len)
    408 {
    409     D("++ usb_write ++");
    410 
    411     unsigned char *data = (unsigned char*) _data;
    412     int n = usb_bulk_write(h, data, len);
    413     if (n != len) {
    414         D("ERROR: n = %d, errno = %d (%s)", n, errno, strerror(errno));
    415         return -1;
    416     }
    417 
    418     if (h->zero_mask && !(len & h->zero_mask)) {
    419         // If we need 0-markers and our transfer is an even multiple of the packet size,
    420         // then send a zero marker.
    421         return usb_bulk_write(h, _data, 0);
    422     }
    423 
    424     D("-- usb_write --");
    425     return 0;
    426 }
    427 
    428 int usb_read(usb_handle *h, void *_data, int len)
    429 {
    430     unsigned char *data = (unsigned char*) _data;
    431     int n;
    432 
    433     D("++ usb_read ++");
    434     int orig_len = len;
    435     while (len == orig_len) {
    436         int xfer = len;
    437 
    438         D("[ usb read %d fd = %d], path=%s", xfer, h->fd, h->path.c_str());
    439         n = usb_bulk_read(h, data, xfer);
    440         D("[ usb read %d ] = %d, path=%s", xfer, n, h->path.c_str());
    441         if (n <= 0) {
    442             if((errno == ETIMEDOUT) && (h->fd != -1)) {
    443                 D("[ timeout ]");
    444                 continue;
    445             }
    446             D("ERROR: n = %d, errno = %d (%s)",
    447                 n, errno, strerror(errno));
    448             return -1;
    449         }
    450 
    451         len -= n;
    452         data += n;
    453     }
    454 
    455     D("-- usb_read --");
    456     return orig_len - len;
    457 }
    458 
    459 void usb_kick(usb_handle* h) {
    460     std::lock_guard<std::mutex> lock(h->mutex);
    461     D("[ kicking %p (fd = %d) ]", h, h->fd);
    462     if (!h->dead) {
    463         h->dead = true;
    464 
    465         if (h->writeable) {
    466             /* HACK ALERT!
    467             ** Sometimes we get stuck in ioctl(USBDEVFS_REAPURB).
    468             ** This is a workaround for that problem.
    469             */
    470             if (h->reaper_thread) {
    471                 pthread_kill(h->reaper_thread, SIGALRM);
    472             }
    473 
    474             /* cancel any pending transactions
    475             ** these will quietly fail if the txns are not active,
    476             ** but this ensures that a reader blocked on REAPURB
    477             ** will get unblocked
    478             */
    479             ioctl(h->fd, USBDEVFS_DISCARDURB, &h->urb_in);
    480             ioctl(h->fd, USBDEVFS_DISCARDURB, &h->urb_out);
    481             h->urb_in.status = -ENODEV;
    482             h->urb_out.status = -ENODEV;
    483             h->urb_in_busy = false;
    484             h->urb_out_busy = false;
    485             h->cv.notify_all();
    486         } else {
    487             unregister_usb_transport(h);
    488         }
    489     }
    490 }
    491 
    492 int usb_close(usb_handle* h) {
    493     std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
    494     g_usb_handles.remove(h);
    495 
    496     D("-- usb close %p (fd = %d) --", h, h->fd);
    497 
    498     delete h;
    499 
    500     return 0;
    501 }
    502 
    503 size_t usb_get_max_packet_size(usb_handle* h) {
    504     return h->max_packet_size;
    505 }
    506 
    507 static void register_device(const char* dev_name, const char* dev_path, unsigned char ep_in,
    508                             unsigned char ep_out, int interface, int serial_index,
    509                             unsigned zero_mask, size_t max_packet_size) {
    510     // Since Linux will not reassign the device ID (and dev_name) as long as the
    511     // device is open, we can add to the list here once we open it and remove
    512     // from the list when we're finally closed and everything will work out
    513     // fine.
    514     //
    515     // If we have a usb_handle on the list of handles with a matching name, we
    516     // have no further work to do.
    517     {
    518         std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
    519         for (usb_handle* usb: g_usb_handles) {
    520             if (usb->path == dev_name) {
    521                 return;
    522             }
    523         }
    524     }
    525 
    526     D("[ usb located new device %s (%d/%d/%d) ]", dev_name, ep_in, ep_out, interface);
    527     std::unique_ptr<usb_handle> usb(new usb_handle);
    528     usb->path = dev_name;
    529     usb->ep_in = ep_in;
    530     usb->ep_out = ep_out;
    531     usb->zero_mask = zero_mask;
    532     usb->max_packet_size = max_packet_size;
    533 
    534     // Initialize mark so we don't get garbage collected after the device scan.
    535     usb->mark = true;
    536 
    537     usb->fd = unix_open(usb->path.c_str(), O_RDWR | O_CLOEXEC);
    538     if (usb->fd == -1) {
    539         // Opening RW failed, so see if we have RO access.
    540         usb->fd = unix_open(usb->path.c_str(), O_RDONLY | O_CLOEXEC);
    541         if (usb->fd == -1) {
    542             D("[ usb open %s failed: %s]", usb->path.c_str(), strerror(errno));
    543             return;
    544         }
    545         usb->writeable = 0;
    546     }
    547 
    548     D("[ usb opened %s%s, fd=%d]",
    549       usb->path.c_str(), (usb->writeable ? "" : " (read-only)"), usb->fd);
    550 
    551     if (usb->writeable) {
    552         if (ioctl(usb->fd, USBDEVFS_CLAIMINTERFACE, &interface) != 0) {
    553             D("[ usb ioctl(%d, USBDEVFS_CLAIMINTERFACE) failed: %s]", usb->fd, strerror(errno));
    554             return;
    555         }
    556     }
    557 
    558     // Read the device's serial number.
    559     std::string serial_path = android::base::StringPrintf(
    560         "/sys/bus/usb/devices/%s/serial", dev_path + 4);
    561     std::string serial;
    562     if (!android::base::ReadFileToString(serial_path, &serial)) {
    563         D("[ usb read %s failed: %s ]", serial_path.c_str(), strerror(errno));
    564         // We don't actually want to treat an unknown serial as an error because
    565         // devices aren't able to communicate a serial number in early bringup.
    566         // http://b/20883914
    567         serial = "";
    568     }
    569     serial = android::base::Trim(serial);
    570 
    571     // Add to the end of the active handles.
    572     usb_handle* done_usb = usb.release();
    573     {
    574         std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
    575         g_usb_handles.push_back(done_usb);
    576     }
    577     register_usb_transport(done_usb, serial.c_str(), dev_path, done_usb->writeable);
    578 }
    579 
    580 static void device_poll_thread() {
    581     adb_thread_setname("device poll");
    582     D("Created device thread");
    583     while (true) {
    584         // TODO: Use inotify.
    585         find_usb_device("/dev/bus/usb", register_device);
    586         kick_disconnected_devices();
    587         std::this_thread::sleep_for(1s);
    588     }
    589 }
    590 
    591 void usb_init() {
    592     struct sigaction actions;
    593     memset(&actions, 0, sizeof(actions));
    594     sigemptyset(&actions.sa_mask);
    595     actions.sa_flags = 0;
    596     actions.sa_handler = [](int) {};
    597     sigaction(SIGALRM, &actions, nullptr);
    598 
    599     std::thread(device_poll_thread).detach();
    600 }
    601 
    602 void usb_cleanup() {}
    603 
    604 } // namespace native
    605