message.c 52 KB

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