message.c 52 KB

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