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