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