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