1 /* 2 * message.c - synchronous message handling 3 */ 4 5 #include <linux/pci.h> /* for scatterlist macros */ 6 #include <linux/usb.h> 7 #include <linux/module.h> 8 #include <linux/slab.h> 9 #include <linux/init.h> 10 #include <linux/mm.h> 11 #include <linux/timer.h> 12 #include <linux/ctype.h> 13 #include <linux/nls.h> 14 #include <linux/device.h> 15 #include <linux/scatterlist.h> 16 #include <linux/usb/quirks.h> 17 #include <linux/usb/hcd.h> /* for usbcore internals */ 18 #include <asm/byteorder.h> 19 20 #include "usb.h" 21 22 static void cancel_async_set_config(struct usb_device *udev); 23 24 struct api_context { 25 struct completion done; 26 int status; 27 }; 28 29 static void usb_api_blocking_completion(struct urb *urb) 30 { 31 struct api_context *ctx = urb->context; 32 33 ctx->status = urb->status; 34 complete(&ctx->done); 35 } 36 37 38 /* 39 * Starts urb and waits for completion or timeout. Note that this call 40 * is NOT interruptible. Many device driver i/o requests should be 41 * interruptible and therefore these drivers should implement their 42 * own interruptible routines. 43 */ 44 static int usb_start_wait_urb(struct urb *urb, int timeout, int *actual_length) 45 { 46 struct api_context ctx; 47 unsigned long expire; 48 int retval; 49 50 init_completion(&ctx.done); 51 urb->context = &ctx; 52 urb->actual_length = 0; 53 retval = usb_submit_urb(urb, GFP_NOIO); 54 if (unlikely(retval)) 55 goto out; 56 57 expire = timeout ? msecs_to_jiffies(timeout) : MAX_SCHEDULE_TIMEOUT; 58 if (!wait_for_completion_timeout(&ctx.done, expire)) { 59 usb_kill_urb(urb); 60 retval = (ctx.status == -ENOENT ? -ETIMEDOUT : ctx.status); 61 62 dev_dbg(&urb->dev->dev, 63 "%s timed out on ep%d%s len=%u/%u\n", 64 current->comm, 65 usb_endpoint_num(&urb->ep->desc), 66 usb_urb_dir_in(urb) ? "in" : "out", 67 urb->actual_length, 68 urb->transfer_buffer_length); 69 } else 70 retval = ctx.status; 71 out: 72 if (actual_length) 73 *actual_length = urb->actual_length; 74 75 usb_free_urb(urb); 76 return retval; 77 } 78 79 /*-------------------------------------------------------------------*/ 80 /* returns status (negative) or length (positive) */ 81 static int usb_internal_control_msg(struct usb_device *usb_dev, 82 unsigned int pipe, 83 struct usb_ctrlrequest *cmd, 84 void *data, int len, int timeout) 85 { 86 struct urb *urb; 87 int retv; 88 int length; 89 90 urb = usb_alloc_urb(0, GFP_NOIO); 91 if (!urb) 92 return -ENOMEM; 93 94 usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data, 95 len, usb_api_blocking_completion, NULL); 96 97 retv = usb_start_wait_urb(urb, timeout, &length); 98 if (retv < 0) 99 return retv; 100 else 101 return length; 102 } 103 104 /** 105 * usb_control_msg - Builds a control urb, sends it off and waits for completion 106 * @dev: pointer to the usb device to send the message to 107 * @pipe: endpoint "pipe" to send the message to 108 * @request: USB message request value 109 * @requesttype: USB message request type value 110 * @value: USB message value 111 * @index: USB message index value 112 * @data: pointer to the data to send 113 * @size: length in bytes of the data to send 114 * @timeout: time in msecs to wait for the message to complete before timing 115 * out (if 0 the wait is forever) 116 * 117 * Context: !in_interrupt () 118 * 119 * This function sends a simple control message to a specified endpoint and 120 * waits for the message to complete, or timeout. 121 * 122 * If successful, it returns the number of bytes transferred, otherwise a 123 * negative error number. 124 * 125 * Don't use this function from within an interrupt context, like a bottom half 126 * handler. If you need an asynchronous message, or need to send a message 127 * from within interrupt context, use usb_submit_urb(). 128 * If a thread in your driver uses this call, make sure your disconnect() 129 * method can wait for it to complete. Since you don't have a handle on the 130 * URB used, you can't cancel the request. 131 */ 132 int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, 133 __u8 requesttype, __u16 value, __u16 index, void *data, 134 __u16 size, int timeout) 135 { 136 struct usb_ctrlrequest *dr; 137 int ret; 138 139 dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO); 140 if (!dr) 141 return -ENOMEM; 142 143 dr->bRequestType = requesttype; 144 dr->bRequest = request; 145 dr->wValue = cpu_to_le16(value); 146 dr->wIndex = cpu_to_le16(index); 147 dr->wLength = cpu_to_le16(size); 148 149 /* dbg("usb_control_msg"); */ 150 151 ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout); 152 153 kfree(dr); 154 155 return ret; 156 } 157 EXPORT_SYMBOL_GPL(usb_control_msg); 158 159 /** 160 * usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion 161 * @usb_dev: pointer to the usb device to send the message to 162 * @pipe: endpoint "pipe" to send the message to 163 * @data: pointer to the data to send 164 * @len: length in bytes of the data to send 165 * @actual_length: pointer to a location to put the actual length transferred 166 * in bytes 167 * @timeout: time in msecs to wait for the message to complete before 168 * timing out (if 0 the wait is forever) 169 * 170 * Context: !in_interrupt () 171 * 172 * This function sends a simple interrupt message to a specified endpoint and 173 * waits for the message to complete, or timeout. 174 * 175 * If successful, it returns 0, otherwise a negative error number. The number 176 * of actual bytes transferred will be stored in the actual_length paramater. 177 * 178 * Don't use this function from within an interrupt context, like a bottom half 179 * handler. If you need an asynchronous message, or need to send a message 180 * from within interrupt context, use usb_submit_urb() If a thread in your 181 * driver uses this call, make sure your disconnect() method can wait for it to 182 * complete. Since you don't have a handle on the URB used, you can't cancel 183 * the request. 184 */ 185 int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe, 186 void *data, int len, int *actual_length, int timeout) 187 { 188 return usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout); 189 } 190 EXPORT_SYMBOL_GPL(usb_interrupt_msg); 191 192 /** 193 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion 194 * @usb_dev: pointer to the usb device to send the message to 195 * @pipe: endpoint "pipe" to send the message to 196 * @data: pointer to the data to send 197 * @len: length in bytes of the data to send 198 * @actual_length: pointer to a location to put the actual length transferred 199 * in bytes 200 * @timeout: time in msecs to wait for the message to complete before 201 * timing out (if 0 the wait is forever) 202 * 203 * Context: !in_interrupt () 204 * 205 * This function sends a simple bulk message to a specified endpoint 206 * and waits for the message to complete, or timeout. 207 * 208 * If successful, it returns 0, otherwise a negative error number. The number 209 * of actual bytes transferred will be stored in the actual_length paramater. 210 * 211 * Don't use this function from within an interrupt context, like a bottom half 212 * handler. If you need an asynchronous message, or need to send a message 213 * from within interrupt context, use usb_submit_urb() If a thread in your 214 * driver uses this call, make sure your disconnect() method can wait for it to 215 * complete. Since you don't have a handle on the URB used, you can't cancel 216 * the request. 217 * 218 * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT ioctl, 219 * users are forced to abuse this routine by using it to submit URBs for 220 * interrupt endpoints. We will take the liberty of creating an interrupt URB 221 * (with the default interval) if the target is an interrupt endpoint. 222 */ 223 int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe, 224 void *data, int len, int *actual_length, int timeout) 225 { 226 struct urb *urb; 227 struct usb_host_endpoint *ep; 228 229 ep = usb_pipe_endpoint(usb_dev, pipe); 230 if (!ep || len < 0) 231 return -EINVAL; 232 233 urb = usb_alloc_urb(0, GFP_KERNEL); 234 if (!urb) 235 return -ENOMEM; 236 237 if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == 238 USB_ENDPOINT_XFER_INT) { 239 pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30); 240 usb_fill_int_urb(urb, usb_dev, pipe, data, len, 241 usb_api_blocking_completion, NULL, 242 ep->desc.bInterval); 243 } else 244 usb_fill_bulk_urb(urb, usb_dev, pipe, data, len, 245 usb_api_blocking_completion, NULL); 246 247 return usb_start_wait_urb(urb, timeout, actual_length); 248 } 249 EXPORT_SYMBOL_GPL(usb_bulk_msg); 250 251 /*-------------------------------------------------------------------*/ 252 253 static void sg_clean(struct usb_sg_request *io) 254 { 255 if (io->urbs) { 256 while (io->entries--) 257 usb_free_urb(io->urbs [io->entries]); 258 kfree(io->urbs); 259 io->urbs = NULL; 260 } 261 io->dev = NULL; 262 } 263 264 static void sg_complete(struct urb *urb) 265 { 266 struct usb_sg_request *io = urb->context; 267 int status = urb->status; 268 269 spin_lock(&io->lock); 270 271 /* In 2.5 we require hcds' endpoint queues not to progress after fault 272 * reports, until the completion callback (this!) returns. That lets 273 * device driver code (like this routine) unlink queued urbs first, 274 * if it needs to, since the HC won't work on them at all. So it's 275 * not possible for page N+1 to overwrite page N, and so on. 276 * 277 * That's only for "hard" faults; "soft" faults (unlinks) sometimes 278 * complete before the HCD can get requests away from hardware, 279 * though never during cleanup after a hard fault. 280 */ 281 if (io->status 282 && (io->status != -ECONNRESET 283 || status != -ECONNRESET) 284 && urb->actual_length) { 285 dev_err(io->dev->bus->controller, 286 "dev %s ep%d%s scatterlist error %d/%d\n", 287 io->dev->devpath, 288 usb_endpoint_num(&urb->ep->desc), 289 usb_urb_dir_in(urb) ? "in" : "out", 290 status, io->status); 291 /* BUG (); */ 292 } 293 294 if (io->status == 0 && status && status != -ECONNRESET) { 295 int i, found, retval; 296 297 io->status = status; 298 299 /* the previous urbs, and this one, completed already. 300 * unlink pending urbs so they won't rx/tx bad data. 301 * careful: unlink can sometimes be synchronous... 302 */ 303 spin_unlock(&io->lock); 304 for (i = 0, found = 0; i < io->entries; i++) { 305 if (!io->urbs [i] || !io->urbs [i]->dev) 306 continue; 307 if (found) { 308 retval = usb_unlink_urb(io->urbs [i]); 309 if (retval != -EINPROGRESS && 310 retval != -ENODEV && 311 retval != -EBUSY) 312 dev_err(&io->dev->dev, 313 "%s, unlink --> %d\n", 314 __func__, retval); 315 } else if (urb == io->urbs [i]) 316 found = 1; 317 } 318 spin_lock(&io->lock); 319 } 320 urb->dev = NULL; 321 322 /* on the last completion, signal usb_sg_wait() */ 323 io->bytes += urb->actual_length; 324 io->count--; 325 if (!io->count) 326 complete(&io->complete); 327 328 spin_unlock(&io->lock); 329 } 330 331 332 /** 333 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request 334 * @io: request block being initialized. until usb_sg_wait() returns, 335 * treat this as a pointer to an opaque block of memory, 336 * @dev: the usb device that will send or receive the data 337 * @pipe: endpoint "pipe" used to transfer the data 338 * @period: polling rate for interrupt endpoints, in frames or 339 * (for high speed endpoints) microframes; ignored for bulk 340 * @sg: scatterlist entries 341 * @nents: how many entries in the scatterlist 342 * @length: how many bytes to send from the scatterlist, or zero to 343 * send every byte identified in the list. 344 * @mem_flags: SLAB_* flags affecting memory allocations in this call 345 * 346 * Returns zero for success, else a negative errno value. This initializes a 347 * scatter/gather request, allocating resources such as I/O mappings and urb 348 * memory (except maybe memory used by USB controller drivers). 349 * 350 * The request must be issued using usb_sg_wait(), which waits for the I/O to 351 * complete (or to be canceled) and then cleans up all resources allocated by 352 * usb_sg_init(). 353 * 354 * The request may be canceled with usb_sg_cancel(), either before or after 355 * usb_sg_wait() is called. 356 */ 357 int usb_sg_init(struct usb_sg_request *io, struct usb_device *dev, 358 unsigned pipe, unsigned period, struct scatterlist *sg, 359 int nents, size_t length, gfp_t mem_flags) 360 { 361 int i; 362 int urb_flags; 363 int use_sg; 364 365 if (!io || !dev || !sg 366 || usb_pipecontrol(pipe) 367 || usb_pipeisoc(pipe) 368 || nents <= 0) 369 return -EINVAL; 370 371 spin_lock_init(&io->lock); 372 io->dev = dev; 373 io->pipe = pipe; 374 375 if (dev->bus->sg_tablesize > 0) { 376 use_sg = true; 377 io->entries = 1; 378 } else { 379 use_sg = false; 380 io->entries = nents; 381 } 382 383 /* initialize all the urbs we'll use */ 384 io->urbs = kmalloc(io->entries * sizeof *io->urbs, mem_flags); 385 if (!io->urbs) 386 goto nomem; 387 388 urb_flags = URB_NO_INTERRUPT; 389 if (usb_pipein(pipe)) 390 urb_flags |= URB_SHORT_NOT_OK; 391 392 for_each_sg(sg, sg, io->entries, i) { 393 struct urb *urb; 394 unsigned len; 395 396 urb = usb_alloc_urb(0, mem_flags); 397 if (!urb) { 398 io->entries = i; 399 goto nomem; 400 } 401 io->urbs[i] = urb; 402 403 urb->dev = NULL; 404 urb->pipe = pipe; 405 urb->interval = period; 406 urb->transfer_flags = urb_flags; 407 urb->complete = sg_complete; 408 urb->context = io; 409 urb->sg = sg; 410 411 if (use_sg) { 412 /* There is no single transfer buffer */ 413 urb->transfer_buffer = NULL; 414 urb->num_sgs = nents; 415 416 /* A length of zero means transfer the whole sg list */ 417 len = length; 418 if (len == 0) { 419 for_each_sg(sg, sg, nents, i) 420 len += sg->length; 421 } 422 } else { 423 /* 424 * Some systems can't use DMA; they use PIO instead. 425 * For their sakes, transfer_buffer is set whenever 426 * possible. 427 */ 428 if (!PageHighMem(sg_page(sg))) 429 urb->transfer_buffer = sg_virt(sg); 430 else 431 urb->transfer_buffer = NULL; 432 433 len = sg->length; 434 if (length) { 435 len = min_t(unsigned, len, length); 436 length -= len; 437 if (length == 0) 438 io->entries = i + 1; 439 } 440 } 441 urb->transfer_buffer_length = len; 442 } 443 io->urbs[--i]->transfer_flags &= ~URB_NO_INTERRUPT; 444 445 /* transaction state */ 446 io->count = io->entries; 447 io->status = 0; 448 io->bytes = 0; 449 init_completion(&io->complete); 450 return 0; 451 452 nomem: 453 sg_clean(io); 454 return -ENOMEM; 455 } 456 EXPORT_SYMBOL_GPL(usb_sg_init); 457 458 /** 459 * usb_sg_wait - synchronously execute scatter/gather request 460 * @io: request block handle, as initialized with usb_sg_init(). 461 * some fields become accessible when this call returns. 462 * Context: !in_interrupt () 463 * 464 * This function blocks until the specified I/O operation completes. It 465 * leverages the grouping of the related I/O requests to get good transfer 466 * rates, by queueing the requests. At higher speeds, such queuing can 467 * significantly improve USB throughput. 468 * 469 * There are three kinds of completion for this function. 470 * (1) success, where io->status is zero. The number of io->bytes 471 * transferred is as requested. 472 * (2) error, where io->status is a negative errno value. The number 473 * of io->bytes transferred before the error is usually less 474 * than requested, and can be nonzero. 475 * (3) cancellation, a type of error with status -ECONNRESET that 476 * is initiated by usb_sg_cancel(). 477 * 478 * When this function returns, all memory allocated through usb_sg_init() or 479 * this call will have been freed. The request block parameter may still be 480 * passed to usb_sg_cancel(), or it may be freed. It could also be 481 * reinitialized and then reused. 482 * 483 * Data Transfer Rates: 484 * 485 * Bulk transfers are valid for full or high speed endpoints. 486 * The best full speed data rate is 19 packets of 64 bytes each 487 * per frame, or 1216 bytes per millisecond. 488 * The best high speed data rate is 13 packets of 512 bytes each 489 * per microframe, or 52 KBytes per millisecond. 490 * 491 * The reason to use interrupt transfers through this API would most likely 492 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond 493 * could be transferred. That capability is less useful for low or full 494 * speed interrupt endpoints, which allow at most one packet per millisecond, 495 * of at most 8 or 64 bytes (respectively). 496 * 497 * It is not necessary to call this function to reserve bandwidth for devices 498 * under an xHCI host controller, as the bandwidth is reserved when the 499 * configuration or interface alt setting is selected. 500 */ 501 void usb_sg_wait(struct usb_sg_request *io) 502 { 503 int i; 504 int entries = io->entries; 505 506 /* queue the urbs. */ 507 spin_lock_irq(&io->lock); 508 i = 0; 509 while (i < entries && !io->status) { 510 int retval; 511 512 io->urbs[i]->dev = io->dev; 513 retval = usb_submit_urb(io->urbs [i], GFP_ATOMIC); 514 515 /* after we submit, let completions or cancelations fire; 516 * we handshake using io->status. 517 */ 518 spin_unlock_irq(&io->lock); 519 switch (retval) { 520 /* maybe we retrying will recover */ 521 case -ENXIO: /* hc didn't queue this one */ 522 case -EAGAIN: 523 case -ENOMEM: 524 io->urbs[i]->dev = NULL; 525 retval = 0; 526 yield(); 527 break; 528 529 /* no error? continue immediately. 530 * 531 * NOTE: to work better with UHCI (4K I/O buffer may 532 * need 3K of TDs) it may be good to limit how many 533 * URBs are queued at once; N milliseconds? 534 */ 535 case 0: 536 ++i; 537 cpu_relax(); 538 break; 539 540 /* fail any uncompleted urbs */ 541 default: 542 io->urbs[i]->dev = NULL; 543 io->urbs[i]->status = retval; 544 dev_dbg(&io->dev->dev, "%s, submit --> %d\n", 545 __func__, retval); 546 usb_sg_cancel(io); 547 } 548 spin_lock_irq(&io->lock); 549 if (retval && (io->status == 0 || io->status == -ECONNRESET)) 550 io->status = retval; 551 } 552 io->count -= entries - i; 553 if (io->count == 0) 554 complete(&io->complete); 555 spin_unlock_irq(&io->lock); 556 557 /* OK, yes, this could be packaged as non-blocking. 558 * So could the submit loop above ... but it's easier to 559 * solve neither problem than to solve both! 560 */ 561 wait_for_completion(&io->complete); 562 563 sg_clean(io); 564 } 565 EXPORT_SYMBOL_GPL(usb_sg_wait); 566 567 /** 568 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait() 569 * @io: request block, initialized with usb_sg_init() 570 * 571 * This stops a request after it has been started by usb_sg_wait(). 572 * It can also prevents one initialized by usb_sg_init() from starting, 573 * so that call just frees resources allocated to the request. 574 */ 575 void usb_sg_cancel(struct usb_sg_request *io) 576 { 577 unsigned long flags; 578 579 spin_lock_irqsave(&io->lock, flags); 580 581 /* shut everything down, if it didn't already */ 582 if (!io->status) { 583 int i; 584 585 io->status = -ECONNRESET; 586 spin_unlock(&io->lock); 587 for (i = 0; i < io->entries; i++) { 588 int retval; 589 590 if (!io->urbs [i]->dev) 591 continue; 592 retval = usb_unlink_urb(io->urbs [i]); 593 if (retval != -EINPROGRESS && retval != -EBUSY) 594 dev_warn(&io->dev->dev, "%s, unlink --> %d\n", 595 __func__, retval); 596 } 597 spin_lock(&io->lock); 598 } 599 spin_unlock_irqrestore(&io->lock, flags); 600 } 601 EXPORT_SYMBOL_GPL(usb_sg_cancel); 602 603 /*-------------------------------------------------------------------*/ 604 605 /** 606 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request 607 * @dev: the device whose descriptor is being retrieved 608 * @type: the descriptor type (USB_DT_*) 609 * @index: the number of the descriptor 610 * @buf: where to put the descriptor 611 * @size: how big is "buf"? 612 * Context: !in_interrupt () 613 * 614 * Gets a USB descriptor. Convenience functions exist to simplify 615 * getting some types of descriptors. Use 616 * usb_get_string() or usb_string() for USB_DT_STRING. 617 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG) 618 * are part of the device structure. 619 * In addition to a number of USB-standard descriptors, some 620 * devices also use class-specific or vendor-specific descriptors. 621 * 622 * This call is synchronous, and may not be used in an interrupt context. 623 * 624 * Returns the number of bytes received on success, or else the status code 625 * returned by the underlying usb_control_msg() call. 626 */ 627 int usb_get_descriptor(struct usb_device *dev, unsigned char type, 628 unsigned char index, void *buf, int size) 629 { 630 int i; 631 int result; 632 633 memset(buf, 0, size); /* Make sure we parse really received data */ 634 635 for (i = 0; i < 3; ++i) { 636 /* retry on length 0 or error; some devices are flakey */ 637 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), 638 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN, 639 (type << 8) + index, 0, buf, size, 640 USB_CTRL_GET_TIMEOUT); 641 if (result <= 0 && result != -ETIMEDOUT) 642 continue; 643 if (result > 1 && ((u8 *)buf)[1] != type) { 644 result = -ENODATA; 645 continue; 646 } 647 break; 648 } 649 return result; 650 } 651 EXPORT_SYMBOL_GPL(usb_get_descriptor); 652 653 /** 654 * usb_get_string - gets a string descriptor 655 * @dev: the device whose string descriptor is being retrieved 656 * @langid: code for language chosen (from string descriptor zero) 657 * @index: the number of the descriptor 658 * @buf: where to put the string 659 * @size: how big is "buf"? 660 * Context: !in_interrupt () 661 * 662 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character, 663 * in little-endian byte order). 664 * The usb_string() function will often be a convenient way to turn 665 * these strings into kernel-printable form. 666 * 667 * Strings may be referenced in device, configuration, interface, or other 668 * descriptors, and could also be used in vendor-specific ways. 669 * 670 * This call is synchronous, and may not be used in an interrupt context. 671 * 672 * Returns the number of bytes received on success, or else the status code 673 * returned by the underlying usb_control_msg() call. 674 */ 675 static int usb_get_string(struct usb_device *dev, unsigned short langid, 676 unsigned char index, void *buf, int size) 677 { 678 int i; 679 int result; 680 681 for (i = 0; i < 3; ++i) { 682 /* retry on length 0 or stall; some devices are flakey */ 683 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), 684 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN, 685 (USB_DT_STRING << 8) + index, langid, buf, size, 686 USB_CTRL_GET_TIMEOUT); 687 if (result == 0 || result == -EPIPE) 688 continue; 689 if (result > 1 && ((u8 *) buf)[1] != USB_DT_STRING) { 690 result = -ENODATA; 691 continue; 692 } 693 break; 694 } 695 return result; 696 } 697 698 static void usb_try_string_workarounds(unsigned char *buf, int *length) 699 { 700 int newlength, oldlength = *length; 701 702 for (newlength = 2; newlength + 1 < oldlength; newlength += 2) 703 if (!isprint(buf[newlength]) || buf[newlength + 1]) 704 break; 705 706 if (newlength > 2) { 707 buf[0] = newlength; 708 *length = newlength; 709 } 710 } 711 712 static int usb_string_sub(struct usb_device *dev, unsigned int langid, 713 unsigned int index, unsigned char *buf) 714 { 715 int rc; 716 717 /* Try to read the string descriptor by asking for the maximum 718 * possible number of bytes */ 719 if (dev->quirks & USB_QUIRK_STRING_FETCH_255) 720 rc = -EIO; 721 else 722 rc = usb_get_string(dev, langid, index, buf, 255); 723 724 /* If that failed try to read the descriptor length, then 725 * ask for just that many bytes */ 726 if (rc < 2) { 727 rc = usb_get_string(dev, langid, index, buf, 2); 728 if (rc == 2) 729 rc = usb_get_string(dev, langid, index, buf, buf[0]); 730 } 731 732 if (rc >= 2) { 733 if (!buf[0] && !buf[1]) 734 usb_try_string_workarounds(buf, &rc); 735 736 /* There might be extra junk at the end of the descriptor */ 737 if (buf[0] < rc) 738 rc = buf[0]; 739 740 rc = rc - (rc & 1); /* force a multiple of two */ 741 } 742 743 if (rc < 2) 744 rc = (rc < 0 ? rc : -EINVAL); 745 746 return rc; 747 } 748 749 static int usb_get_langid(struct usb_device *dev, unsigned char *tbuf) 750 { 751 int err; 752 753 if (dev->have_langid) 754 return 0; 755 756 if (dev->string_langid < 0) 757 return -EPIPE; 758 759 err = usb_string_sub(dev, 0, 0, tbuf); 760 761 /* If the string was reported but is malformed, default to english 762 * (0x0409) */ 763 if (err == -ENODATA || (err > 0 && err < 4)) { 764 dev->string_langid = 0x0409; 765 dev->have_langid = 1; 766 dev_err(&dev->dev, 767 "string descriptor 0 malformed (err = %d), " 768 "defaulting to 0x%04x\n", 769 err, dev->string_langid); 770 return 0; 771 } 772 773 /* In case of all other errors, we assume the device is not able to 774 * deal with strings at all. Set string_langid to -1 in order to 775 * prevent any string to be retrieved from the device */ 776 if (err < 0) { 777 dev_err(&dev->dev, "string descriptor 0 read error: %d\n", 778 err); 779 dev->string_langid = -1; 780 return -EPIPE; 781 } 782 783 /* always use the first langid listed */ 784 dev->string_langid = tbuf[2] | (tbuf[3] << 8); 785 dev->have_langid = 1; 786 dev_dbg(&dev->dev, "default language 0x%04x\n", 787 dev->string_langid); 788 return 0; 789 } 790 791 /** 792 * usb_string - returns UTF-8 version of a string descriptor 793 * @dev: the device whose string descriptor is being retrieved 794 * @index: the number of the descriptor 795 * @buf: where to put the string 796 * @size: how big is "buf"? 797 * Context: !in_interrupt () 798 * 799 * This converts the UTF-16LE encoded strings returned by devices, from 800 * usb_get_string_descriptor(), to null-terminated UTF-8 encoded ones 801 * that are more usable in most kernel contexts. Note that this function 802 * chooses strings in the first language supported by the device. 803 * 804 * This call is synchronous, and may not be used in an interrupt context. 805 * 806 * Returns length of the string (>= 0) or usb_control_msg status (< 0). 807 */ 808 int usb_string(struct usb_device *dev, int index, char *buf, size_t size) 809 { 810 unsigned char *tbuf; 811 int err; 812 813 if (dev->state == USB_STATE_SUSPENDED) 814 return -EHOSTUNREACH; 815 if (size <= 0 || !buf || !index) 816 return -EINVAL; 817 buf[0] = 0; 818 tbuf = kmalloc(256, GFP_NOIO); 819 if (!tbuf) 820 return -ENOMEM; 821 822 err = usb_get_langid(dev, tbuf); 823 if (err < 0) 824 goto errout; 825 826 err = usb_string_sub(dev, dev->string_langid, index, tbuf); 827 if (err < 0) 828 goto errout; 829 830 size--; /* leave room for trailing NULL char in output buffer */ 831 err = utf16s_to_utf8s((wchar_t *) &tbuf[2], (err - 2) / 2, 832 UTF16_LITTLE_ENDIAN, buf, size); 833 buf[err] = 0; 834 835 if (tbuf[1] != USB_DT_STRING) 836 dev_dbg(&dev->dev, 837 "wrong descriptor type %02x for string %d (\"%s\")\n", 838 tbuf[1], index, buf); 839 840 errout: 841 kfree(tbuf); 842 return err; 843 } 844 EXPORT_SYMBOL_GPL(usb_string); 845 846 /* one UTF-8-encoded 16-bit character has at most three bytes */ 847 #define MAX_USB_STRING_SIZE (127 * 3 + 1) 848 849 /** 850 * usb_cache_string - read a string descriptor and cache it for later use 851 * @udev: the device whose string descriptor is being read 852 * @index: the descriptor index 853 * 854 * Returns a pointer to a kmalloc'ed buffer containing the descriptor string, 855 * or NULL if the index is 0 or the string could not be read. 856 */ 857 char *usb_cache_string(struct usb_device *udev, int index) 858 { 859 char *buf; 860 char *smallbuf = NULL; 861 int len; 862 863 if (index <= 0) 864 return NULL; 865 866 buf = kmalloc(MAX_USB_STRING_SIZE, GFP_NOIO); 867 if (buf) { 868 len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE); 869 if (len > 0) { 870 smallbuf = kmalloc(++len, GFP_NOIO); 871 if (!smallbuf) 872 return buf; 873 memcpy(smallbuf, buf, len); 874 } 875 kfree(buf); 876 } 877 return smallbuf; 878 } 879 880 /* 881 * usb_get_device_descriptor - (re)reads the device descriptor (usbcore) 882 * @dev: the device whose device descriptor is being updated 883 * @size: how much of the descriptor to read 884 * Context: !in_interrupt () 885 * 886 * Updates the copy of the device descriptor stored in the device structure, 887 * which dedicates space for this purpose. 888 * 889 * Not exported, only for use by the core. If drivers really want to read 890 * the device descriptor directly, they can call usb_get_descriptor() with 891 * type = USB_DT_DEVICE and index = 0. 892 * 893 * This call is synchronous, and may not be used in an interrupt context. 894 * 895 * Returns the number of bytes received on success, or else the status code 896 * returned by the underlying usb_control_msg() call. 897 */ 898 int usb_get_device_descriptor(struct usb_device *dev, unsigned int size) 899 { 900 struct usb_device_descriptor *desc; 901 int ret; 902 903 if (size > sizeof(*desc)) 904 return -EINVAL; 905 desc = kmalloc(sizeof(*desc), GFP_NOIO); 906 if (!desc) 907 return -ENOMEM; 908 909 ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size); 910 if (ret >= 0) 911 memcpy(&dev->descriptor, desc, size); 912 kfree(desc); 913 return ret; 914 } 915 916 /** 917 * usb_get_status - issues a GET_STATUS call 918 * @dev: the device whose status is being checked 919 * @type: USB_RECIP_*; for device, interface, or endpoint 920 * @target: zero (for device), else interface or endpoint number 921 * @data: pointer to two bytes of bitmap data 922 * Context: !in_interrupt () 923 * 924 * Returns device, interface, or endpoint status. Normally only of 925 * interest to see if the device is self powered, or has enabled the 926 * remote wakeup facility; or whether a bulk or interrupt endpoint 927 * is halted ("stalled"). 928 * 929 * Bits in these status bitmaps are set using the SET_FEATURE request, 930 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt() 931 * function should be used to clear halt ("stall") status. 932 * 933 * This call is synchronous, and may not be used in an interrupt context. 934 * 935 * Returns the number of bytes received on success, or else the status code 936 * returned by the underlying usb_control_msg() call. 937 */ 938 int usb_get_status(struct usb_device *dev, int type, int target, void *data) 939 { 940 int ret; 941 u16 *status = kmalloc(sizeof(*status), GFP_KERNEL); 942 943 if (!status) 944 return -ENOMEM; 945 946 ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), 947 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status, 948 sizeof(*status), USB_CTRL_GET_TIMEOUT); 949 950 *(u16 *)data = *status; 951 kfree(status); 952 return ret; 953 } 954 EXPORT_SYMBOL_GPL(usb_get_status); 955 956 /** 957 * usb_clear_halt - tells device to clear endpoint halt/stall condition 958 * @dev: device whose endpoint is halted 959 * @pipe: endpoint "pipe" being cleared 960 * Context: !in_interrupt () 961 * 962 * This is used to clear halt conditions for bulk and interrupt endpoints, 963 * as reported by URB completion status. Endpoints that are halted are 964 * sometimes referred to as being "stalled". Such endpoints are unable 965 * to transmit or receive data until the halt status is cleared. Any URBs 966 * queued for such an endpoint should normally be unlinked by the driver 967 * before clearing the halt condition, as described in sections 5.7.5 968 * and 5.8.5 of the USB 2.0 spec. 969 * 970 * Note that control and isochronous endpoints don't halt, although control 971 * endpoints report "protocol stall" (for unsupported requests) using the 972 * same status code used to report a true stall. 973 * 974 * This call is synchronous, and may not be used in an interrupt context. 975 * 976 * Returns zero on success, or else the status code returned by the 977 * underlying usb_control_msg() call. 978 */ 979 int usb_clear_halt(struct usb_device *dev, int pipe) 980 { 981 int result; 982 int endp = usb_pipeendpoint(pipe); 983 984 if (usb_pipein(pipe)) 985 endp |= USB_DIR_IN; 986 987 /* we don't care if it wasn't halted first. in fact some devices 988 * (like some ibmcam model 1 units) seem to expect hosts to make 989 * this request for iso endpoints, which can't halt! 990 */ 991 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), 992 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT, 993 USB_ENDPOINT_HALT, endp, NULL, 0, 994 USB_CTRL_SET_TIMEOUT); 995 996 /* don't un-halt or force to DATA0 except on success */ 997 if (result < 0) 998 return result; 999 1000 /* NOTE: seems like Microsoft and Apple don't bother verifying 1001 * the clear "took", so some devices could lock up if you check... 1002 * such as the Hagiwara FlashGate DUAL. So we won't bother. 1003 * 1004 * NOTE: make sure the logic here doesn't diverge much from 1005 * the copy in usb-storage, for as long as we need two copies. 1006 */ 1007 1008 usb_reset_endpoint(dev, endp); 1009 1010 return 0; 1011 } 1012 EXPORT_SYMBOL_GPL(usb_clear_halt); 1013 1014 static int create_intf_ep_devs(struct usb_interface *intf) 1015 { 1016 struct usb_device *udev = interface_to_usbdev(intf); 1017 struct usb_host_interface *alt = intf->cur_altsetting; 1018 int i; 1019 1020 if (intf->ep_devs_created || intf->unregistering) 1021 return 0; 1022 1023 for (i = 0; i < alt->desc.bNumEndpoints; ++i) 1024 (void) usb_create_ep_devs(&intf->dev, &alt->endpoint[i], udev); 1025 intf->ep_devs_created = 1; 1026 return 0; 1027 } 1028 1029 static void remove_intf_ep_devs(struct usb_interface *intf) 1030 { 1031 struct usb_host_interface *alt = intf->cur_altsetting; 1032 int i; 1033 1034 if (!intf->ep_devs_created) 1035 return; 1036 1037 for (i = 0; i < alt->desc.bNumEndpoints; ++i) 1038 usb_remove_ep_devs(&alt->endpoint[i]); 1039 intf->ep_devs_created = 0; 1040 } 1041 1042 /** 1043 * usb_disable_endpoint -- Disable an endpoint by address 1044 * @dev: the device whose endpoint is being disabled 1045 * @epaddr: the endpoint's address. Endpoint number for output, 1046 * endpoint number + USB_DIR_IN for input 1047 * @reset_hardware: flag to erase any endpoint state stored in the 1048 * controller hardware 1049 * 1050 * Disables the endpoint for URB submission and nukes all pending URBs. 1051 * If @reset_hardware is set then also deallocates hcd/hardware state 1052 * for the endpoint. 1053 */ 1054 void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr, 1055 bool reset_hardware) 1056 { 1057 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK; 1058 struct usb_host_endpoint *ep; 1059 1060 if (!dev) 1061 return; 1062 1063 if (usb_endpoint_out(epaddr)) { 1064 ep = dev->ep_out[epnum]; 1065 if (reset_hardware) 1066 dev->ep_out[epnum] = NULL; 1067 } else { 1068 ep = dev->ep_in[epnum]; 1069 if (reset_hardware) 1070 dev->ep_in[epnum] = NULL; 1071 } 1072 if (ep) { 1073 ep->enabled = 0; 1074 usb_hcd_flush_endpoint(dev, ep); 1075 if (reset_hardware) 1076 usb_hcd_disable_endpoint(dev, ep); 1077 } 1078 } 1079 1080 /** 1081 * usb_reset_endpoint - Reset an endpoint's state. 1082 * @dev: the device whose endpoint is to be reset 1083 * @epaddr: the endpoint's address. Endpoint number for output, 1084 * endpoint number + USB_DIR_IN for input 1085 * 1086 * Resets any host-side endpoint state such as the toggle bit, 1087 * sequence number or current window. 1088 */ 1089 void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr) 1090 { 1091 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK; 1092 struct usb_host_endpoint *ep; 1093 1094 if (usb_endpoint_out(epaddr)) 1095 ep = dev->ep_out[epnum]; 1096 else 1097 ep = dev->ep_in[epnum]; 1098 if (ep) 1099 usb_hcd_reset_endpoint(dev, ep); 1100 } 1101 EXPORT_SYMBOL_GPL(usb_reset_endpoint); 1102 1103 1104 /** 1105 * usb_disable_interface -- Disable all endpoints for an interface 1106 * @dev: the device whose interface is being disabled 1107 * @intf: pointer to the interface descriptor 1108 * @reset_hardware: flag to erase any endpoint state stored in the 1109 * controller hardware 1110 * 1111 * Disables all the endpoints for the interface's current altsetting. 1112 */ 1113 void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf, 1114 bool reset_hardware) 1115 { 1116 struct usb_host_interface *alt = intf->cur_altsetting; 1117 int i; 1118 1119 for (i = 0; i < alt->desc.bNumEndpoints; ++i) { 1120 usb_disable_endpoint(dev, 1121 alt->endpoint[i].desc.bEndpointAddress, 1122 reset_hardware); 1123 } 1124 } 1125 1126 /** 1127 * usb_disable_device - Disable all the endpoints for a USB device 1128 * @dev: the device whose endpoints are being disabled 1129 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it. 1130 * 1131 * Disables all the device's endpoints, potentially including endpoint 0. 1132 * Deallocates hcd/hardware state for the endpoints (nuking all or most 1133 * pending urbs) and usbcore state for the interfaces, so that usbcore 1134 * must usb_set_configuration() before any interfaces could be used. 1135 */ 1136 void usb_disable_device(struct usb_device *dev, int skip_ep0) 1137 { 1138 int i; 1139 1140 dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__, 1141 skip_ep0 ? "non-ep0" : "all"); 1142 for (i = skip_ep0; i < 16; ++i) { 1143 usb_disable_endpoint(dev, i, true); 1144 usb_disable_endpoint(dev, i + USB_DIR_IN, true); 1145 } 1146 1147 /* getting rid of interfaces will disconnect 1148 * any drivers bound to them (a key side effect) 1149 */ 1150 if (dev->actconfig) { 1151 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) { 1152 struct usb_interface *interface; 1153 1154 /* remove this interface if it has been registered */ 1155 interface = dev->actconfig->interface[i]; 1156 if (!device_is_registered(&interface->dev)) 1157 continue; 1158 dev_dbg(&dev->dev, "unregistering interface %s\n", 1159 dev_name(&interface->dev)); 1160 interface->unregistering = 1; 1161 remove_intf_ep_devs(interface); 1162 device_del(&interface->dev); 1163 } 1164 1165 /* Now that the interfaces are unbound, nobody should 1166 * try to access them. 1167 */ 1168 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) { 1169 put_device(&dev->actconfig->interface[i]->dev); 1170 dev->actconfig->interface[i] = NULL; 1171 } 1172 dev->actconfig = NULL; 1173 if (dev->state == USB_STATE_CONFIGURED) 1174 usb_set_device_state(dev, USB_STATE_ADDRESS); 1175 } 1176 } 1177 1178 /** 1179 * usb_enable_endpoint - Enable an endpoint for USB communications 1180 * @dev: the device whose interface is being enabled 1181 * @ep: the endpoint 1182 * @reset_ep: flag to reset the endpoint state 1183 * 1184 * Resets the endpoint state if asked, and sets dev->ep_{in,out} pointers. 1185 * For control endpoints, both the input and output sides are handled. 1186 */ 1187 void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep, 1188 bool reset_ep) 1189 { 1190 int epnum = usb_endpoint_num(&ep->desc); 1191 int is_out = usb_endpoint_dir_out(&ep->desc); 1192 int is_control = usb_endpoint_xfer_control(&ep->desc); 1193 1194 if (reset_ep) 1195 usb_hcd_reset_endpoint(dev, ep); 1196 if (is_out || is_control) 1197 dev->ep_out[epnum] = ep; 1198 if (!is_out || is_control) 1199 dev->ep_in[epnum] = ep; 1200 ep->enabled = 1; 1201 } 1202 1203 /** 1204 * usb_enable_interface - Enable all the endpoints for an interface 1205 * @dev: the device whose interface is being enabled 1206 * @intf: pointer to the interface descriptor 1207 * @reset_eps: flag to reset the endpoints' state 1208 * 1209 * Enables all the endpoints for the interface's current altsetting. 1210 */ 1211 void usb_enable_interface(struct usb_device *dev, 1212 struct usb_interface *intf, bool reset_eps) 1213 { 1214 struct usb_host_interface *alt = intf->cur_altsetting; 1215 int i; 1216 1217 for (i = 0; i < alt->desc.bNumEndpoints; ++i) 1218 usb_enable_endpoint(dev, &alt->endpoint[i], reset_eps); 1219 } 1220 1221 /** 1222 * usb_set_interface - Makes a particular alternate setting be current 1223 * @dev: the device whose interface is being updated 1224 * @interface: the interface being updated 1225 * @alternate: the setting being chosen. 1226 * Context: !in_interrupt () 1227 * 1228 * This is used to enable data transfers on interfaces that may not 1229 * be enabled by default. Not all devices support such configurability. 1230 * Only the driver bound to an interface may change its setting. 1231 * 1232 * Within any given configuration, each interface may have several 1233 * alternative settings. These are often used to control levels of 1234 * bandwidth consumption. For example, the default setting for a high 1235 * speed interrupt endpoint may not send more than 64 bytes per microframe, 1236 * while interrupt transfers of up to 3KBytes per microframe are legal. 1237 * Also, isochronous endpoints may never be part of an 1238 * interface's default setting. To access such bandwidth, alternate 1239 * interface settings must be made current. 1240 * 1241 * Note that in the Linux USB subsystem, bandwidth associated with 1242 * an endpoint in a given alternate setting is not reserved until an URB 1243 * is submitted that needs that bandwidth. Some other operating systems 1244 * allocate bandwidth early, when a configuration is chosen. 1245 * 1246 * This call is synchronous, and may not be used in an interrupt context. 1247 * Also, drivers must not change altsettings while urbs are scheduled for 1248 * endpoints in that interface; all such urbs must first be completed 1249 * (perhaps forced by unlinking). 1250 * 1251 * Returns zero on success, or else the status code returned by the 1252 * underlying usb_control_msg() call. 1253 */ 1254 int usb_set_interface(struct usb_device *dev, int interface, int alternate) 1255 { 1256 struct usb_interface *iface; 1257 struct usb_host_interface *alt; 1258 struct usb_hcd *hcd = bus_to_hcd(dev->bus); 1259 int ret; 1260 int manual = 0; 1261 unsigned int epaddr; 1262 unsigned int pipe; 1263 1264 if (dev->state == USB_STATE_SUSPENDED) 1265 return -EHOSTUNREACH; 1266 1267 iface = usb_ifnum_to_if(dev, interface); 1268 if (!iface) { 1269 dev_dbg(&dev->dev, "selecting invalid interface %d\n", 1270 interface); 1271 return -EINVAL; 1272 } 1273 1274 alt = usb_altnum_to_altsetting(iface, alternate); 1275 if (!alt) { 1276 dev_warn(&dev->dev, "selecting invalid altsetting %d\n", 1277 alternate); 1278 return -EINVAL; 1279 } 1280 1281 /* Make sure we have enough bandwidth for this alternate interface. 1282 * Remove the current alt setting and add the new alt setting. 1283 */ 1284 mutex_lock(&hcd->bandwidth_mutex); 1285 ret = usb_hcd_alloc_bandwidth(dev, NULL, iface->cur_altsetting, alt); 1286 if (ret < 0) { 1287 dev_info(&dev->dev, "Not enough bandwidth for altsetting %d\n", 1288 alternate); 1289 mutex_unlock(&hcd->bandwidth_mutex); 1290 return ret; 1291 } 1292 1293 if (dev->quirks & USB_QUIRK_NO_SET_INTF) 1294 ret = -EPIPE; 1295 else 1296 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), 1297 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE, 1298 alternate, interface, NULL, 0, 5000); 1299 1300 /* 9.4.10 says devices don't need this and are free to STALL the 1301 * request if the interface only has one alternate setting. 1302 */ 1303 if (ret == -EPIPE && iface->num_altsetting == 1) { 1304 dev_dbg(&dev->dev, 1305 "manual set_interface for iface %d, alt %d\n", 1306 interface, alternate); 1307 manual = 1; 1308 } else if (ret < 0) { 1309 /* Re-instate the old alt setting */ 1310 usb_hcd_alloc_bandwidth(dev, NULL, alt, iface->cur_altsetting); 1311 mutex_unlock(&hcd->bandwidth_mutex); 1312 return ret; 1313 } 1314 mutex_unlock(&hcd->bandwidth_mutex); 1315 1316 /* FIXME drivers shouldn't need to replicate/bugfix the logic here 1317 * when they implement async or easily-killable versions of this or 1318 * other "should-be-internal" functions (like clear_halt). 1319 * should hcd+usbcore postprocess control requests? 1320 */ 1321 1322 /* prevent submissions using previous endpoint settings */ 1323 if (iface->cur_altsetting != alt) { 1324 remove_intf_ep_devs(iface); 1325 usb_remove_sysfs_intf_files(iface); 1326 } 1327 usb_disable_interface(dev, iface, true); 1328 1329 iface->cur_altsetting = alt; 1330 1331 /* If the interface only has one altsetting and the device didn't 1332 * accept the request, we attempt to carry out the equivalent action 1333 * by manually clearing the HALT feature for each endpoint in the 1334 * new altsetting. 1335 */ 1336 if (manual) { 1337 int i; 1338 1339 for (i = 0; i < alt->desc.bNumEndpoints; i++) { 1340 epaddr = alt->endpoint[i].desc.bEndpointAddress; 1341 pipe = __create_pipe(dev, 1342 USB_ENDPOINT_NUMBER_MASK & epaddr) | 1343 (usb_endpoint_out(epaddr) ? 1344 USB_DIR_OUT : USB_DIR_IN); 1345 1346 usb_clear_halt(dev, pipe); 1347 } 1348 } 1349 1350 /* 9.1.1.5: reset toggles for all endpoints in the new altsetting 1351 * 1352 * Note: 1353 * Despite EP0 is always present in all interfaces/AS, the list of 1354 * endpoints from the descriptor does not contain EP0. Due to its 1355 * omnipresence one might expect EP0 being considered "affected" by 1356 * any SetInterface request and hence assume toggles need to be reset. 1357 * However, EP0 toggles are re-synced for every individual transfer 1358 * during the SETUP stage - hence EP0 toggles are "don't care" here. 1359 * (Likewise, EP0 never "halts" on well designed devices.) 1360 */ 1361 usb_enable_interface(dev, iface, true); 1362 if (device_is_registered(&iface->dev)) { 1363 usb_create_sysfs_intf_files(iface); 1364 create_intf_ep_devs(iface); 1365 } 1366 return 0; 1367 } 1368 EXPORT_SYMBOL_GPL(usb_set_interface); 1369 1370 /** 1371 * usb_reset_configuration - lightweight device reset 1372 * @dev: the device whose configuration is being reset 1373 * 1374 * This issues a standard SET_CONFIGURATION request to the device using 1375 * the current configuration. The effect is to reset most USB-related 1376 * state in the device, including interface altsettings (reset to zero), 1377 * endpoint halts (cleared), and endpoint state (only for bulk and interrupt 1378 * endpoints). Other usbcore state is unchanged, including bindings of 1379 * usb device drivers to interfaces. 1380 * 1381 * Because this affects multiple interfaces, avoid using this with composite 1382 * (multi-interface) devices. Instead, the driver for each interface may 1383 * use usb_set_interface() on the interfaces it claims. Be careful though; 1384 * some devices don't support the SET_INTERFACE request, and others won't 1385 * reset all the interface state (notably endpoint state). Resetting the whole 1386 * configuration would affect other drivers' interfaces. 1387 * 1388 * The caller must own the device lock. 1389 * 1390 * Returns zero on success, else a negative error code. 1391 */ 1392 int usb_reset_configuration(struct usb_device *dev) 1393 { 1394 int i, retval; 1395 struct usb_host_config *config; 1396 struct usb_hcd *hcd = bus_to_hcd(dev->bus); 1397 1398 if (dev->state == USB_STATE_SUSPENDED) 1399 return -EHOSTUNREACH; 1400 1401 /* caller must have locked the device and must own 1402 * the usb bus readlock (so driver bindings are stable); 1403 * calls during probe() are fine 1404 */ 1405 1406 for (i = 1; i < 16; ++i) { 1407 usb_disable_endpoint(dev, i, true); 1408 usb_disable_endpoint(dev, i + USB_DIR_IN, true); 1409 } 1410 1411 config = dev->actconfig; 1412 retval = 0; 1413 mutex_lock(&hcd->bandwidth_mutex); 1414 /* Make sure we have enough bandwidth for each alternate setting 0 */ 1415 for (i = 0; i < config->desc.bNumInterfaces; i++) { 1416 struct usb_interface *intf = config->interface[i]; 1417 struct usb_host_interface *alt; 1418 1419 alt = usb_altnum_to_altsetting(intf, 0); 1420 if (!alt) 1421 alt = &intf->altsetting[0]; 1422 if (alt != intf->cur_altsetting) 1423 retval = usb_hcd_alloc_bandwidth(dev, NULL, 1424 intf->cur_altsetting, alt); 1425 if (retval < 0) 1426 break; 1427 } 1428 /* If not, reinstate the old alternate settings */ 1429 if (retval < 0) { 1430 reset_old_alts: 1431 for (i--; i >= 0; i--) { 1432 struct usb_interface *intf = config->interface[i]; 1433 struct usb_host_interface *alt; 1434 1435 alt = usb_altnum_to_altsetting(intf, 0); 1436 if (!alt) 1437 alt = &intf->altsetting[0]; 1438 if (alt != intf->cur_altsetting) 1439 usb_hcd_alloc_bandwidth(dev, NULL, 1440 alt, intf->cur_altsetting); 1441 } 1442 mutex_unlock(&hcd->bandwidth_mutex); 1443 return retval; 1444 } 1445 retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), 1446 USB_REQ_SET_CONFIGURATION, 0, 1447 config->desc.bConfigurationValue, 0, 1448 NULL, 0, USB_CTRL_SET_TIMEOUT); 1449 if (retval < 0) 1450 goto reset_old_alts; 1451 mutex_unlock(&hcd->bandwidth_mutex); 1452 1453 /* re-init hc/hcd interface/endpoint state */ 1454 for (i = 0; i < config->desc.bNumInterfaces; i++) { 1455 struct usb_interface *intf = config->interface[i]; 1456 struct usb_host_interface *alt; 1457 1458 alt = usb_altnum_to_altsetting(intf, 0); 1459 1460 /* No altsetting 0? We'll assume the first altsetting. 1461 * We could use a GetInterface call, but if a device is 1462 * so non-compliant that it doesn't have altsetting 0 1463 * then I wouldn't trust its reply anyway. 1464 */ 1465 if (!alt) 1466 alt = &intf->altsetting[0]; 1467 1468 if (alt != intf->cur_altsetting) { 1469 remove_intf_ep_devs(intf); 1470 usb_remove_sysfs_intf_files(intf); 1471 } 1472 intf->cur_altsetting = alt; 1473 usb_enable_interface(dev, intf, true); 1474 if (device_is_registered(&intf->dev)) { 1475 usb_create_sysfs_intf_files(intf); 1476 create_intf_ep_devs(intf); 1477 } 1478 } 1479 return 0; 1480 } 1481 EXPORT_SYMBOL_GPL(usb_reset_configuration); 1482 1483 static void usb_release_interface(struct device *dev) 1484 { 1485 struct usb_interface *intf = to_usb_interface(dev); 1486 struct usb_interface_cache *intfc = 1487 altsetting_to_usb_interface_cache(intf->altsetting); 1488 1489 kref_put(&intfc->ref, usb_release_interface_cache); 1490 kfree(intf); 1491 } 1492 1493 #ifdef CONFIG_HOTPLUG 1494 static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env) 1495 { 1496 struct usb_device *usb_dev; 1497 struct usb_interface *intf; 1498 struct usb_host_interface *alt; 1499 1500 intf = to_usb_interface(dev); 1501 usb_dev = interface_to_usbdev(intf); 1502 alt = intf->cur_altsetting; 1503 1504 if (add_uevent_var(env, "INTERFACE=%d/%d/%d", 1505 alt->desc.bInterfaceClass, 1506 alt->desc.bInterfaceSubClass, 1507 alt->desc.bInterfaceProtocol)) 1508 return -ENOMEM; 1509 1510 if (add_uevent_var(env, 1511 "MODALIAS=usb:" 1512 "v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02X", 1513 le16_to_cpu(usb_dev->descriptor.idVendor), 1514 le16_to_cpu(usb_dev->descriptor.idProduct), 1515 le16_to_cpu(usb_dev->descriptor.bcdDevice), 1516 usb_dev->descriptor.bDeviceClass, 1517 usb_dev->descriptor.bDeviceSubClass, 1518 usb_dev->descriptor.bDeviceProtocol, 1519 alt->desc.bInterfaceClass, 1520 alt->desc.bInterfaceSubClass, 1521 alt->desc.bInterfaceProtocol)) 1522 return -ENOMEM; 1523 1524 return 0; 1525 } 1526 1527 #else 1528 1529 static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env) 1530 { 1531 return -ENODEV; 1532 } 1533 #endif /* CONFIG_HOTPLUG */ 1534 1535 struct device_type usb_if_device_type = { 1536 .name = "usb_interface", 1537 .release = usb_release_interface, 1538 .uevent = usb_if_uevent, 1539 }; 1540 1541 static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev, 1542 struct usb_host_config *config, 1543 u8 inum) 1544 { 1545 struct usb_interface_assoc_descriptor *retval = NULL; 1546 struct usb_interface_assoc_descriptor *intf_assoc; 1547 int first_intf; 1548 int last_intf; 1549 int i; 1550 1551 for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) { 1552 intf_assoc = config->intf_assoc[i]; 1553 if (intf_assoc->bInterfaceCount == 0) 1554 continue; 1555 1556 first_intf = intf_assoc->bFirstInterface; 1557 last_intf = first_intf + (intf_assoc->bInterfaceCount - 1); 1558 if (inum >= first_intf && inum <= last_intf) { 1559 if (!retval) 1560 retval = intf_assoc; 1561 else 1562 dev_err(&dev->dev, "Interface #%d referenced" 1563 " by multiple IADs\n", inum); 1564 } 1565 } 1566 1567 return retval; 1568 } 1569 1570 1571 /* 1572 * Internal function to queue a device reset 1573 * 1574 * This is initialized into the workstruct in 'struct 1575 * usb_device->reset_ws' that is launched by 1576 * message.c:usb_set_configuration() when initializing each 'struct 1577 * usb_interface'. 1578 * 1579 * It is safe to get the USB device without reference counts because 1580 * the life cycle of @iface is bound to the life cycle of @udev. Then, 1581 * this function will be ran only if @iface is alive (and before 1582 * freeing it any scheduled instances of it will have been cancelled). 1583 * 1584 * We need to set a flag (usb_dev->reset_running) because when we call 1585 * the reset, the interfaces might be unbound. The current interface 1586 * cannot try to remove the queued work as it would cause a deadlock 1587 * (you cannot remove your work from within your executing 1588 * workqueue). This flag lets it know, so that 1589 * usb_cancel_queued_reset() doesn't try to do it. 1590 * 1591 * See usb_queue_reset_device() for more details 1592 */ 1593 static void __usb_queue_reset_device(struct work_struct *ws) 1594 { 1595 int rc; 1596 struct usb_interface *iface = 1597 container_of(ws, struct usb_interface, reset_ws); 1598 struct usb_device *udev = interface_to_usbdev(iface); 1599 1600 rc = usb_lock_device_for_reset(udev, iface); 1601 if (rc >= 0) { 1602 iface->reset_running = 1; 1603 usb_reset_device(udev); 1604 iface->reset_running = 0; 1605 usb_unlock_device(udev); 1606 } 1607 } 1608 1609 1610 /* 1611 * usb_set_configuration - Makes a particular device setting be current 1612 * @dev: the device whose configuration is being updated 1613 * @configuration: the configuration being chosen. 1614 * Context: !in_interrupt(), caller owns the device lock 1615 * 1616 * This is used to enable non-default device modes. Not all devices 1617 * use this kind of configurability; many devices only have one 1618 * configuration. 1619 * 1620 * @configuration is the value of the configuration to be installed. 1621 * According to the USB spec (e.g. section 9.1.1.5), configuration values 1622 * must be non-zero; a value of zero indicates that the device in 1623 * unconfigured. However some devices erroneously use 0 as one of their 1624 * configuration values. To help manage such devices, this routine will 1625 * accept @configuration = -1 as indicating the device should be put in 1626 * an unconfigured state. 1627 * 1628 * USB device configurations may affect Linux interoperability, 1629 * power consumption and the functionality available. For example, 1630 * the default configuration is limited to using 100mA of bus power, 1631 * so that when certain device functionality requires more power, 1632 * and the device is bus powered, that functionality should be in some 1633 * non-default device configuration. Other device modes may also be 1634 * reflected as configuration options, such as whether two ISDN 1635 * channels are available independently; and choosing between open 1636 * standard device protocols (like CDC) or proprietary ones. 1637 * 1638 * Note that a non-authorized device (dev->authorized == 0) will only 1639 * be put in unconfigured mode. 1640 * 1641 * Note that USB has an additional level of device configurability, 1642 * associated with interfaces. That configurability is accessed using 1643 * usb_set_interface(). 1644 * 1645 * This call is synchronous. The calling context must be able to sleep, 1646 * must own the device lock, and must not hold the driver model's USB 1647 * bus mutex; usb interface driver probe() methods cannot use this routine. 1648 * 1649 * Returns zero on success, or else the status code returned by the 1650 * underlying call that failed. On successful completion, each interface 1651 * in the original device configuration has been destroyed, and each one 1652 * in the new configuration has been probed by all relevant usb device 1653 * drivers currently known to the kernel. 1654 */ 1655 int usb_set_configuration(struct usb_device *dev, int configuration) 1656 { 1657 int i, ret; 1658 struct usb_host_config *cp = NULL; 1659 struct usb_interface **new_interfaces = NULL; 1660 struct usb_hcd *hcd = bus_to_hcd(dev->bus); 1661 int n, nintf; 1662 1663 if (dev->authorized == 0 || configuration == -1) 1664 configuration = 0; 1665 else { 1666 for (i = 0; i < dev->descriptor.bNumConfigurations; i++) { 1667 if (dev->config[i].desc.bConfigurationValue == 1668 configuration) { 1669 cp = &dev->config[i]; 1670 break; 1671 } 1672 } 1673 } 1674 if ((!cp && configuration != 0)) 1675 return -EINVAL; 1676 1677 /* The USB spec says configuration 0 means unconfigured. 1678 * But if a device includes a configuration numbered 0, 1679 * we will accept it as a correctly configured state. 1680 * Use -1 if you really want to unconfigure the device. 1681 */ 1682 if (cp && configuration == 0) 1683 dev_warn(&dev->dev, "config 0 descriptor??\n"); 1684 1685 /* Allocate memory for new interfaces before doing anything else, 1686 * so that if we run out then nothing will have changed. */ 1687 n = nintf = 0; 1688 if (cp) { 1689 nintf = cp->desc.bNumInterfaces; 1690 new_interfaces = kmalloc(nintf * sizeof(*new_interfaces), 1691 GFP_NOIO); 1692 if (!new_interfaces) { 1693 dev_err(&dev->dev, "Out of memory\n"); 1694 return -ENOMEM; 1695 } 1696 1697 for (; n < nintf; ++n) { 1698 new_interfaces[n] = kzalloc( 1699 sizeof(struct usb_interface), 1700 GFP_NOIO); 1701 if (!new_interfaces[n]) { 1702 dev_err(&dev->dev, "Out of memory\n"); 1703 ret = -ENOMEM; 1704 free_interfaces: 1705 while (--n >= 0) 1706 kfree(new_interfaces[n]); 1707 kfree(new_interfaces); 1708 return ret; 1709 } 1710 } 1711 1712 i = dev->bus_mA - cp->desc.bMaxPower * 2; 1713 if (i < 0) 1714 dev_warn(&dev->dev, "new config #%d exceeds power " 1715 "limit by %dmA\n", 1716 configuration, -i); 1717 } 1718 1719 /* Wake up the device so we can send it the Set-Config request */ 1720 ret = usb_autoresume_device(dev); 1721 if (ret) 1722 goto free_interfaces; 1723 1724 /* Make sure we have bandwidth (and available HCD resources) for this 1725 * configuration. Remove endpoints from the schedule if we're dropping 1726 * this configuration to set configuration 0. After this point, the 1727 * host controller will not allow submissions to dropped endpoints. If 1728 * this call fails, the device state is unchanged. 1729 */ 1730 mutex_lock(&hcd->bandwidth_mutex); 1731 ret = usb_hcd_alloc_bandwidth(dev, cp, NULL, NULL); 1732 if (ret < 0) { 1733 usb_autosuspend_device(dev); 1734 mutex_unlock(&hcd->bandwidth_mutex); 1735 goto free_interfaces; 1736 } 1737 1738 /* if it's already configured, clear out old state first. 1739 * getting rid of old interfaces means unbinding their drivers. 1740 */ 1741 if (dev->state != USB_STATE_ADDRESS) 1742 usb_disable_device(dev, 1); /* Skip ep0 */ 1743 1744 /* Get rid of pending async Set-Config requests for this device */ 1745 cancel_async_set_config(dev); 1746 1747 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), 1748 USB_REQ_SET_CONFIGURATION, 0, configuration, 0, 1749 NULL, 0, USB_CTRL_SET_TIMEOUT); 1750 if (ret < 0) { 1751 /* All the old state is gone, so what else can we do? 1752 * The device is probably useless now anyway. 1753 */ 1754 cp = NULL; 1755 } 1756 1757 dev->actconfig = cp; 1758 if (!cp) { 1759 usb_set_device_state(dev, USB_STATE_ADDRESS); 1760 usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL); 1761 usb_autosuspend_device(dev); 1762 mutex_unlock(&hcd->bandwidth_mutex); 1763 goto free_interfaces; 1764 } 1765 mutex_unlock(&hcd->bandwidth_mutex); 1766 usb_set_device_state(dev, USB_STATE_CONFIGURED); 1767 1768 /* Initialize the new interface structures and the 1769 * hc/hcd/usbcore interface/endpoint state. 1770 */ 1771 for (i = 0; i < nintf; ++i) { 1772 struct usb_interface_cache *intfc; 1773 struct usb_interface *intf; 1774 struct usb_host_interface *alt; 1775 1776 cp->interface[i] = intf = new_interfaces[i]; 1777 intfc = cp->intf_cache[i]; 1778 intf->altsetting = intfc->altsetting; 1779 intf->num_altsetting = intfc->num_altsetting; 1780 intf->intf_assoc = find_iad(dev, cp, i); 1781 kref_get(&intfc->ref); 1782 1783 alt = usb_altnum_to_altsetting(intf, 0); 1784 1785 /* No altsetting 0? We'll assume the first altsetting. 1786 * We could use a GetInterface call, but if a device is 1787 * so non-compliant that it doesn't have altsetting 0 1788 * then I wouldn't trust its reply anyway. 1789 */ 1790 if (!alt) 1791 alt = &intf->altsetting[0]; 1792 1793 intf->cur_altsetting = alt; 1794 usb_enable_interface(dev, intf, true); 1795 intf->dev.parent = &dev->dev; 1796 intf->dev.driver = NULL; 1797 intf->dev.bus = &usb_bus_type; 1798 intf->dev.type = &usb_if_device_type; 1799 intf->dev.groups = usb_interface_groups; 1800 intf->dev.dma_mask = dev->dev.dma_mask; 1801 INIT_WORK(&intf->reset_ws, __usb_queue_reset_device); 1802 device_initialize(&intf->dev); 1803 dev_set_name(&intf->dev, "%d-%s:%d.%d", 1804 dev->bus->busnum, dev->devpath, 1805 configuration, alt->desc.bInterfaceNumber); 1806 } 1807 kfree(new_interfaces); 1808 1809 if (cp->string == NULL && 1810 !(dev->quirks & USB_QUIRK_CONFIG_INTF_STRINGS)) 1811 cp->string = usb_cache_string(dev, cp->desc.iConfiguration); 1812 1813 /* Now that all the interfaces are set up, register them 1814 * to trigger binding of drivers to interfaces. probe() 1815 * routines may install different altsettings and may 1816 * claim() any interfaces not yet bound. Many class drivers 1817 * need that: CDC, audio, video, etc. 1818 */ 1819 for (i = 0; i < nintf; ++i) { 1820 struct usb_interface *intf = cp->interface[i]; 1821 1822 dev_dbg(&dev->dev, 1823 "adding %s (config #%d, interface %d)\n", 1824 dev_name(&intf->dev), configuration, 1825 intf->cur_altsetting->desc.bInterfaceNumber); 1826 device_enable_async_suspend(&intf->dev); 1827 ret = device_add(&intf->dev); 1828 if (ret != 0) { 1829 dev_err(&dev->dev, "device_add(%s) --> %d\n", 1830 dev_name(&intf->dev), ret); 1831 continue; 1832 } 1833 create_intf_ep_devs(intf); 1834 } 1835 1836 usb_autosuspend_device(dev); 1837 return 0; 1838 } 1839 1840 static LIST_HEAD(set_config_list); 1841 static DEFINE_SPINLOCK(set_config_lock); 1842 1843 struct set_config_request { 1844 struct usb_device *udev; 1845 int config; 1846 struct work_struct work; 1847 struct list_head node; 1848 }; 1849 1850 /* Worker routine for usb_driver_set_configuration() */ 1851 static void driver_set_config_work(struct work_struct *work) 1852 { 1853 struct set_config_request *req = 1854 container_of(work, struct set_config_request, work); 1855 struct usb_device *udev = req->udev; 1856 1857 usb_lock_device(udev); 1858 spin_lock(&set_config_lock); 1859 list_del(&req->node); 1860 spin_unlock(&set_config_lock); 1861 1862 if (req->config >= -1) /* Is req still valid? */ 1863 usb_set_configuration(udev, req->config); 1864 usb_unlock_device(udev); 1865 usb_put_dev(udev); 1866 kfree(req); 1867 } 1868 1869 /* Cancel pending Set-Config requests for a device whose configuration 1870 * was just changed 1871 */ 1872 static void cancel_async_set_config(struct usb_device *udev) 1873 { 1874 struct set_config_request *req; 1875 1876 spin_lock(&set_config_lock); 1877 list_for_each_entry(req, &set_config_list, node) { 1878 if (req->udev == udev) 1879 req->config = -999; /* Mark as cancelled */ 1880 } 1881 spin_unlock(&set_config_lock); 1882 } 1883 1884 /** 1885 * usb_driver_set_configuration - Provide a way for drivers to change device configurations 1886 * @udev: the device whose configuration is being updated 1887 * @config: the configuration being chosen. 1888 * Context: In process context, must be able to sleep 1889 * 1890 * Device interface drivers are not allowed to change device configurations. 1891 * This is because changing configurations will destroy the interface the 1892 * driver is bound to and create new ones; it would be like a floppy-disk 1893 * driver telling the computer to replace the floppy-disk drive with a 1894 * tape drive! 1895 * 1896 * Still, in certain specialized circumstances the need may arise. This 1897 * routine gets around the normal restrictions by using a work thread to 1898 * submit the change-config request. 1899 * 1900 * Returns 0 if the request was successfully queued, error code otherwise. 1901 * The caller has no way to know whether the queued request will eventually 1902 * succeed. 1903 */ 1904 int usb_driver_set_configuration(struct usb_device *udev, int config) 1905 { 1906 struct set_config_request *req; 1907 1908 req = kmalloc(sizeof(*req), GFP_KERNEL); 1909 if (!req) 1910 return -ENOMEM; 1911 req->udev = udev; 1912 req->config = config; 1913 INIT_WORK(&req->work, driver_set_config_work); 1914 1915 spin_lock(&set_config_lock); 1916 list_add(&req->node, &set_config_list); 1917 spin_unlock(&set_config_lock); 1918 1919 usb_get_dev(udev); 1920 schedule_work(&req->work); 1921 return 0; 1922 } 1923 EXPORT_SYMBOL_GPL(usb_driver_set_configuration); 1924