message.c 49 KB

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