2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
25 #include <linux/usb/ch9.h>
26 #include <linux/usbdevice_fs.h>
27 #include <linux/version.h>
31 #include <sys/ioctl.h>
33 #include <sys/types.h>
37 #include <condition_variable>
42 #include <base/file.h>
43 #include <base/stringprintf.h>
44 #include <base/strings.h>
47 #include "transport.h"
49 using namespace std::literals;
51 /* usb scan debugging is waaaay too verbose */
56 if (fd != -1) unix_close(fd);
65 unsigned writeable = 1;
70 bool urb_in_busy = false;
71 bool urb_out_busy = false;
74 std::condition_variable cv;
77 // for garbage collecting disconnected devices
80 // ID of thread currently in REAPURB
81 pthread_t reaper_thread = 0;
84 static auto& g_usb_handles_mutex = *new std::mutex();
85 static auto& g_usb_handles = *new std::list<usb_handle*>();
87 static int is_known_device(const char* dev_name) {
88 std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
89 for (usb_handle* usb : g_usb_handles) {
90 if (usb->path == dev_name) {
91 // set mark flag to indicate this device is still alive
99 static void kick_disconnected_devices() {
100 std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
101 // kick any devices in the device list that were not found in the device scan
102 for (usb_handle* usb : g_usb_handles) {
111 static inline bool contains_non_digit(const char* name) {
113 if (!isdigit(*name++)) return true;
118 static void find_usb_device(const std::string& base,
119 void (*register_device_callback)
120 (const char*, const char*, unsigned char, unsigned char, int, int, unsigned))
122 std::unique_ptr<DIR, int(*)(DIR*)> bus_dir(opendir(base.c_str()), closedir);
123 if (!bus_dir) return;
126 while ((de = readdir(bus_dir.get())) != 0) {
127 if (contains_non_digit(de->d_name)) continue;
129 std::string bus_name = base + "/" + de->d_name;
131 std::unique_ptr<DIR, int(*)(DIR*)> dev_dir(opendir(bus_name.c_str()), closedir);
132 if (!dev_dir) continue;
134 while ((de = readdir(dev_dir.get()))) {
135 unsigned char devdesc[4096];
136 unsigned char* bufptr = devdesc;
137 unsigned char* bufend;
138 struct usb_device_descriptor* device;
139 struct usb_config_descriptor* config;
140 struct usb_interface_descriptor* interface;
141 struct usb_endpoint_descriptor *ep1, *ep2;
142 unsigned zero_mask = 0;
145 if (contains_non_digit(de->d_name)) continue;
147 std::string dev_name = bus_name + "/" + de->d_name;
148 if (is_known_device(dev_name.c_str())) {
152 int fd = unix_open(dev_name.c_str(), O_RDONLY | O_CLOEXEC);
157 size_t desclength = unix_read(fd, devdesc, sizeof(devdesc));
158 bufend = bufptr + desclength;
160 // should have device and configuration descriptors, and atleast two endpoints
161 if (desclength < USB_DT_DEVICE_SIZE + USB_DT_CONFIG_SIZE) {
162 D("desclength %zu is too small", desclength);
167 device = (struct usb_device_descriptor*)bufptr;
168 bufptr += USB_DT_DEVICE_SIZE;
170 if((device->bLength != USB_DT_DEVICE_SIZE) || (device->bDescriptorType != USB_DT_DEVICE)) {
175 vid = device->idVendor;
176 pid = device->idProduct;
177 DBGX("[ %s is V:%04x P:%04x ]\n", dev_name.c_str(), vid, pid);
179 // should have config descriptor next
180 config = (struct usb_config_descriptor *)bufptr;
181 bufptr += USB_DT_CONFIG_SIZE;
182 if (config->bLength != USB_DT_CONFIG_SIZE || config->bDescriptorType != USB_DT_CONFIG) {
183 D("usb_config_descriptor not found");
188 // loop through all the descriptors and look for the ADB interface
189 while (bufptr < bufend) {
190 unsigned char length = bufptr[0];
191 unsigned char type = bufptr[1];
193 if (type == USB_DT_INTERFACE) {
194 interface = (struct usb_interface_descriptor *)bufptr;
197 if (length != USB_DT_INTERFACE_SIZE) {
198 D("interface descriptor has wrong size");
202 DBGX("bInterfaceClass: %d, bInterfaceSubClass: %d,"
203 "bInterfaceProtocol: %d, bNumEndpoints: %d\n",
204 interface->bInterfaceClass, interface->bInterfaceSubClass,
205 interface->bInterfaceProtocol, interface->bNumEndpoints);
207 if (interface->bNumEndpoints == 2 &&
208 is_adb_interface(vid, pid, interface->bInterfaceClass,
209 interface->bInterfaceSubClass, interface->bInterfaceProtocol)) {
214 char *devpath = nullptr;
216 DBGX("looking for bulk endpoints\n");
218 ep1 = (struct usb_endpoint_descriptor *)bufptr;
219 bufptr += USB_DT_ENDPOINT_SIZE;
220 // For USB 3.0 SuperSpeed devices, skip potential
221 // USB 3.0 SuperSpeed Endpoint Companion descriptor
222 if (bufptr+2 <= devdesc + desclength &&
223 bufptr[0] == USB_DT_SS_EP_COMP_SIZE &&
224 bufptr[1] == USB_DT_SS_ENDPOINT_COMP) {
225 bufptr += USB_DT_SS_EP_COMP_SIZE;
227 ep2 = (struct usb_endpoint_descriptor *)bufptr;
228 bufptr += USB_DT_ENDPOINT_SIZE;
229 if (bufptr+2 <= devdesc + desclength &&
230 bufptr[0] == USB_DT_SS_EP_COMP_SIZE &&
231 bufptr[1] == USB_DT_SS_ENDPOINT_COMP) {
232 bufptr += USB_DT_SS_EP_COMP_SIZE;
235 if (bufptr > devdesc + desclength ||
236 ep1->bLength != USB_DT_ENDPOINT_SIZE ||
237 ep1->bDescriptorType != USB_DT_ENDPOINT ||
238 ep2->bLength != USB_DT_ENDPOINT_SIZE ||
239 ep2->bDescriptorType != USB_DT_ENDPOINT) {
240 D("endpoints not found");
244 // both endpoints should be bulk
245 if (ep1->bmAttributes != USB_ENDPOINT_XFER_BULK ||
246 ep2->bmAttributes != USB_ENDPOINT_XFER_BULK) {
247 D("bulk endpoints not found");
250 /* aproto 01 needs 0 termination */
251 if(interface->bInterfaceProtocol == 0x01) {
252 zero_mask = ep1->wMaxPacketSize - 1;
255 // we have a match. now we just need to figure out which is in and which is out.
256 unsigned char local_ep_in, local_ep_out;
257 if (ep1->bEndpointAddress & USB_ENDPOINT_DIR_MASK) {
258 local_ep_in = ep1->bEndpointAddress;
259 local_ep_out = ep2->bEndpointAddress;
261 local_ep_in = ep2->bEndpointAddress;
262 local_ep_out = ep1->bEndpointAddress;
265 // Determine the device path
266 if (!fstat(fd, &st) && S_ISCHR(st.st_mode)) {
267 snprintf(pathbuf, sizeof(pathbuf), "/sys/dev/char/%d:%d",
268 major(st.st_rdev), minor(st.st_rdev));
269 ssize_t link_len = readlink(pathbuf, link, sizeof(link) - 1);
271 link[link_len] = '\0';
272 const char* slash = strrchr(link, '/');
274 snprintf(pathbuf, sizeof(pathbuf),
275 "usb:%s", slash + 1);
281 register_device_callback(dev_name.c_str(), devpath,
282 local_ep_in, local_ep_out,
283 interface->bInterfaceNumber, device->iSerialNumber, zero_mask);
296 static int usb_bulk_write(usb_handle* h, const void* data, int len) {
297 std::unique_lock<std::mutex> lock(h->mutex);
298 D("++ usb_bulk_write ++");
300 usbdevfs_urb* urb = &h->urb_out;
301 memset(urb, 0, sizeof(*urb));
302 urb->type = USBDEVFS_URB_TYPE_BULK;
303 urb->endpoint = h->ep_out;
305 urb->buffer = const_cast<void*>(data);
306 urb->buffer_length = len;
313 if (TEMP_FAILURE_RETRY(ioctl(h->fd, USBDEVFS_SUBMITURB, urb)) == -1) {
317 h->urb_out_busy = true;
319 auto now = std::chrono::system_clock::now();
320 if (h->cv.wait_until(lock, now + 5s) == std::cv_status::timeout || h->dead) {
321 // TODO: call USBDEVFS_DISCARDURB?
325 if (!h->urb_out_busy) {
326 if (urb->status != 0) {
327 errno = -urb->status;
330 return urb->actual_length;
335 static int usb_bulk_read(usb_handle* h, void* data, int len) {
336 std::unique_lock<std::mutex> lock(h->mutex);
337 D("++ usb_bulk_read ++");
339 usbdevfs_urb* urb = &h->urb_in;
340 memset(urb, 0, sizeof(*urb));
341 urb->type = USBDEVFS_URB_TYPE_BULK;
342 urb->endpoint = h->ep_in;
345 urb->buffer_length = len;
352 if (TEMP_FAILURE_RETRY(ioctl(h->fd, USBDEVFS_SUBMITURB, urb)) == -1) {
356 h->urb_in_busy = true;
358 D("[ reap urb - wait ]");
359 h->reaper_thread = pthread_self();
363 // This ioctl must not have TEMP_FAILURE_RETRY because we send SIGALRM to break out.
364 usbdevfs_urb* out = nullptr;
365 int res = ioctl(fd, USBDEVFS_REAPURB, &out);
366 int saved_errno = errno;
369 h->reaper_thread = 0;
375 if (saved_errno == EINTR) {
378 D("[ reap urb - error ]");
382 D("[ urb @%p status = %d, actual = %d ]", out, out->status, out->actual_length);
384 if (out == &h->urb_in) {
385 D("[ reap urb - IN complete ]");
386 h->urb_in_busy = false;
387 if (urb->status != 0) {
388 errno = -urb->status;
391 return urb->actual_length;
393 if (out == &h->urb_out) {
394 D("[ reap urb - OUT compelete ]");
395 h->urb_out_busy = false;
402 int usb_write(usb_handle *h, const void *_data, int len)
404 D("++ usb_write ++");
406 unsigned char *data = (unsigned char*) _data;
407 int n = usb_bulk_write(h, data, len);
409 D("ERROR: n = %d, errno = %d (%s)", n, errno, strerror(errno));
413 if (h->zero_mask && !(len & h->zero_mask)) {
414 // If we need 0-markers and our transfer is an even multiple of the packet size,
415 // then send a zero marker.
416 return usb_bulk_write(h, _data, 0);
419 D("-- usb_write --");
423 int usb_read(usb_handle *h, void *_data, int len)
425 unsigned char *data = (unsigned char*) _data;
432 D("[ usb read %d fd = %d], path=%s", xfer, h->fd, h->path.c_str());
433 n = usb_bulk_read(h, data, xfer);
434 D("[ usb read %d ] = %d, path=%s", xfer, n, h->path.c_str());
436 if((errno == ETIMEDOUT) && (h->fd != -1)) {
444 D("ERROR: n = %d, errno = %d (%s)",
445 n, errno, strerror(errno));
457 void usb_kick(usb_handle* h) {
458 std::lock_guard<std::mutex> lock(h->mutex);
459 D("[ kicking %p (fd = %d) ]", h, h->fd);
465 ** Sometimes we get stuck in ioctl(USBDEVFS_REAPURB).
466 ** This is a workaround for that problem.
468 if (h->reaper_thread) {
469 pthread_kill(h->reaper_thread, SIGALRM);
472 /* cancel any pending transactions
473 ** these will quietly fail if the txns are not active,
474 ** but this ensures that a reader blocked on REAPURB
475 ** will get unblocked
477 ioctl(h->fd, USBDEVFS_DISCARDURB, &h->urb_in);
478 ioctl(h->fd, USBDEVFS_DISCARDURB, &h->urb_out);
479 h->urb_in.status = -ENODEV;
480 h->urb_out.status = -ENODEV;
481 h->urb_in_busy = false;
482 h->urb_out_busy = false;
485 unregister_usb_transport(h);
490 int usb_close(usb_handle* h) {
491 std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
492 g_usb_handles.remove(h);
494 D("-- usb close %p (fd = %d) --", h, h->fd);
501 static void register_device(const char* dev_name, const char* dev_path,
502 unsigned char ep_in, unsigned char ep_out,
503 int interface, int serial_index,
504 unsigned zero_mask) {
505 // Since Linux will not reassign the device ID (and dev_name) as long as the
506 // device is open, we can add to the list here once we open it and remove
507 // from the list when we're finally closed and everything will work out
510 // If we have a usb_handle on the list of handles with a matching name, we
511 // have no further work to do.
513 std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
514 for (usb_handle* usb: g_usb_handles) {
515 if (usb->path == dev_name) {
521 D("[ usb located new device %s (%d/%d/%d) ]", dev_name, ep_in, ep_out, interface);
522 std::unique_ptr<usb_handle> usb(new usb_handle);
523 usb->path = dev_name;
525 usb->ep_out = ep_out;
526 usb->zero_mask = zero_mask;
528 // Initialize mark so we don't get garbage collected after the device scan.
531 usb->fd = unix_open(usb->path.c_str(), O_RDWR | O_CLOEXEC);
533 // Opening RW failed, so see if we have RO access.
534 usb->fd = unix_open(usb->path.c_str(), O_RDONLY | O_CLOEXEC);
536 D("[ usb open %s failed: %s]", usb->path.c_str(), strerror(errno));
542 D("[ usb opened %s%s, fd=%d]",
543 usb->path.c_str(), (usb->writeable ? "" : " (read-only)"), usb->fd);
545 if (usb->writeable) {
546 if (ioctl(usb->fd, USBDEVFS_CLAIMINTERFACE, &interface) != 0) {
547 D("[ usb ioctl(%d, USBDEVFS_CLAIMINTERFACE) failed: %s]", usb->fd, strerror(errno));
552 // Read the device's serial number.
553 std::string serial_path = android::base::StringPrintf(
554 "/sys/bus/usb/devices/%s/serial", dev_path + 4);
556 if (!android::base::ReadFileToString(serial_path, &serial)) {
557 D("[ usb read %s failed: %s ]", serial_path.c_str(), strerror(errno));
558 // We don't actually want to treat an unknown serial as an error because
559 // devices aren't able to communicate a serial number in early bringup.
563 serial = android::base::Trim(serial);
565 // Add to the end of the active handles.
566 usb_handle* done_usb = usb.release();
568 std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
569 g_usb_handles.push_back(done_usb);
571 register_usb_transport(done_usb, serial.c_str(), dev_path, done_usb->writeable);
574 static void* device_poll_thread(void* unused) {
575 adb_thread_setname("device poll");
576 D("Created device thread");
578 // TODO: Use inotify.
579 find_usb_device("/dev/bus/usb", register_device);
580 kick_disconnected_devices();
587 struct sigaction actions;
588 memset(&actions, 0, sizeof(actions));
589 sigemptyset(&actions.sa_mask);
590 actions.sa_flags = 0;
591 actions.sa_handler = [](int) {};
592 sigaction(SIGALRM, &actions, nullptr);
594 if (!adb_thread_create(device_poll_thread, nullptr)) {
595 fatal_errno("cannot create device_poll thread");