message.c 48 KB

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