urb.c 34 KB

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