1 /* 2 * Copyright (C) 2010 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 DEBUG 1 18 #if DEBUG 19 20 #ifdef USE_LIBLOG 21 #define LOG_TAG "usbhost" 22 #include "utils/Log.h" 23 #define D ALOGD 24 #else 25 #define D printf 26 #endif 27 28 #else 29 #define D(...) 30 #endif 31 32 #include <stdio.h> 33 #include <stdlib.h> 34 #include <unistd.h> 35 #include <string.h> 36 #include <stddef.h> 37 38 #include <sys/ioctl.h> 39 #include <sys/types.h> 40 #include <sys/time.h> 41 #include <sys/inotify.h> 42 #include <dirent.h> 43 #include <fcntl.h> 44 #include <errno.h> 45 #include <ctype.h> 46 #include <pthread.h> 47 48 #include <linux/usbdevice_fs.h> 49 #include <asm/byteorder.h> 50 51 #include "usbhost/usbhost.h" 52 53 #define DEV_DIR "/dev" 54 #define DEV_BUS_DIR DEV_DIR "/bus" 55 #define USB_FS_DIR DEV_BUS_DIR "/usb" 56 #define USB_FS_ID_SCANNER USB_FS_DIR "/%d/%d" 57 #define USB_FS_ID_FORMAT USB_FS_DIR "/%03d/%03d" 58 59 // From drivers/usb/core/devio.c 60 // I don't know why this isn't in a kernel header 61 #define MAX_USBFS_BUFFER_SIZE 16384 62 63 #define MAX_USBFS_WD_COUNT 10 64 65 struct usb_host_context { 66 int fd; 67 usb_device_added_cb cb_added; 68 usb_device_removed_cb cb_removed; 69 void *data; 70 int wds[MAX_USBFS_WD_COUNT]; 71 int wdd; 72 int wddbus; 73 }; 74 75 struct usb_device { 76 char dev_name[64]; 77 unsigned char desc[4096]; 78 int desc_length; 79 int fd; 80 int writeable; 81 }; 82 83 static inline int badname(const char *name) 84 { 85 while(*name) { 86 if(!isdigit(*name++)) return 1; 87 } 88 return 0; 89 } 90 91 static int find_existing_devices_bus(char *busname, 92 usb_device_added_cb added_cb, 93 void *client_data) 94 { 95 char devname[32]; 96 DIR *devdir; 97 struct dirent *de; 98 int done = 0; 99 100 devdir = opendir(busname); 101 if(devdir == 0) return 0; 102 103 while ((de = readdir(devdir)) && !done) { 104 if(badname(de->d_name)) continue; 105 106 snprintf(devname, sizeof(devname), "%s/%s", busname, de->d_name); 107 done = added_cb(devname, client_data); 108 } // end of devdir while 109 closedir(devdir); 110 111 return done; 112 } 113 114 /* returns true if one of the callbacks indicates we are done */ 115 static int find_existing_devices(usb_device_added_cb added_cb, 116 void *client_data) 117 { 118 char busname[32]; 119 DIR *busdir; 120 struct dirent *de; 121 int done = 0; 122 123 busdir = opendir(USB_FS_DIR); 124 if(busdir == 0) return 0; 125 126 while ((de = readdir(busdir)) != 0 && !done) { 127 if(badname(de->d_name)) continue; 128 129 snprintf(busname, sizeof(busname), USB_FS_DIR "/%s", de->d_name); 130 done = find_existing_devices_bus(busname, added_cb, 131 client_data); 132 } //end of busdir while 133 closedir(busdir); 134 135 return done; 136 } 137 138 static void watch_existing_subdirs(struct usb_host_context *context, 139 int *wds, int wd_count) 140 { 141 char path[100]; 142 int i, ret; 143 144 wds[0] = inotify_add_watch(context->fd, USB_FS_DIR, IN_CREATE | IN_DELETE); 145 if (wds[0] < 0) 146 return; 147 148 /* watch existing subdirectories of USB_FS_DIR */ 149 for (i = 1; i < wd_count; i++) { 150 snprintf(path, sizeof(path), USB_FS_DIR "/%03d", i); 151 ret = inotify_add_watch(context->fd, path, IN_CREATE | IN_DELETE); 152 if (ret >= 0) 153 wds[i] = ret; 154 } 155 } 156 157 struct usb_host_context *usb_host_init() 158 { 159 struct usb_host_context *context = calloc(1, sizeof(struct usb_host_context)); 160 if (!context) { 161 fprintf(stderr, "out of memory in usb_host_context\n"); 162 return NULL; 163 } 164 context->fd = inotify_init(); 165 if (context->fd < 0) { 166 fprintf(stderr, "inotify_init failed\n"); 167 free(context); 168 return NULL; 169 } 170 return context; 171 } 172 173 void usb_host_cleanup(struct usb_host_context *context) 174 { 175 close(context->fd); 176 free(context); 177 } 178 179 int usb_host_get_fd(struct usb_host_context *context) 180 { 181 return context->fd; 182 } /* usb_host_get_fd() */ 183 184 int usb_host_load(struct usb_host_context *context, 185 usb_device_added_cb added_cb, 186 usb_device_removed_cb removed_cb, 187 usb_discovery_done_cb discovery_done_cb, 188 void *client_data) 189 { 190 int done = 0; 191 int i; 192 193 context->cb_added = added_cb; 194 context->cb_removed = removed_cb; 195 context->data = client_data; 196 197 D("Created device discovery thread\n"); 198 199 /* watch for files added and deleted within USB_FS_DIR */ 200 context->wddbus = -1; 201 for (i = 0; i < MAX_USBFS_WD_COUNT; i++) 202 context->wds[i] = -1; 203 204 /* watch the root for new subdirectories */ 205 context->wdd = inotify_add_watch(context->fd, DEV_DIR, IN_CREATE | IN_DELETE); 206 if (context->wdd < 0) { 207 fprintf(stderr, "inotify_add_watch failed\n"); 208 if (discovery_done_cb) 209 discovery_done_cb(client_data); 210 return done; 211 } 212 213 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT); 214 215 /* check for existing devices first, after we have inotify set up */ 216 done = find_existing_devices(added_cb, client_data); 217 if (discovery_done_cb) 218 done |= discovery_done_cb(client_data); 219 220 return done; 221 } /* usb_host_load() */ 222 223 int usb_host_read_event(struct usb_host_context *context) 224 { 225 struct inotify_event* event; 226 char event_buf[512]; 227 char path[100]; 228 int i, ret, done = 0; 229 int offset = 0; 230 int wd; 231 232 ret = read(context->fd, event_buf, sizeof(event_buf)); 233 if (ret >= (int)sizeof(struct inotify_event)) { 234 while (offset < ret && !done) { 235 event = (struct inotify_event*)&event_buf[offset]; 236 done = 0; 237 wd = event->wd; 238 if (wd == context->wdd) { 239 if ((event->mask & IN_CREATE) && !strcmp(event->name, "bus")) { 240 context->wddbus = inotify_add_watch(context->fd, DEV_BUS_DIR, IN_CREATE | IN_DELETE); 241 if (context->wddbus < 0) { 242 done = 1; 243 } else { 244 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT); 245 done = find_existing_devices(context->cb_added, context->data); 246 } 247 } 248 } else if (wd == context->wddbus) { 249 if ((event->mask & IN_CREATE) && !strcmp(event->name, "usb")) { 250 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT); 251 done = find_existing_devices(context->cb_added, context->data); 252 } else if ((event->mask & IN_DELETE) && !strcmp(event->name, "usb")) { 253 for (i = 0; i < MAX_USBFS_WD_COUNT; i++) { 254 if (context->wds[i] >= 0) { 255 inotify_rm_watch(context->fd, context->wds[i]); 256 context->wds[i] = -1; 257 } 258 } 259 } 260 } else if (wd == context->wds[0]) { 261 i = atoi(event->name); 262 snprintf(path, sizeof(path), USB_FS_DIR "/%s", event->name); 263 D("%s subdirectory %s: index: %d\n", (event->mask & IN_CREATE) ? 264 "new" : "gone", path, i); 265 if (i > 0 && i < MAX_USBFS_WD_COUNT) { 266 int local_ret = 0; 267 if (event->mask & IN_CREATE) { 268 local_ret = inotify_add_watch(context->fd, path, 269 IN_CREATE | IN_DELETE); 270 if (local_ret >= 0) 271 context->wds[i] = local_ret; 272 done = find_existing_devices_bus(path, context->cb_added, 273 context->data); 274 } else if (event->mask & IN_DELETE) { 275 inotify_rm_watch(context->fd, context->wds[i]); 276 context->wds[i] = -1; 277 } 278 } 279 } else { 280 for (i = 1; (i < MAX_USBFS_WD_COUNT) && !done; i++) { 281 if (wd == context->wds[i]) { 282 snprintf(path, sizeof(path), USB_FS_DIR "/%03d/%s", i, event->name); 283 if (event->mask == IN_CREATE) { 284 D("new device %s\n", path); 285 done = context->cb_added(path, context->data); 286 } else if (event->mask == IN_DELETE) { 287 D("gone device %s\n", path); 288 done = context->cb_removed(path, context->data); 289 } 290 } 291 } 292 } 293 294 offset += sizeof(struct inotify_event) + event->len; 295 } 296 } 297 298 return done; 299 } /* usb_host_read_event() */ 300 301 void usb_host_run(struct usb_host_context *context, 302 usb_device_added_cb added_cb, 303 usb_device_removed_cb removed_cb, 304 usb_discovery_done_cb discovery_done_cb, 305 void *client_data) 306 { 307 int done; 308 309 done = usb_host_load(context, added_cb, removed_cb, discovery_done_cb, client_data); 310 311 while (!done) { 312 313 done = usb_host_read_event(context); 314 } 315 } /* usb_host_run() */ 316 317 struct usb_device *usb_device_open(const char *dev_name) 318 { 319 int fd, did_retry = 0, writeable = 1; 320 321 D("usb_device_open %s\n", dev_name); 322 323 retry: 324 fd = open(dev_name, O_RDWR); 325 if (fd < 0) { 326 /* if we fail, see if have read-only access */ 327 fd = open(dev_name, O_RDONLY); 328 D("usb_device_open open returned %d errno %d\n", fd, errno); 329 if (fd < 0 && (errno == EACCES || errno == ENOENT) && !did_retry) { 330 /* work around race condition between inotify and permissions management */ 331 sleep(1); 332 did_retry = 1; 333 goto retry; 334 } 335 336 if (fd < 0) 337 return NULL; 338 writeable = 0; 339 D("[ usb open read-only %s fd = %d]\n", dev_name, fd); 340 } 341 342 struct usb_device* result = usb_device_new(dev_name, fd); 343 if (result) 344 result->writeable = writeable; 345 return result; 346 } 347 348 void usb_device_close(struct usb_device *device) 349 { 350 close(device->fd); 351 free(device); 352 } 353 354 struct usb_device *usb_device_new(const char *dev_name, int fd) 355 { 356 struct usb_device *device = calloc(1, sizeof(struct usb_device)); 357 int length; 358 359 D("usb_device_new %s fd: %d\n", dev_name, fd); 360 361 if (lseek(fd, 0, SEEK_SET) != 0) 362 goto failed; 363 length = read(fd, device->desc, sizeof(device->desc)); 364 D("usb_device_new read returned %d errno %d\n", length, errno); 365 if (length < 0) 366 goto failed; 367 368 strncpy(device->dev_name, dev_name, sizeof(device->dev_name) - 1); 369 device->fd = fd; 370 device->desc_length = length; 371 // assume we are writeable, since usb_device_get_fd will only return writeable fds 372 device->writeable = 1; 373 return device; 374 375 failed: 376 close(fd); 377 free(device); 378 return NULL; 379 } 380 381 static int usb_device_reopen_writeable(struct usb_device *device) 382 { 383 if (device->writeable) 384 return 1; 385 386 int fd = open(device->dev_name, O_RDWR); 387 if (fd >= 0) { 388 close(device->fd); 389 device->fd = fd; 390 device->writeable = 1; 391 return 1; 392 } 393 D("usb_device_reopen_writeable failed errno %d\n", errno); 394 return 0; 395 } 396 397 int usb_device_get_fd(struct usb_device *device) 398 { 399 if (!usb_device_reopen_writeable(device)) 400 return -1; 401 return device->fd; 402 } 403 404 const char* usb_device_get_name(struct usb_device *device) 405 { 406 return device->dev_name; 407 } 408 409 int usb_device_get_unique_id(struct usb_device *device) 410 { 411 int bus = 0, dev = 0; 412 sscanf(device->dev_name, USB_FS_ID_SCANNER, &bus, &dev); 413 return bus * 1000 + dev; 414 } 415 416 int usb_device_get_unique_id_from_name(const char* name) 417 { 418 int bus = 0, dev = 0; 419 sscanf(name, USB_FS_ID_SCANNER, &bus, &dev); 420 return bus * 1000 + dev; 421 } 422 423 char* usb_device_get_name_from_unique_id(int id) 424 { 425 int bus = id / 1000; 426 int dev = id % 1000; 427 char* result = (char *)calloc(1, strlen(USB_FS_ID_FORMAT)); 428 snprintf(result, strlen(USB_FS_ID_FORMAT) - 1, USB_FS_ID_FORMAT, bus, dev); 429 return result; 430 } 431 432 uint16_t usb_device_get_vendor_id(struct usb_device *device) 433 { 434 struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc; 435 return __le16_to_cpu(desc->idVendor); 436 } 437 438 uint16_t usb_device_get_product_id(struct usb_device *device) 439 { 440 struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc; 441 return __le16_to_cpu(desc->idProduct); 442 } 443 444 const struct usb_device_descriptor* usb_device_get_device_descriptor(struct usb_device *device) 445 { 446 return (struct usb_device_descriptor*)device->desc; 447 } 448 449 char* usb_device_get_string(struct usb_device *device, int id) 450 { 451 char string[256]; 452 __u16 buffer[128]; 453 __u16 languages[128]; 454 int i, result; 455 int languageCount = 0; 456 457 if (id == 0) return NULL; 458 459 string[0] = 0; 460 memset(languages, 0, sizeof(languages)); 461 462 // read list of supported languages 463 result = usb_device_control_transfer(device, 464 USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR, 465 (USB_DT_STRING << 8) | 0, 0, languages, sizeof(languages), 0); 466 if (result > 0) 467 languageCount = (result - 2) / 2; 468 469 for (i = 1; i <= languageCount; i++) { 470 memset(buffer, 0, sizeof(buffer)); 471 472 result = usb_device_control_transfer(device, 473 USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR, 474 (USB_DT_STRING << 8) | id, languages[i], buffer, sizeof(buffer), 0); 475 if (result > 0) { 476 int i; 477 // skip first word, and copy the rest to the string, changing shorts to bytes. 478 result /= 2; 479 for (i = 1; i < result; i++) 480 string[i - 1] = buffer[i]; 481 string[i - 1] = 0; 482 return strdup(string); 483 } 484 } 485 486 return NULL; 487 } 488 489 char* usb_device_get_manufacturer_name(struct usb_device *device) 490 { 491 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc; 492 return usb_device_get_string(device, desc->iManufacturer); 493 } 494 495 char* usb_device_get_product_name(struct usb_device *device) 496 { 497 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc; 498 return usb_device_get_string(device, desc->iProduct); 499 } 500 501 char* usb_device_get_serial(struct usb_device *device) 502 { 503 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc; 504 return usb_device_get_string(device, desc->iSerialNumber); 505 } 506 507 int usb_device_is_writeable(struct usb_device *device) 508 { 509 return device->writeable; 510 } 511 512 void usb_descriptor_iter_init(struct usb_device *device, struct usb_descriptor_iter *iter) 513 { 514 iter->config = device->desc; 515 iter->config_end = device->desc + device->desc_length; 516 iter->curr_desc = device->desc; 517 } 518 519 struct usb_descriptor_header *usb_descriptor_iter_next(struct usb_descriptor_iter *iter) 520 { 521 struct usb_descriptor_header* next; 522 if (iter->curr_desc >= iter->config_end) 523 return NULL; 524 next = (struct usb_descriptor_header*)iter->curr_desc; 525 iter->curr_desc += next->bLength; 526 return next; 527 } 528 529 int usb_device_claim_interface(struct usb_device *device, unsigned int interface) 530 { 531 return ioctl(device->fd, USBDEVFS_CLAIMINTERFACE, &interface); 532 } 533 534 int usb_device_release_interface(struct usb_device *device, unsigned int interface) 535 { 536 return ioctl(device->fd, USBDEVFS_RELEASEINTERFACE, &interface); 537 } 538 539 int usb_device_connect_kernel_driver(struct usb_device *device, 540 unsigned int interface, int connect) 541 { 542 struct usbdevfs_ioctl ctl; 543 544 ctl.ifno = interface; 545 ctl.ioctl_code = (connect ? USBDEVFS_CONNECT : USBDEVFS_DISCONNECT); 546 ctl.data = NULL; 547 return ioctl(device->fd, USBDEVFS_IOCTL, &ctl); 548 } 549 550 int usb_device_set_configuration(struct usb_device *device, int configuration) 551 { 552 return ioctl(device->fd, USBDEVFS_SETCONFIGURATION, &configuration); 553 } 554 555 int usb_device_set_interface(struct usb_device *device, unsigned int interface, 556 unsigned int alt_setting) 557 { 558 struct usbdevfs_setinterface ctl; 559 560 ctl.interface = interface; 561 ctl.altsetting = alt_setting; 562 return ioctl(device->fd, USBDEVFS_SETINTERFACE, &ctl); 563 } 564 565 int usb_device_control_transfer(struct usb_device *device, 566 int requestType, 567 int request, 568 int value, 569 int index, 570 void* buffer, 571 int length, 572 unsigned int timeout) 573 { 574 struct usbdevfs_ctrltransfer ctrl; 575 576 // this usually requires read/write permission 577 if (!usb_device_reopen_writeable(device)) 578 return -1; 579 580 memset(&ctrl, 0, sizeof(ctrl)); 581 ctrl.bRequestType = requestType; 582 ctrl.bRequest = request; 583 ctrl.wValue = value; 584 ctrl.wIndex = index; 585 ctrl.wLength = length; 586 ctrl.data = buffer; 587 ctrl.timeout = timeout; 588 return ioctl(device->fd, USBDEVFS_CONTROL, &ctrl); 589 } 590 591 int usb_device_bulk_transfer(struct usb_device *device, 592 int endpoint, 593 void* buffer, 594 int length, 595 unsigned int timeout) 596 { 597 struct usbdevfs_bulktransfer ctrl; 598 599 // need to limit request size to avoid EINVAL 600 if (length > MAX_USBFS_BUFFER_SIZE) 601 length = MAX_USBFS_BUFFER_SIZE; 602 603 memset(&ctrl, 0, sizeof(ctrl)); 604 ctrl.ep = endpoint; 605 ctrl.len = length; 606 ctrl.data = buffer; 607 ctrl.timeout = timeout; 608 return ioctl(device->fd, USBDEVFS_BULK, &ctrl); 609 } 610 611 struct usb_request *usb_request_new(struct usb_device *dev, 612 const struct usb_endpoint_descriptor *ep_desc) 613 { 614 struct usbdevfs_urb *urb = calloc(1, sizeof(struct usbdevfs_urb)); 615 if (!urb) 616 return NULL; 617 618 if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK) 619 urb->type = USBDEVFS_URB_TYPE_BULK; 620 else if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT) 621 urb->type = USBDEVFS_URB_TYPE_INTERRUPT; 622 else { 623 D("Unsupported endpoint type %d", ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK); 624 free(urb); 625 return NULL; 626 } 627 urb->endpoint = ep_desc->bEndpointAddress; 628 629 struct usb_request *req = calloc(1, sizeof(struct usb_request)); 630 if (!req) { 631 free(urb); 632 return NULL; 633 } 634 635 req->dev = dev; 636 req->max_packet_size = __le16_to_cpu(ep_desc->wMaxPacketSize); 637 req->private_data = urb; 638 req->endpoint = urb->endpoint; 639 urb->usercontext = req; 640 641 return req; 642 } 643 644 void usb_request_free(struct usb_request *req) 645 { 646 free(req->private_data); 647 free(req); 648 } 649 650 int usb_request_queue(struct usb_request *req) 651 { 652 struct usbdevfs_urb *urb = (struct usbdevfs_urb*)req->private_data; 653 int res; 654 655 urb->status = -1; 656 urb->buffer = req->buffer; 657 // need to limit request size to avoid EINVAL 658 if (req->buffer_length > MAX_USBFS_BUFFER_SIZE) 659 urb->buffer_length = MAX_USBFS_BUFFER_SIZE; 660 else 661 urb->buffer_length = req->buffer_length; 662 663 do { 664 res = ioctl(req->dev->fd, USBDEVFS_SUBMITURB, urb); 665 } while((res < 0) && (errno == EINTR)); 666 667 return res; 668 } 669 670 struct usb_request *usb_request_wait(struct usb_device *dev) 671 { 672 struct usbdevfs_urb *urb = NULL; 673 struct usb_request *req = NULL; 674 675 while (1) { 676 int res = ioctl(dev->fd, USBDEVFS_REAPURB, &urb); 677 D("USBDEVFS_REAPURB returned %d\n", res); 678 if (res < 0) { 679 if(errno == EINTR) { 680 continue; 681 } 682 D("[ reap urb - error ]\n"); 683 return NULL; 684 } else { 685 D("[ urb @%p status = %d, actual = %d ]\n", 686 urb, urb->status, urb->actual_length); 687 req = (struct usb_request*)urb->usercontext; 688 req->actual_length = urb->actual_length; 689 } 690 break; 691 } 692 return req; 693 } 694 695 int usb_request_cancel(struct usb_request *req) 696 { 697 struct usbdevfs_urb *urb = ((struct usbdevfs_urb*)req->private_data); 698 return ioctl(req->dev->fd, USBDEVFS_DISCARDURB, urb); 699 } 700 701