usb_linux.c revision 0e7c4274c687446dbe30a814278d7a6b99da8c4e
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[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 adb_mutex_lock(&h->lock); 373 h->reaper_thread = 0; 374 if(h->dead) { 375 res = -1; 376 break; 377 } 378 if(res < 0) { 379 if(errno == EINTR) { 380 continue; 381 } 382 D("[ reap urb - error ]\n"); 383 break; 384 } 385 D("[ urb @%p status = %d, actual = %d ]\n", 386 out, out->status, out->actual_length); 387 388 if(out == &h->urb_in) { 389 D("[ reap urb - IN complete ]\n"); 390 h->urb_in_busy = 0; 391 if(urb->status == 0) { 392 res = urb->actual_length; 393 } else { 394 res = -1; 395 } 396 break; 397 } 398 if(out == &h->urb_out) { 399 D("[ reap urb - OUT compelete ]\n"); 400 h->urb_out_busy = 0; 401 adb_cond_broadcast(&h->notify); 402 } 403 } 404fail: 405 adb_mutex_unlock(&h->lock); 406 return res; 407} 408 409 410int usb_write(usb_handle *h, const void *_data, int len) 411{ 412 unsigned char *data = (unsigned char*) _data; 413 int n; 414 int need_zero = 0; 415 416 if(h->zero_mask) { 417 /* if we need 0-markers and our transfer 418 ** is an even multiple of the packet size, 419 ** we make note of it 420 */ 421 if(!(len & h->zero_mask)) { 422 need_zero = 1; 423 } 424 } 425 426 while(len > 0) { 427 int xfer = (len > 4096) ? 4096 : len; 428 429 n = usb_bulk_write(h, data, xfer); 430 if(n != xfer) { 431 D("ERROR: n = %d, errno = %d (%s)\n", 432 n, errno, strerror(errno)); 433 return -1; 434 } 435 436 len -= xfer; 437 data += xfer; 438 } 439 440 if(need_zero){ 441 n = usb_bulk_write(h, _data, 0); 442 return n; 443 } 444 445 return 0; 446} 447 448int usb_read(usb_handle *h, void *_data, int len) 449{ 450 unsigned char *data = (unsigned char*) _data; 451 int n; 452 453 D("++ usb_read ++\n"); 454 while(len > 0) { 455 int xfer = (len > 4096) ? 4096 : len; 456 457 D("[ usb read %d fd = %d], fname=%s\n", xfer, h->desc, h->fname); 458 n = usb_bulk_read(h, data, xfer); 459 D("[ usb read %d ] = %d, fname=%s\n", xfer, n, h->fname); 460 if(n != xfer) { 461 if((errno == ETIMEDOUT) && (h->desc != -1)) { 462 D("[ timeout ]\n"); 463 if(n > 0){ 464 data += n; 465 len -= n; 466 } 467 continue; 468 } 469 D("ERROR: n = %d, errno = %d (%s)\n", 470 n, errno, strerror(errno)); 471 return -1; 472 } 473 474 len -= xfer; 475 data += xfer; 476 } 477 478 D("-- usb_read --\n"); 479 return 0; 480} 481 482void usb_kick(usb_handle *h) 483{ 484 D("[ kicking %p (fd = %d) ]\n", h, h->desc); 485 adb_mutex_lock(&h->lock); 486 if(h->dead == 0) { 487 h->dead = 1; 488 489 if (h->writeable) { 490 /* HACK ALERT! 491 ** Sometimes we get stuck in ioctl(USBDEVFS_REAPURB). 492 ** This is a workaround for that problem. 493 */ 494 if (h->reaper_thread) { 495 pthread_kill(h->reaper_thread, SIGALRM); 496 } 497 498 /* cancel any pending transactions 499 ** these will quietly fail if the txns are not active, 500 ** but this ensures that a reader blocked on REAPURB 501 ** will get unblocked 502 */ 503 ioctl(h->desc, USBDEVFS_DISCARDURB, &h->urb_in); 504 ioctl(h->desc, USBDEVFS_DISCARDURB, &h->urb_out); 505 h->urb_in.status = -ENODEV; 506 h->urb_out.status = -ENODEV; 507 h->urb_in_busy = 0; 508 h->urb_out_busy = 0; 509 adb_cond_broadcast(&h->notify); 510 } else { 511 unregister_usb_transport(h); 512 } 513 } 514 adb_mutex_unlock(&h->lock); 515} 516 517int usb_close(usb_handle *h) 518{ 519 D("[ usb close ... ]\n"); 520 adb_mutex_lock(&usb_lock); 521 h->next->prev = h->prev; 522 h->prev->next = h->next; 523 h->prev = 0; 524 h->next = 0; 525 526 adb_close(h->desc); 527 D("[ usb closed %p (fd = %d) ]\n", h, h->desc); 528 adb_mutex_unlock(&usb_lock); 529 530 free(h); 531 return 0; 532} 533 534static void register_device(const char *dev_name, 535 unsigned char ep_in, unsigned char ep_out, 536 int interface, int serial_index, unsigned zero_mask) 537{ 538 usb_handle* usb = 0; 539 int n = 0; 540 char serial[256]; 541 542 /* Since Linux will not reassign the device ID (and dev_name) 543 ** as long as the device is open, we can add to the list here 544 ** once we open it and remove from the list when we're finally 545 ** closed and everything will work out fine. 546 ** 547 ** If we have a usb_handle on the list 'o handles with a matching 548 ** name, we have no further work to do. 549 */ 550 adb_mutex_lock(&usb_lock); 551 for(usb = handle_list.next; usb != &handle_list; usb = usb->next){ 552 if(!strcmp(usb->fname, dev_name)) { 553 adb_mutex_unlock(&usb_lock); 554 return; 555 } 556 } 557 adb_mutex_unlock(&usb_lock); 558 559 D("[ usb located new device %s (%d/%d/%d) ]\n", 560 dev_name, ep_in, ep_out, interface); 561 usb = calloc(1, sizeof(usb_handle)); 562 strcpy(usb->fname, dev_name); 563 usb->ep_in = ep_in; 564 usb->ep_out = ep_out; 565 usb->zero_mask = zero_mask; 566 usb->writeable = 1; 567 568 adb_cond_init(&usb->notify, 0); 569 adb_mutex_init(&usb->lock, 0); 570 /* initialize mark to 1 so we don't get garbage collected after the device scan */ 571 usb->mark = 1; 572 usb->reaper_thread = 0; 573 574 usb->desc = unix_open(usb->fname, O_RDWR); 575 if(usb->desc < 0) { 576 /* if we fail, see if have read-only access */ 577 usb->desc = unix_open(usb->fname, O_RDONLY); 578 if(usb->desc < 0) goto fail; 579 usb->writeable = 0; 580 D("[ usb open read-only %s fd = %d]\n", usb->fname, usb->desc); 581 } else { 582 D("[ usb open %s fd = %d]\n", usb->fname, usb->desc); 583 n = ioctl(usb->desc, USBDEVFS_CLAIMINTERFACE, &interface); 584 if(n != 0) goto fail; 585 } 586 587 /* read the device's serial number */ 588 serial[0] = 0; 589 memset(serial, 0, sizeof(serial)); 590 if (serial_index) { 591 struct usbdevfs_ctrltransfer ctrl; 592 __u16 buffer[128]; 593 __u16 languages[128]; 594 int i, result; 595 int languageCount = 0; 596 597 memset(languages, 0, sizeof(languages)); 598 memset(&ctrl, 0, sizeof(ctrl)); 599 600 // read list of supported languages 601 ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE; 602 ctrl.bRequest = USB_REQ_GET_DESCRIPTOR; 603 ctrl.wValue = (USB_DT_STRING << 8) | 0; 604 ctrl.wIndex = 0; 605 ctrl.wLength = sizeof(languages); 606 ctrl.data = languages; 607 608 result = ioctl(usb->desc, USBDEVFS_CONTROL, &ctrl); 609 if (result > 0) 610 languageCount = (result - 2) / 2; 611 612 for (i = 1; i <= languageCount; i++) { 613 memset(buffer, 0, sizeof(buffer)); 614 memset(&ctrl, 0, sizeof(ctrl)); 615 616 ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE; 617 ctrl.bRequest = USB_REQ_GET_DESCRIPTOR; 618 ctrl.wValue = (USB_DT_STRING << 8) | serial_index; 619 ctrl.wIndex = __le16_to_cpu(languages[i]); 620 ctrl.wLength = sizeof(buffer); 621 ctrl.data = buffer; 622 623 result = ioctl(usb->desc, USBDEVFS_CONTROL, &ctrl); 624 if (result > 0) { 625 int i; 626 // skip first word, and copy the rest to the serial string, changing shorts to bytes. 627 result /= 2; 628 for (i = 1; i < result; i++) 629 serial[i - 1] = __le16_to_cpu(buffer[i]); 630 serial[i - 1] = 0; 631 break; 632 } 633 } 634 } 635 636 /* add to the end of the active handles */ 637 adb_mutex_lock(&usb_lock); 638 usb->next = &handle_list; 639 usb->prev = handle_list.prev; 640 usb->prev->next = usb; 641 usb->next->prev = usb; 642 adb_mutex_unlock(&usb_lock); 643 644 register_usb_transport(usb, serial, usb->writeable); 645 return; 646 647fail: 648 D("[ usb open %s error=%d, err_str = %s]\n", 649 usb->fname, errno, strerror(errno)); 650 if(usb->desc >= 0) { 651 adb_close(usb->desc); 652 } 653 free(usb); 654} 655 656void* device_poll_thread(void* unused) 657{ 658 D("Created device thread\n"); 659 for(;;) { 660 /* XXX use inotify */ 661 find_usb_device("/dev/bus/usb", register_device); 662 kick_disconnected_devices(); 663 sleep(1); 664 } 665 return NULL; 666} 667 668static void sigalrm_handler(int signo) 669{ 670 // don't need to do anything here 671} 672 673void usb_init() 674{ 675 adb_thread_t tid; 676 struct sigaction actions; 677 678 memset(&actions, 0, sizeof(actions)); 679 sigemptyset(&actions.sa_mask); 680 actions.sa_flags = 0; 681 actions.sa_handler = sigalrm_handler; 682 sigaction(SIGALRM,& actions, NULL); 683 684 if(adb_thread_create(&tid, device_poll_thread, NULL)){ 685 fatal_errno("cannot create input thread"); 686 } 687} 688 689