message.c 51 KB

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