1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Released under the GPLv2 only. 4 */ 5 6 #include <linux/module.h> 7 #include <linux/string.h> 8 #include <linux/bitops.h> 9 #include <linux/slab.h> 10 #include <linux/log2.h> 11 #include <linux/kmsan.h> 12 #include <linux/usb.h> 13 #include <linux/wait.h> 14 #include <linux/usb/hcd.h> 15 #include <linux/scatterlist.h> 16 17 #define to_urb(d) container_of(d, struct urb, kref) 18 19 20 static void urb_destroy(struct kref *kref) 21 { 22 struct urb *urb = to_urb(kref); 23 24 if (urb->transfer_flags & URB_FREE_BUFFER) 25 kfree(urb->transfer_buffer); 26 27 kfree(urb); 28 } 29 30 /** 31 * usb_init_urb - initializes a urb so that it can be used by a USB driver 32 * @urb: pointer to the urb to initialize 33 * 34 * Initializes a urb so that the USB subsystem can use it properly. 35 * 36 * If a urb is created with a call to usb_alloc_urb() it is not 37 * necessary to call this function. Only use this if you allocate the 38 * space for a struct urb on your own. If you call this function, be 39 * careful when freeing the memory for your urb that it is no longer in 40 * use by the USB core. 41 * 42 * Only use this function if you _really_ understand what you are doing. 43 */ 44 void usb_init_urb(struct urb *urb) 45 { 46 if (urb) { 47 memset(urb, 0, sizeof(*urb)); 48 kref_init(&urb->kref); 49 INIT_LIST_HEAD(&urb->urb_list); 50 INIT_LIST_HEAD(&urb->anchor_list); 51 } 52 } 53 EXPORT_SYMBOL_GPL(usb_init_urb); 54 55 /** 56 * usb_alloc_urb - creates a new urb for a USB driver to use 57 * @iso_packets: number of iso packets for this urb 58 * @mem_flags: the type of memory to allocate, see kmalloc() for a list of 59 * valid options for this. 60 * 61 * Creates an urb for the USB driver to use, initializes a few internal 62 * structures, increments the usage counter, and returns a pointer to it. 63 * 64 * If the driver want to use this urb for interrupt, control, or bulk 65 * endpoints, pass '0' as the number of iso packets. 66 * 67 * The driver must call usb_free_urb() when it is finished with the urb. 68 * 69 * Return: A pointer to the new urb, or %NULL if no memory is available. 70 */ 71 struct urb *usb_alloc_urb(int iso_packets, gfp_t mem_flags) 72 { 73 struct urb *urb; 74 75 urb = kmalloc_flex(*urb, iso_frame_desc, iso_packets, mem_flags); 76 if (!urb) 77 return NULL; 78 usb_init_urb(urb); 79 return urb; 80 } 81 EXPORT_SYMBOL_GPL(usb_alloc_urb); 82 83 /** 84 * usb_free_urb - frees the memory used by a urb when all users of it are finished 85 * @urb: pointer to the urb to free, may be NULL 86 * 87 * Must be called when a user of a urb is finished with it. When the last user 88 * of the urb calls this function, the memory of the urb is freed. 89 * 90 * Note: The transfer buffer associated with the urb is not freed unless the 91 * URB_FREE_BUFFER transfer flag is set. 92 */ 93 void usb_free_urb(struct urb *urb) 94 { 95 if (urb) 96 kref_put(&urb->kref, urb_destroy); 97 } 98 EXPORT_SYMBOL_GPL(usb_free_urb); 99 100 /** 101 * usb_get_urb - increments the reference count of the urb 102 * @urb: pointer to the urb to modify, may be NULL 103 * 104 * This must be called whenever a urb is transferred from a device driver to a 105 * host controller driver. This allows proper reference counting to happen 106 * for urbs. 107 * 108 * Return: A pointer to the urb with the incremented reference counter. 109 */ 110 struct urb *usb_get_urb(struct urb *urb) 111 { 112 if (urb) 113 kref_get(&urb->kref); 114 return urb; 115 } 116 EXPORT_SYMBOL_GPL(usb_get_urb); 117 118 /** 119 * usb_anchor_urb - anchors an URB while it is processed 120 * @urb: pointer to the urb to anchor 121 * @anchor: pointer to the anchor 122 * 123 * This can be called to have access to URBs which are to be executed 124 * without bothering to track them 125 */ 126 void usb_anchor_urb(struct urb *urb, struct usb_anchor *anchor) 127 { 128 unsigned long flags; 129 130 spin_lock_irqsave(&anchor->lock, flags); 131 usb_get_urb(urb); 132 list_add_tail(&urb->anchor_list, &anchor->urb_list); 133 urb->anchor = anchor; 134 135 if (unlikely(anchor->poisoned)) 136 atomic_inc(&urb->reject); 137 138 spin_unlock_irqrestore(&anchor->lock, flags); 139 } 140 EXPORT_SYMBOL_GPL(usb_anchor_urb); 141 142 static int usb_anchor_check_wakeup(struct usb_anchor *anchor) 143 { 144 return atomic_read(&anchor->suspend_wakeups) == 0 && 145 list_empty(&anchor->urb_list); 146 } 147 148 /* Callers must hold anchor->lock */ 149 static void __usb_unanchor_urb(struct urb *urb, struct usb_anchor *anchor) 150 { 151 urb->anchor = NULL; 152 list_del(&urb->anchor_list); 153 usb_put_urb(urb); 154 if (usb_anchor_check_wakeup(anchor)) 155 wake_up(&anchor->wait); 156 } 157 158 /** 159 * usb_unanchor_urb - unanchors an URB 160 * @urb: pointer to the urb to anchor 161 * 162 * Call this to stop the system keeping track of this URB 163 */ 164 void usb_unanchor_urb(struct urb *urb) 165 { 166 unsigned long flags; 167 struct usb_anchor *anchor; 168 169 if (!urb) 170 return; 171 172 anchor = urb->anchor; 173 if (!anchor) 174 return; 175 176 spin_lock_irqsave(&anchor->lock, flags); 177 /* 178 * At this point, we could be competing with another thread which 179 * has the same intention. To protect the urb from being unanchored 180 * twice, only the winner of the race gets the job. 181 */ 182 if (likely(anchor == urb->anchor)) 183 __usb_unanchor_urb(urb, anchor); 184 spin_unlock_irqrestore(&anchor->lock, flags); 185 } 186 EXPORT_SYMBOL_GPL(usb_unanchor_urb); 187 188 /*-------------------------------------------------------------------*/ 189 190 static const int pipetypes[4] = { 191 PIPE_CONTROL, PIPE_ISOCHRONOUS, PIPE_BULK, PIPE_INTERRUPT 192 }; 193 194 /** 195 * usb_pipe_type_check - sanity check of a specific pipe for a usb device 196 * @dev: struct usb_device to be checked 197 * @pipe: pipe to check 198 * 199 * This performs a light-weight sanity check for the endpoint in the 200 * given usb device. It returns 0 if the pipe is valid for the specific usb 201 * device, otherwise a negative error code. 202 */ 203 int usb_pipe_type_check(struct usb_device *dev, unsigned int pipe) 204 { 205 const struct usb_host_endpoint *ep; 206 207 ep = usb_pipe_endpoint(dev, pipe); 208 if (!ep) 209 return -EINVAL; 210 if (usb_pipetype(pipe) != pipetypes[usb_endpoint_type(&ep->desc)]) 211 return -EINVAL; 212 return 0; 213 } 214 EXPORT_SYMBOL_GPL(usb_pipe_type_check); 215 216 /** 217 * usb_urb_ep_type_check - sanity check of endpoint in the given urb 218 * @urb: urb to be checked 219 * 220 * This performs a light-weight sanity check for the endpoint in the 221 * given urb. It returns 0 if the urb contains a valid endpoint, otherwise 222 * a negative error code. 223 */ 224 int usb_urb_ep_type_check(const struct urb *urb) 225 { 226 return usb_pipe_type_check(urb->dev, urb->pipe); 227 } 228 EXPORT_SYMBOL_GPL(usb_urb_ep_type_check); 229 230 /** 231 * usb_submit_urb - issue an asynchronous transfer request for an endpoint 232 * @urb: pointer to the urb describing the request 233 * @mem_flags: the type of memory to allocate, see kmalloc() for a list 234 * of valid options for this. 235 * 236 * This submits a transfer request, and transfers control of the URB 237 * describing that request to the USB subsystem. Request completion will 238 * be indicated later, asynchronously, by calling the completion handler. 239 * The three types of completion are success, error, and unlink 240 * (a software-induced fault, also called "request cancellation"). 241 * 242 * URBs may be submitted in interrupt context. 243 * 244 * The caller must have correctly initialized the URB before submitting 245 * it. Functions such as usb_fill_bulk_urb() and usb_fill_control_urb() are 246 * available to ensure that most fields are correctly initialized, for 247 * the particular kind of transfer, although they will not initialize 248 * any transfer flags. 249 * 250 * If the submission is successful, the complete() callback from the URB 251 * will be called exactly once, when the USB core and Host Controller Driver 252 * (HCD) are finished with the URB. When the completion function is called, 253 * control of the URB is returned to the device driver which issued the 254 * request. The completion handler may then immediately free or reuse that 255 * URB. 256 * 257 * The USB core makes no guarantees at all about the context in which 258 * the complete() callback is invoked. It may be in process context, 259 * interrupt context, BH context, or anything else. Also, local interrupts 260 * may be enabled or disabled. To deal with this, the callback routine 261 * must always use the _irqsave and _irqrestore variants of things like 262 * spin_lock(), and it must always use GFP_ATOMIC for its memory 263 * allocation flags. 264 * 265 * With few exceptions, USB device drivers should never access URB fields 266 * provided by usbcore or the HCD until its complete() is called. 267 * The exceptions relate to periodic transfer scheduling. For both 268 * interrupt and isochronous urbs, as part of successful URB submission 269 * urb->interval is modified to reflect the actual transfer period used 270 * (normally some power of two units). And for isochronous urbs, 271 * urb->start_frame is modified to reflect when the URB's transfers were 272 * scheduled to start. 273 * 274 * Not all isochronous transfer scheduling policies will work, but most 275 * host controller drivers should easily handle ISO queues going from now 276 * until 10-200 msec into the future. Drivers should try to keep at 277 * least one or two msec of data in the queue; many controllers require 278 * that new transfers start at least 1 msec in the future when they are 279 * added. If the driver is unable to keep up and the queue empties out, 280 * the behavior for new submissions is governed by the URB_ISO_ASAP flag. 281 * If the flag is set, or if the queue is idle, then the URB is always 282 * assigned to the first available (and not yet expired) slot in the 283 * endpoint's schedule. If the flag is not set and the queue is active 284 * then the URB is always assigned to the next slot in the schedule 285 * following the end of the endpoint's previous URB, even if that slot is 286 * in the past. When a packet is assigned in this way to a slot that has 287 * already expired, the packet is not transmitted and the corresponding 288 * usb_iso_packet_descriptor's status field will return -EXDEV. If this 289 * would happen to all the packets in the URB, submission fails with a 290 * -EXDEV error code. 291 * 292 * For control endpoints, the synchronous usb_control_msg() call is 293 * often used (in non-interrupt context) instead of this call. 294 * That is often used through convenience wrappers, for the requests 295 * that are standardized in the USB 2.0 specification. For bulk 296 * endpoints, a synchronous usb_bulk_msg() call is available. 297 * 298 * Return: 299 * 0 on successful submissions. A negative error number otherwise. 300 * 301 * Request Queuing: 302 * 303 * URBs may be submitted to endpoints before previous ones complete, to 304 * minimize the impact of interrupt latencies and system overhead on data 305 * throughput. With that queuing policy, an endpoint's queue would never 306 * be empty. This is required for continuous isochronous data streams, 307 * and may also be required for some kinds of interrupt transfers. Such 308 * queuing also maximizes bandwidth utilization by letting USB controllers 309 * start work on later requests before driver software has finished the 310 * completion processing for earlier (successful) requests. 311 * 312 * As of Linux 2.6, all USB endpoint transfer queues support depths greater 313 * than one. This was previously a HCD-specific behavior, except for ISO 314 * transfers. Non-isochronous endpoint queues are inactive during cleanup 315 * after faults (transfer errors or cancellation). 316 * 317 * Reserved Bandwidth Transfers: 318 * 319 * Periodic transfers (interrupt or isochronous) are performed repeatedly, 320 * using the interval specified in the urb. Submitting the first urb to 321 * the endpoint reserves the bandwidth necessary to make those transfers. 322 * If the USB subsystem can't allocate sufficient bandwidth to perform 323 * the periodic request, submitting such a periodic request should fail. 324 * 325 * For devices under xHCI, the bandwidth is reserved at configuration time, or 326 * when the alt setting is selected. If there is not enough bus bandwidth, the 327 * configuration/alt setting request will fail. Therefore, submissions to 328 * periodic endpoints on devices under xHCI should never fail due to bandwidth 329 * constraints. 330 * 331 * Device drivers must explicitly request that repetition, by ensuring that 332 * some URB is always on the endpoint's queue (except possibly for short 333 * periods during completion callbacks). When there is no longer an urb 334 * queued, the endpoint's bandwidth reservation is canceled. This means 335 * drivers can use their completion handlers to ensure they keep bandwidth 336 * they need, by reinitializing and resubmitting the just-completed urb 337 * until the driver longer needs that periodic bandwidth. 338 * 339 * Memory Flags: 340 * 341 * The general rules for how to decide which mem_flags to use 342 * are the same as for kmalloc. There are four 343 * different possible values; GFP_KERNEL, GFP_NOFS, GFP_NOIO and 344 * GFP_ATOMIC. 345 * 346 * GFP_NOFS is not ever used, as it has not been implemented yet. 347 * 348 * GFP_ATOMIC is used when 349 * (a) you are inside a completion handler, an interrupt, bottom half, 350 * tasklet or timer, or 351 * (b) you are holding a spinlock or rwlock (does not apply to 352 * semaphores), or 353 * (c) current->state != TASK_RUNNING, this is the case only after 354 * you've changed it. 355 * 356 * GFP_NOIO is used in the block io path and error handling of storage 357 * devices. 358 * 359 * All other situations use GFP_KERNEL. 360 * 361 * Some more specific rules for mem_flags can be inferred, such as 362 * (1) start_xmit, timeout, and receive methods of network drivers must 363 * use GFP_ATOMIC (they are called with a spinlock held); 364 * (2) queuecommand methods of scsi drivers must use GFP_ATOMIC (also 365 * called with a spinlock held); 366 * (3) If you use a kernel thread with a network driver you must use 367 * GFP_NOIO, unless (b) or (c) apply; 368 * (4) after you have done a down() you can use GFP_KERNEL, unless (b) or (c) 369 * apply or your are in a storage driver's block io path; 370 * (5) USB probe and disconnect can use GFP_KERNEL unless (b) or (c) apply; and 371 * (6) changing firmware on a running storage or net device uses 372 * GFP_NOIO, unless b) or c) apply 373 * 374 */ 375 int usb_submit_urb(struct urb *urb, gfp_t mem_flags) 376 { 377 int xfertype, max; 378 struct usb_device *dev; 379 struct usb_host_endpoint *ep; 380 int is_out; 381 unsigned int allowed; 382 bool is_eusb2_isoch_double; 383 384 if (!urb || !urb->complete) 385 return -EINVAL; 386 if (urb->hcpriv) { 387 WARN_ONCE(1, "URB %p submitted while active\n", urb); 388 return -EBUSY; 389 } 390 391 dev = urb->dev; 392 if ((!dev) || (dev->state < USB_STATE_UNAUTHENTICATED)) 393 return -ENODEV; 394 395 /* For now, get the endpoint from the pipe. Eventually drivers 396 * will be required to set urb->ep directly and we will eliminate 397 * urb->pipe. 398 */ 399 ep = usb_pipe_endpoint(dev, urb->pipe); 400 if (!ep) 401 return -ENOENT; 402 403 urb->ep = ep; 404 urb->status = -EINPROGRESS; 405 urb->actual_length = 0; 406 407 /* Lots of sanity checks, so HCDs can rely on clean data 408 * and don't need to duplicate tests 409 */ 410 xfertype = usb_endpoint_type(&ep->desc); 411 if (xfertype == USB_ENDPOINT_XFER_CONTROL) { 412 struct usb_ctrlrequest *setup = 413 (struct usb_ctrlrequest *) urb->setup_packet; 414 415 if (!setup) 416 return -ENOEXEC; 417 is_out = !(setup->bRequestType & USB_DIR_IN) || 418 !setup->wLength; 419 dev_WARN_ONCE(&dev->dev, (usb_pipeout(urb->pipe) != is_out), 420 "BOGUS control dir, pipe %x doesn't match bRequestType %x\n", 421 urb->pipe, setup->bRequestType); 422 if (le16_to_cpu(setup->wLength) != urb->transfer_buffer_length) { 423 dev_dbg(&dev->dev, "BOGUS control len %d doesn't match transfer length %d\n", 424 le16_to_cpu(setup->wLength), 425 urb->transfer_buffer_length); 426 return -EBADR; 427 } 428 } else { 429 is_out = usb_endpoint_dir_out(&ep->desc); 430 } 431 432 /* Clear the internal flags and cache the direction for later use */ 433 urb->transfer_flags &= ~(URB_DIR_MASK | URB_DMA_MAP_SINGLE | 434 URB_DMA_MAP_PAGE | URB_DMA_MAP_SG | URB_MAP_LOCAL | 435 URB_SETUP_MAP_SINGLE | URB_SETUP_MAP_LOCAL | 436 URB_DMA_SG_COMBINED); 437 urb->transfer_flags |= (is_out ? URB_DIR_OUT : URB_DIR_IN); 438 kmsan_handle_urb(urb, is_out); 439 440 if (xfertype != USB_ENDPOINT_XFER_CONTROL && 441 dev->state < USB_STATE_CONFIGURED) 442 return -ENODEV; 443 444 max = usb_endpoint_maxp(&ep->desc); 445 is_eusb2_isoch_double = usb_endpoint_is_hs_isoc_double(dev, ep); 446 if (!max && !is_eusb2_isoch_double) { 447 dev_dbg(&dev->dev, 448 "bogus endpoint ep%d%s in %s (bad maxpacket %d)\n", 449 usb_endpoint_num(&ep->desc), is_out ? "out" : "in", 450 __func__, max); 451 return -EMSGSIZE; 452 } 453 454 /* periodic transfers limit size per frame/uframe, 455 * but drivers only control those sizes for ISO. 456 * while we're checking, initialize return status. 457 */ 458 if (xfertype == USB_ENDPOINT_XFER_ISOC) { 459 int n, len; 460 461 /* SuperSpeed isoc endpoints have up to 16 bursts of up to 462 * 3 packets each 463 */ 464 if (dev->speed >= USB_SPEED_SUPER) { 465 int burst = 1 + ep->ss_ep_comp.bMaxBurst; 466 int mult = USB_SS_MULT(ep->ss_ep_comp.bmAttributes); 467 max *= burst; 468 max *= mult; 469 } 470 471 if (dev->speed == USB_SPEED_SUPER_PLUS && 472 USB_SS_SSP_ISOC_COMP(ep->ss_ep_comp.bmAttributes)) { 473 struct usb_ssp_isoc_ep_comp_descriptor *isoc_ep_comp; 474 475 isoc_ep_comp = &ep->ssp_isoc_ep_comp; 476 max = le32_to_cpu(isoc_ep_comp->dwBytesPerInterval); 477 } 478 479 /* High speed, 1-3 packets/uframe, max 6 for eUSB2 double bw */ 480 if (dev->speed == USB_SPEED_HIGH) { 481 if (is_eusb2_isoch_double) 482 max = le32_to_cpu(ep->eusb2_isoc_ep_comp.dwBytesPerInterval); 483 else 484 max *= usb_endpoint_maxp_mult(&ep->desc); 485 } 486 487 if (urb->number_of_packets <= 0) 488 return -EINVAL; 489 for (n = 0; n < urb->number_of_packets; n++) { 490 len = urb->iso_frame_desc[n].length; 491 if (len < 0 || len > max) 492 return -EMSGSIZE; 493 urb->iso_frame_desc[n].status = -EXDEV; 494 urb->iso_frame_desc[n].actual_length = 0; 495 } 496 } else if (urb->num_sgs && !urb->dev->bus->no_sg_constraint) { 497 struct scatterlist *sg; 498 int i; 499 500 for_each_sg(urb->sg, sg, urb->num_sgs - 1, i) 501 if (sg->length % max) 502 return -EINVAL; 503 } 504 505 /* the I/O buffer must be mapped/unmapped, except when length=0 */ 506 if (urb->transfer_buffer_length > INT_MAX) 507 return -EMSGSIZE; 508 509 /* 510 * stuff that drivers shouldn't do, but which shouldn't 511 * cause problems in HCDs if they get it wrong. 512 */ 513 514 /* Check that the pipe's type matches the endpoint's type */ 515 if (usb_pipe_type_check(urb->dev, urb->pipe)) 516 dev_warn_once(&dev->dev, "BOGUS urb xfer, pipe %x != type %x\n", 517 usb_pipetype(urb->pipe), pipetypes[xfertype]); 518 519 /* Check against a simple/standard policy */ 520 allowed = (URB_NO_TRANSFER_DMA_MAP | URB_NO_INTERRUPT | URB_DIR_MASK | 521 URB_FREE_BUFFER); 522 switch (xfertype) { 523 case USB_ENDPOINT_XFER_BULK: 524 case USB_ENDPOINT_XFER_INT: 525 if (is_out) 526 allowed |= URB_ZERO_PACKET; 527 fallthrough; 528 default: /* all non-iso endpoints */ 529 if (!is_out) 530 allowed |= URB_SHORT_NOT_OK; 531 break; 532 case USB_ENDPOINT_XFER_ISOC: 533 allowed |= URB_ISO_ASAP; 534 break; 535 } 536 allowed &= urb->transfer_flags; 537 538 /* warn if submitter gave bogus flags */ 539 if (allowed != urb->transfer_flags) 540 dev_WARN(&dev->dev, "BOGUS urb flags, %x --> %x\n", 541 urb->transfer_flags, allowed); 542 543 /* 544 * Force periodic transfer intervals to be legal values that are 545 * a power of two (so HCDs don't need to). 546 * 547 * FIXME want bus->{intr,iso}_sched_horizon values here. Each HC 548 * supports different values... this uses EHCI/UHCI defaults (and 549 * EHCI can use smaller non-default values). 550 */ 551 switch (xfertype) { 552 case USB_ENDPOINT_XFER_ISOC: 553 case USB_ENDPOINT_XFER_INT: 554 /* too small? */ 555 if (urb->interval <= 0) 556 return -EINVAL; 557 558 /* too big? */ 559 switch (dev->speed) { 560 case USB_SPEED_SUPER_PLUS: 561 case USB_SPEED_SUPER: /* units are 125us */ 562 /* Handle up to 2^(16-1) microframes */ 563 if (urb->interval > (1 << 15)) 564 return -EINVAL; 565 max = 1 << 15; 566 break; 567 case USB_SPEED_HIGH: /* units are microframes */ 568 /* NOTE usb handles 2^15 */ 569 if (urb->interval > (1024 * 8)) 570 urb->interval = 1024 * 8; 571 max = 1024 * 8; 572 break; 573 case USB_SPEED_FULL: /* units are frames/msec */ 574 case USB_SPEED_LOW: 575 if (xfertype == USB_ENDPOINT_XFER_INT) { 576 if (urb->interval > 255) 577 return -EINVAL; 578 /* NOTE ohci only handles up to 32 */ 579 max = 128; 580 } else { 581 if (urb->interval > 1024) 582 urb->interval = 1024; 583 /* NOTE usb and ohci handle up to 2^15 */ 584 max = 1024; 585 } 586 break; 587 default: 588 return -EINVAL; 589 } 590 /* Round down to a power of 2, no more than max */ 591 urb->interval = min(max, 1 << ilog2(urb->interval)); 592 } 593 594 return usb_hcd_submit_urb(urb, mem_flags); 595 } 596 EXPORT_SYMBOL_GPL(usb_submit_urb); 597 598 /*-------------------------------------------------------------------*/ 599 600 /** 601 * usb_unlink_urb - abort/cancel a transfer request for an endpoint 602 * @urb: pointer to urb describing a previously submitted request, 603 * may be NULL 604 * 605 * This routine cancels an in-progress request. URBs complete only once 606 * per submission, and may be canceled only once per submission. 607 * Successful cancellation means termination of @urb will be expedited 608 * and the completion handler will be called with a status code 609 * indicating that the request has been canceled (rather than any other 610 * code). 611 * 612 * Drivers should not call this routine or related routines, such as 613 * usb_kill_urb(), after their disconnect method has returned. The 614 * disconnect function should synchronize with a driver's I/O routines 615 * to insure that all URB-related activity has completed before it returns. 616 * 617 * This request is asynchronous, however the HCD might call the ->complete() 618 * callback during unlink. Therefore when drivers call usb_unlink_urb(), they 619 * must not hold any locks that may be taken by the completion function. 620 * Success is indicated by returning -EINPROGRESS, at which time the URB will 621 * probably not yet have been given back to the device driver. When it is 622 * eventually called, the completion function will see @urb->status == 623 * -ECONNRESET. 624 * Failure is indicated by usb_unlink_urb() returning any other value. 625 * Unlinking will fail when @urb is not currently "linked" (i.e., it was 626 * never submitted, or it was unlinked before, or the hardware is already 627 * finished with it), even if the completion handler has not yet run. 628 * 629 * The URB must not be deallocated while this routine is running. In 630 * particular, when a driver calls this routine, it must insure that the 631 * completion handler cannot deallocate the URB. 632 * 633 * Return: -EINPROGRESS on success. See description for other values on 634 * failure. 635 * 636 * Unlinking and Endpoint Queues: 637 * 638 * [The behaviors and guarantees described below do not apply to virtual 639 * root hubs but only to endpoint queues for physical USB devices.] 640 * 641 * Host Controller Drivers (HCDs) place all the URBs for a particular 642 * endpoint in a queue. Normally the queue advances as the controller 643 * hardware processes each request. But when an URB terminates with an 644 * error its queue generally stops (see below), at least until that URB's 645 * completion routine returns. It is guaranteed that a stopped queue 646 * will not restart until all its unlinked URBs have been fully retired, 647 * with their completion routines run, even if that's not until some time 648 * after the original completion handler returns. The same behavior and 649 * guarantee apply when an URB terminates because it was unlinked. 650 * 651 * Bulk and interrupt endpoint queues are guaranteed to stop whenever an 652 * URB terminates with any sort of error, including -ECONNRESET, -ENOENT, 653 * and -EREMOTEIO. Control endpoint queues behave the same way except 654 * that they are not guaranteed to stop for -EREMOTEIO errors. Queues 655 * for isochronous endpoints are treated differently, because they must 656 * advance at fixed rates. Such queues do not stop when an URB 657 * encounters an error or is unlinked. An unlinked isochronous URB may 658 * leave a gap in the stream of packets; it is undefined whether such 659 * gaps can be filled in. 660 * 661 * Note that early termination of an URB because a short packet was 662 * received will generate a -EREMOTEIO error if and only if the 663 * URB_SHORT_NOT_OK flag is set. By setting this flag, USB device 664 * drivers can build deep queues for large or complex bulk transfers 665 * and clean them up reliably after any sort of aborted transfer by 666 * unlinking all pending URBs at the first fault. 667 * 668 * When a control URB terminates with an error other than -EREMOTEIO, it 669 * is quite likely that the status stage of the transfer will not take 670 * place. 671 */ 672 int usb_unlink_urb(struct urb *urb) 673 { 674 if (!urb) 675 return -EINVAL; 676 if (!urb->dev) 677 return -ENODEV; 678 if (!urb->ep) 679 return -EIDRM; 680 return usb_hcd_unlink_urb(urb, -ECONNRESET); 681 } 682 EXPORT_SYMBOL_GPL(usb_unlink_urb); 683 684 /** 685 * usb_kill_urb - cancel a transfer request and wait for it to finish 686 * @urb: pointer to URB describing a previously submitted request, 687 * may be NULL 688 * 689 * This routine cancels an in-progress request. It is guaranteed that 690 * upon return all completion handlers will have finished and the URB 691 * will be totally idle and available for reuse. These features make 692 * this an ideal way to stop I/O in a disconnect() callback or close() 693 * function. If the request has not already finished or been unlinked 694 * the completion handler will see urb->status == -ENOENT. 695 * 696 * While the routine is running, attempts to resubmit the URB will fail 697 * with error -EPERM. Thus even if the URB's completion handler always 698 * tries to resubmit, it will not succeed and the URB will become idle. 699 * 700 * The URB must not be deallocated while this routine is running. In 701 * particular, when a driver calls this routine, it must insure that the 702 * completion handler cannot deallocate the URB. 703 * 704 * This routine may not be used in an interrupt context (such as a bottom 705 * half or a completion handler), or when holding a spinlock, or in other 706 * situations where the caller can't schedule(). 707 * 708 * This routine should not be called by a driver after its disconnect 709 * method has returned. 710 */ 711 void usb_kill_urb(struct urb *urb) 712 { 713 might_sleep(); 714 if (!(urb && urb->dev && urb->ep)) 715 return; 716 atomic_inc(&urb->reject); 717 /* 718 * Order the write of urb->reject above before the read 719 * of urb->use_count below. Pairs with the barriers in 720 * __usb_hcd_giveback_urb() and usb_hcd_submit_urb(). 721 */ 722 smp_mb__after_atomic(); 723 724 usb_hcd_unlink_urb(urb, -ENOENT); 725 wait_event(usb_kill_urb_queue, atomic_read(&urb->use_count) == 0); 726 727 atomic_dec(&urb->reject); 728 } 729 EXPORT_SYMBOL_GPL(usb_kill_urb); 730 731 /** 732 * usb_poison_urb - reliably kill a transfer and prevent further use of an URB 733 * @urb: pointer to URB describing a previously submitted request, 734 * may be NULL 735 * 736 * This routine cancels an in-progress request. It is guaranteed that 737 * upon return all completion handlers will have finished and the URB 738 * will be totally idle and cannot be reused. These features make 739 * this an ideal way to stop I/O in a disconnect() callback. 740 * If the request has not already finished or been unlinked 741 * the completion handler will see urb->status == -ENOENT. 742 * 743 * After and while the routine runs, attempts to resubmit the URB will fail 744 * with error -EPERM. Thus even if the URB's completion handler always 745 * tries to resubmit, it will not succeed and the URB will become idle. 746 * 747 * The URB must not be deallocated while this routine is running. In 748 * particular, when a driver calls this routine, it must insure that the 749 * completion handler cannot deallocate the URB. 750 * 751 * This routine may not be used in an interrupt context (such as a bottom 752 * half or a completion handler), or when holding a spinlock, or in other 753 * situations where the caller can't schedule(). 754 * 755 * This routine should not be called by a driver after its disconnect 756 * method has returned. 757 */ 758 void usb_poison_urb(struct urb *urb) 759 { 760 might_sleep(); 761 if (!urb) 762 return; 763 atomic_inc(&urb->reject); 764 /* 765 * Order the write of urb->reject above before the read 766 * of urb->use_count below. Pairs with the barriers in 767 * __usb_hcd_giveback_urb() and usb_hcd_submit_urb(). 768 */ 769 smp_mb__after_atomic(); 770 771 if (!urb->dev || !urb->ep) 772 return; 773 774 usb_hcd_unlink_urb(urb, -ENOENT); 775 wait_event(usb_kill_urb_queue, atomic_read(&urb->use_count) == 0); 776 } 777 EXPORT_SYMBOL_GPL(usb_poison_urb); 778 779 void usb_unpoison_urb(struct urb *urb) 780 { 781 if (!urb) 782 return; 783 784 atomic_dec(&urb->reject); 785 } 786 EXPORT_SYMBOL_GPL(usb_unpoison_urb); 787 788 /** 789 * usb_block_urb - reliably prevent further use of an URB 790 * @urb: pointer to URB to be blocked, may be NULL 791 * 792 * After the routine has run, attempts to resubmit the URB will fail 793 * with error -EPERM. Thus even if the URB's completion handler always 794 * tries to resubmit, it will not succeed and the URB will become idle. 795 * 796 * The URB must not be deallocated while this routine is running. In 797 * particular, when a driver calls this routine, it must insure that the 798 * completion handler cannot deallocate the URB. 799 */ 800 void usb_block_urb(struct urb *urb) 801 { 802 if (!urb) 803 return; 804 805 atomic_inc(&urb->reject); 806 } 807 EXPORT_SYMBOL_GPL(usb_block_urb); 808 809 /** 810 * usb_kill_anchored_urbs - kill all URBs associated with an anchor 811 * @anchor: anchor the requests are bound to 812 * 813 * This kills all outstanding URBs starting from the back of the queue, 814 * with guarantee that no completer callbacks will take place from the 815 * anchor after this function returns. 816 * 817 * This routine should not be called by a driver after its disconnect 818 * method has returned. 819 */ 820 void usb_kill_anchored_urbs(struct usb_anchor *anchor) 821 { 822 struct urb *victim; 823 int surely_empty; 824 825 do { 826 spin_lock_irq(&anchor->lock); 827 while (!list_empty(&anchor->urb_list)) { 828 victim = list_entry(anchor->urb_list.prev, 829 struct urb, anchor_list); 830 /* make sure the URB isn't freed before we kill it */ 831 usb_get_urb(victim); 832 spin_unlock_irq(&anchor->lock); 833 /* this will unanchor the URB */ 834 usb_kill_urb(victim); 835 usb_put_urb(victim); 836 spin_lock_irq(&anchor->lock); 837 } 838 surely_empty = usb_anchor_check_wakeup(anchor); 839 840 spin_unlock_irq(&anchor->lock); 841 cpu_relax(); 842 } while (!surely_empty); 843 } 844 EXPORT_SYMBOL_GPL(usb_kill_anchored_urbs); 845 846 847 /** 848 * usb_poison_anchored_urbs - cease all traffic from an anchor 849 * @anchor: anchor the requests are bound to 850 * 851 * this allows all outstanding URBs to be poisoned starting 852 * from the back of the queue. Newly added URBs will also be 853 * poisoned 854 * 855 * This routine should not be called by a driver after its disconnect 856 * method has returned. 857 */ 858 void usb_poison_anchored_urbs(struct usb_anchor *anchor) 859 { 860 struct urb *victim; 861 int surely_empty; 862 863 do { 864 spin_lock_irq(&anchor->lock); 865 anchor->poisoned = 1; 866 while (!list_empty(&anchor->urb_list)) { 867 victim = list_entry(anchor->urb_list.prev, 868 struct urb, anchor_list); 869 /* make sure the URB isn't freed before we kill it */ 870 usb_get_urb(victim); 871 spin_unlock_irq(&anchor->lock); 872 /* this will unanchor the URB */ 873 usb_poison_urb(victim); 874 usb_put_urb(victim); 875 spin_lock_irq(&anchor->lock); 876 } 877 surely_empty = usb_anchor_check_wakeup(anchor); 878 879 spin_unlock_irq(&anchor->lock); 880 cpu_relax(); 881 } while (!surely_empty); 882 } 883 EXPORT_SYMBOL_GPL(usb_poison_anchored_urbs); 884 885 /** 886 * usb_unpoison_anchored_urbs - let an anchor be used successfully again 887 * @anchor: anchor the requests are bound to 888 * 889 * Reverses the effect of usb_poison_anchored_urbs 890 * the anchor can be used normally after it returns 891 */ 892 void usb_unpoison_anchored_urbs(struct usb_anchor *anchor) 893 { 894 unsigned long flags; 895 struct urb *lazarus; 896 897 spin_lock_irqsave(&anchor->lock, flags); 898 list_for_each_entry(lazarus, &anchor->urb_list, anchor_list) { 899 usb_unpoison_urb(lazarus); 900 } 901 anchor->poisoned = 0; 902 spin_unlock_irqrestore(&anchor->lock, flags); 903 } 904 EXPORT_SYMBOL_GPL(usb_unpoison_anchored_urbs); 905 906 /** 907 * usb_anchor_suspend_wakeups 908 * @anchor: the anchor you want to suspend wakeups on 909 * 910 * Call this to stop the last urb being unanchored from waking up any 911 * usb_wait_anchor_empty_timeout waiters. This is used in the hcd urb give- 912 * back path to delay waking up until after the completion handler has run. 913 */ 914 void usb_anchor_suspend_wakeups(struct usb_anchor *anchor) 915 { 916 if (anchor) 917 atomic_inc(&anchor->suspend_wakeups); 918 } 919 EXPORT_SYMBOL_GPL(usb_anchor_suspend_wakeups); 920 921 /** 922 * usb_anchor_resume_wakeups 923 * @anchor: the anchor you want to resume wakeups on 924 * 925 * Allow usb_wait_anchor_empty_timeout waiters to be woken up again, and 926 * wake up any current waiters if the anchor is empty. 927 */ 928 void usb_anchor_resume_wakeups(struct usb_anchor *anchor) 929 { 930 if (!anchor) 931 return; 932 933 atomic_dec(&anchor->suspend_wakeups); 934 if (usb_anchor_check_wakeup(anchor)) 935 wake_up(&anchor->wait); 936 } 937 EXPORT_SYMBOL_GPL(usb_anchor_resume_wakeups); 938 939 /** 940 * usb_wait_anchor_empty_timeout - wait for an anchor to be unused 941 * @anchor: the anchor you want to become unused 942 * @timeout: how long you are willing to wait in milliseconds 943 * 944 * Call this is you want to be sure all an anchor's 945 * URBs have finished 946 * 947 * Return: Non-zero if the anchor became unused. Zero on timeout. 948 */ 949 int usb_wait_anchor_empty_timeout(struct usb_anchor *anchor, 950 unsigned int timeout) 951 { 952 return wait_event_timeout(anchor->wait, 953 usb_anchor_check_wakeup(anchor), 954 msecs_to_jiffies(timeout)); 955 } 956 EXPORT_SYMBOL_GPL(usb_wait_anchor_empty_timeout); 957 958 /** 959 * usb_get_from_anchor - get an anchor's oldest urb 960 * @anchor: the anchor whose urb you want 961 * 962 * This will take the oldest urb from an anchor, unanchor and return it with 963 * a reference held. 964 * 965 * Return: The oldest urb from @anchor, or %NULL if @anchor has no 966 * urbs associated with it. 967 */ 968 struct urb *usb_get_from_anchor(struct usb_anchor *anchor) 969 { 970 struct urb *victim; 971 unsigned long flags; 972 973 spin_lock_irqsave(&anchor->lock, flags); 974 if (!list_empty(&anchor->urb_list)) { 975 victim = list_entry(anchor->urb_list.next, struct urb, 976 anchor_list); 977 usb_get_urb(victim); 978 __usb_unanchor_urb(victim, anchor); 979 } else { 980 victim = NULL; 981 } 982 spin_unlock_irqrestore(&anchor->lock, flags); 983 984 return victim; 985 } 986 987 EXPORT_SYMBOL_GPL(usb_get_from_anchor); 988 989 /** 990 * usb_scuttle_anchored_urbs - unanchor all an anchor's urbs 991 * @anchor: the anchor whose urbs you want to unanchor 992 * 993 * use this to get rid of all an anchor's urbs 994 */ 995 void usb_scuttle_anchored_urbs(struct usb_anchor *anchor) 996 { 997 struct urb *victim; 998 unsigned long flags; 999 int surely_empty; 1000 1001 do { 1002 spin_lock_irqsave(&anchor->lock, flags); 1003 while (!list_empty(&anchor->urb_list)) { 1004 victim = list_entry(anchor->urb_list.prev, 1005 struct urb, anchor_list); 1006 __usb_unanchor_urb(victim, anchor); 1007 } 1008 surely_empty = usb_anchor_check_wakeup(anchor); 1009 1010 spin_unlock_irqrestore(&anchor->lock, flags); 1011 cpu_relax(); 1012 } while (!surely_empty); 1013 } 1014 1015 EXPORT_SYMBOL_GPL(usb_scuttle_anchored_urbs); 1016 1017 /** 1018 * usb_anchor_empty - is an anchor empty 1019 * @anchor: the anchor you want to query 1020 * 1021 * Return: 1 if the anchor has no urbs associated with it. 1022 */ 1023 int usb_anchor_empty(struct usb_anchor *anchor) 1024 { 1025 return list_empty(&anchor->urb_list); 1026 } 1027 1028 EXPORT_SYMBOL_GPL(usb_anchor_empty); 1029 1030