message.c 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576
  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, struct pt_regs *regs)
  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, struct pt_regs *regs)
  219. {
  220. struct usb_sg_request *io = (struct usb_sg_request *) 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], SLAB_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. Note that several fields are
  737. * converted to the host CPU's byte order: the USB version (bcdUSB), and
  738. * vendors product and version fields (idVendor, idProduct, and bcdDevice).
  739. * That lets device drivers compare against non-byteswapped constants.
  740. *
  741. * Not exported, only for use by the core. If drivers really want to read
  742. * the device descriptor directly, they can call usb_get_descriptor() with
  743. * type = USB_DT_DEVICE and index = 0.
  744. *
  745. * This call is synchronous, and may not be used in an interrupt context.
  746. *
  747. * Returns the number of bytes received on success, or else the status code
  748. * returned by the underlying usb_control_msg() call.
  749. */
  750. int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
  751. {
  752. struct usb_device_descriptor *desc;
  753. int ret;
  754. if (size > sizeof(*desc))
  755. return -EINVAL;
  756. desc = kmalloc(sizeof(*desc), GFP_NOIO);
  757. if (!desc)
  758. return -ENOMEM;
  759. ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
  760. if (ret >= 0)
  761. memcpy(&dev->descriptor, desc, size);
  762. kfree(desc);
  763. return ret;
  764. }
  765. /**
  766. * usb_get_status - issues a GET_STATUS call
  767. * @dev: the device whose status is being checked
  768. * @type: USB_RECIP_*; for device, interface, or endpoint
  769. * @target: zero (for device), else interface or endpoint number
  770. * @data: pointer to two bytes of bitmap data
  771. * Context: !in_interrupt ()
  772. *
  773. * Returns device, interface, or endpoint status. Normally only of
  774. * interest to see if the device is self powered, or has enabled the
  775. * remote wakeup facility; or whether a bulk or interrupt endpoint
  776. * is halted ("stalled").
  777. *
  778. * Bits in these status bitmaps are set using the SET_FEATURE request,
  779. * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
  780. * function should be used to clear halt ("stall") status.
  781. *
  782. * This call is synchronous, and may not be used in an interrupt context.
  783. *
  784. * Returns the number of bytes received on success, or else the status code
  785. * returned by the underlying usb_control_msg() call.
  786. */
  787. int usb_get_status(struct usb_device *dev, int type, int target, void *data)
  788. {
  789. int ret;
  790. u16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
  791. if (!status)
  792. return -ENOMEM;
  793. ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  794. USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
  795. sizeof(*status), USB_CTRL_GET_TIMEOUT);
  796. *(u16 *)data = *status;
  797. kfree(status);
  798. return ret;
  799. }
  800. /**
  801. * usb_clear_halt - tells device to clear endpoint halt/stall condition
  802. * @dev: device whose endpoint is halted
  803. * @pipe: endpoint "pipe" being cleared
  804. * Context: !in_interrupt ()
  805. *
  806. * This is used to clear halt conditions for bulk and interrupt endpoints,
  807. * as reported by URB completion status. Endpoints that are halted are
  808. * sometimes referred to as being "stalled". Such endpoints are unable
  809. * to transmit or receive data until the halt status is cleared. Any URBs
  810. * queued for such an endpoint should normally be unlinked by the driver
  811. * before clearing the halt condition, as described in sections 5.7.5
  812. * and 5.8.5 of the USB 2.0 spec.
  813. *
  814. * Note that control and isochronous endpoints don't halt, although control
  815. * endpoints report "protocol stall" (for unsupported requests) using the
  816. * same status code used to report a true stall.
  817. *
  818. * This call is synchronous, and may not be used in an interrupt context.
  819. *
  820. * Returns zero on success, or else the status code returned by the
  821. * underlying usb_control_msg() call.
  822. */
  823. int usb_clear_halt(struct usb_device *dev, int pipe)
  824. {
  825. int result;
  826. int endp = usb_pipeendpoint(pipe);
  827. if (usb_pipein (pipe))
  828. endp |= USB_DIR_IN;
  829. /* we don't care if it wasn't halted first. in fact some devices
  830. * (like some ibmcam model 1 units) seem to expect hosts to make
  831. * this request for iso endpoints, which can't halt!
  832. */
  833. result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  834. USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
  835. USB_ENDPOINT_HALT, endp, NULL, 0,
  836. USB_CTRL_SET_TIMEOUT);
  837. /* don't un-halt or force to DATA0 except on success */
  838. if (result < 0)
  839. return result;
  840. /* NOTE: seems like Microsoft and Apple don't bother verifying
  841. * the clear "took", so some devices could lock up if you check...
  842. * such as the Hagiwara FlashGate DUAL. So we won't bother.
  843. *
  844. * NOTE: make sure the logic here doesn't diverge much from
  845. * the copy in usb-storage, for as long as we need two copies.
  846. */
  847. /* toggle was reset by the clear */
  848. usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
  849. return 0;
  850. }
  851. /**
  852. * usb_disable_endpoint -- Disable an endpoint by address
  853. * @dev: the device whose endpoint is being disabled
  854. * @epaddr: the endpoint's address. Endpoint number for output,
  855. * endpoint number + USB_DIR_IN for input
  856. *
  857. * Deallocates hcd/hardware state for this endpoint ... and nukes all
  858. * pending urbs.
  859. *
  860. * If the HCD hasn't registered a disable() function, this sets the
  861. * endpoint's maxpacket size to 0 to prevent further submissions.
  862. */
  863. void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr)
  864. {
  865. unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
  866. struct usb_host_endpoint *ep;
  867. if (!dev)
  868. return;
  869. if (usb_endpoint_out(epaddr)) {
  870. ep = dev->ep_out[epnum];
  871. dev->ep_out[epnum] = NULL;
  872. } else {
  873. ep = dev->ep_in[epnum];
  874. dev->ep_in[epnum] = NULL;
  875. }
  876. if (ep && dev->bus)
  877. usb_hcd_endpoint_disable(dev, ep);
  878. }
  879. /**
  880. * usb_disable_interface -- Disable all endpoints for an interface
  881. * @dev: the device whose interface is being disabled
  882. * @intf: pointer to the interface descriptor
  883. *
  884. * Disables all the endpoints for the interface's current altsetting.
  885. */
  886. void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf)
  887. {
  888. struct usb_host_interface *alt = intf->cur_altsetting;
  889. int i;
  890. for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
  891. usb_disable_endpoint(dev,
  892. alt->endpoint[i].desc.bEndpointAddress);
  893. }
  894. }
  895. /*
  896. * usb_disable_device - Disable all the endpoints for a USB device
  897. * @dev: the device whose endpoints are being disabled
  898. * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
  899. *
  900. * Disables all the device's endpoints, potentially including endpoint 0.
  901. * Deallocates hcd/hardware state for the endpoints (nuking all or most
  902. * pending urbs) and usbcore state for the interfaces, so that usbcore
  903. * must usb_set_configuration() before any interfaces could be used.
  904. */
  905. void usb_disable_device(struct usb_device *dev, int skip_ep0)
  906. {
  907. int i;
  908. dev_dbg(&dev->dev, "%s nuking %s URBs\n", __FUNCTION__,
  909. skip_ep0 ? "non-ep0" : "all");
  910. for (i = skip_ep0; i < 16; ++i) {
  911. usb_disable_endpoint(dev, i);
  912. usb_disable_endpoint(dev, i + USB_DIR_IN);
  913. }
  914. dev->toggle[0] = dev->toggle[1] = 0;
  915. /* getting rid of interfaces will disconnect
  916. * any drivers bound to them (a key side effect)
  917. */
  918. if (dev->actconfig) {
  919. for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
  920. struct usb_interface *interface;
  921. /* remove this interface if it has been registered */
  922. interface = dev->actconfig->interface[i];
  923. if (!device_is_registered(&interface->dev))
  924. continue;
  925. dev_dbg (&dev->dev, "unregistering interface %s\n",
  926. interface->dev.bus_id);
  927. usb_remove_sysfs_intf_files(interface);
  928. device_del (&interface->dev);
  929. }
  930. /* Now that the interfaces are unbound, nobody should
  931. * try to access them.
  932. */
  933. for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
  934. put_device (&dev->actconfig->interface[i]->dev);
  935. dev->actconfig->interface[i] = NULL;
  936. }
  937. dev->actconfig = NULL;
  938. if (dev->state == USB_STATE_CONFIGURED)
  939. usb_set_device_state(dev, USB_STATE_ADDRESS);
  940. }
  941. }
  942. /*
  943. * usb_enable_endpoint - Enable an endpoint for USB communications
  944. * @dev: the device whose interface is being enabled
  945. * @ep: the endpoint
  946. *
  947. * Resets the endpoint toggle, and sets dev->ep_{in,out} pointers.
  948. * For control endpoints, both the input and output sides are handled.
  949. */
  950. static void
  951. usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep)
  952. {
  953. unsigned int epaddr = ep->desc.bEndpointAddress;
  954. unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
  955. int is_control;
  956. is_control = ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
  957. == USB_ENDPOINT_XFER_CONTROL);
  958. if (usb_endpoint_out(epaddr) || is_control) {
  959. usb_settoggle(dev, epnum, 1, 0);
  960. dev->ep_out[epnum] = ep;
  961. }
  962. if (!usb_endpoint_out(epaddr) || is_control) {
  963. usb_settoggle(dev, epnum, 0, 0);
  964. dev->ep_in[epnum] = ep;
  965. }
  966. }
  967. /*
  968. * usb_enable_interface - Enable all the endpoints for an interface
  969. * @dev: the device whose interface is being enabled
  970. * @intf: pointer to the interface descriptor
  971. *
  972. * Enables all the endpoints for the interface's current altsetting.
  973. */
  974. static void usb_enable_interface(struct usb_device *dev,
  975. struct usb_interface *intf)
  976. {
  977. struct usb_host_interface *alt = intf->cur_altsetting;
  978. int i;
  979. for (i = 0; i < alt->desc.bNumEndpoints; ++i)
  980. usb_enable_endpoint(dev, &alt->endpoint[i]);
  981. }
  982. /**
  983. * usb_set_interface - Makes a particular alternate setting be current
  984. * @dev: the device whose interface is being updated
  985. * @interface: the interface being updated
  986. * @alternate: the setting being chosen.
  987. * Context: !in_interrupt ()
  988. *
  989. * This is used to enable data transfers on interfaces that may not
  990. * be enabled by default. Not all devices support such configurability.
  991. * Only the driver bound to an interface may change its setting.
  992. *
  993. * Within any given configuration, each interface may have several
  994. * alternative settings. These are often used to control levels of
  995. * bandwidth consumption. For example, the default setting for a high
  996. * speed interrupt endpoint may not send more than 64 bytes per microframe,
  997. * while interrupt transfers of up to 3KBytes per microframe are legal.
  998. * Also, isochronous endpoints may never be part of an
  999. * interface's default setting. To access such bandwidth, alternate
  1000. * interface settings must be made current.
  1001. *
  1002. * Note that in the Linux USB subsystem, bandwidth associated with
  1003. * an endpoint in a given alternate setting is not reserved until an URB
  1004. * is submitted that needs that bandwidth. Some other operating systems
  1005. * allocate bandwidth early, when a configuration is chosen.
  1006. *
  1007. * This call is synchronous, and may not be used in an interrupt context.
  1008. * Also, drivers must not change altsettings while urbs are scheduled for
  1009. * endpoints in that interface; all such urbs must first be completed
  1010. * (perhaps forced by unlinking).
  1011. *
  1012. * Returns zero on success, or else the status code returned by the
  1013. * underlying usb_control_msg() call.
  1014. */
  1015. int usb_set_interface(struct usb_device *dev, int interface, int alternate)
  1016. {
  1017. struct usb_interface *iface;
  1018. struct usb_host_interface *alt;
  1019. int ret;
  1020. int manual = 0;
  1021. if (dev->state == USB_STATE_SUSPENDED)
  1022. return -EHOSTUNREACH;
  1023. iface = usb_ifnum_to_if(dev, interface);
  1024. if (!iface) {
  1025. dev_dbg(&dev->dev, "selecting invalid interface %d\n",
  1026. interface);
  1027. return -EINVAL;
  1028. }
  1029. alt = usb_altnum_to_altsetting(iface, alternate);
  1030. if (!alt) {
  1031. warn("selecting invalid altsetting %d", alternate);
  1032. return -EINVAL;
  1033. }
  1034. ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  1035. USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
  1036. alternate, interface, NULL, 0, 5000);
  1037. /* 9.4.10 says devices don't need this and are free to STALL the
  1038. * request if the interface only has one alternate setting.
  1039. */
  1040. if (ret == -EPIPE && iface->num_altsetting == 1) {
  1041. dev_dbg(&dev->dev,
  1042. "manual set_interface for iface %d, alt %d\n",
  1043. interface, alternate);
  1044. manual = 1;
  1045. } else if (ret < 0)
  1046. return ret;
  1047. /* FIXME drivers shouldn't need to replicate/bugfix the logic here
  1048. * when they implement async or easily-killable versions of this or
  1049. * other "should-be-internal" functions (like clear_halt).
  1050. * should hcd+usbcore postprocess control requests?
  1051. */
  1052. /* prevent submissions using previous endpoint settings */
  1053. if (device_is_registered(&iface->dev))
  1054. usb_remove_sysfs_intf_files(iface);
  1055. usb_disable_interface(dev, iface);
  1056. iface->cur_altsetting = alt;
  1057. /* If the interface only has one altsetting and the device didn't
  1058. * accept the request, we attempt to carry out the equivalent action
  1059. * by manually clearing the HALT feature for each endpoint in the
  1060. * new altsetting.
  1061. */
  1062. if (manual) {
  1063. int i;
  1064. for (i = 0; i < alt->desc.bNumEndpoints; i++) {
  1065. unsigned int epaddr =
  1066. alt->endpoint[i].desc.bEndpointAddress;
  1067. unsigned int pipe =
  1068. __create_pipe(dev, USB_ENDPOINT_NUMBER_MASK & epaddr)
  1069. | (usb_endpoint_out(epaddr) ? USB_DIR_OUT : USB_DIR_IN);
  1070. usb_clear_halt(dev, pipe);
  1071. }
  1072. }
  1073. /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
  1074. *
  1075. * Note:
  1076. * Despite EP0 is always present in all interfaces/AS, the list of
  1077. * endpoints from the descriptor does not contain EP0. Due to its
  1078. * omnipresence one might expect EP0 being considered "affected" by
  1079. * any SetInterface request and hence assume toggles need to be reset.
  1080. * However, EP0 toggles are re-synced for every individual transfer
  1081. * during the SETUP stage - hence EP0 toggles are "don't care" here.
  1082. * (Likewise, EP0 never "halts" on well designed devices.)
  1083. */
  1084. usb_enable_interface(dev, iface);
  1085. if (device_is_registered(&iface->dev))
  1086. usb_create_sysfs_intf_files(iface);
  1087. return 0;
  1088. }
  1089. /**
  1090. * usb_reset_configuration - lightweight device reset
  1091. * @dev: the device whose configuration is being reset
  1092. *
  1093. * This issues a standard SET_CONFIGURATION request to the device using
  1094. * the current configuration. The effect is to reset most USB-related
  1095. * state in the device, including interface altsettings (reset to zero),
  1096. * endpoint halts (cleared), and data toggle (only for bulk and interrupt
  1097. * endpoints). Other usbcore state is unchanged, including bindings of
  1098. * usb device drivers to interfaces.
  1099. *
  1100. * Because this affects multiple interfaces, avoid using this with composite
  1101. * (multi-interface) devices. Instead, the driver for each interface may
  1102. * use usb_set_interface() on the interfaces it claims. Be careful though;
  1103. * some devices don't support the SET_INTERFACE request, and others won't
  1104. * reset all the interface state (notably data toggles). Resetting the whole
  1105. * configuration would affect other drivers' interfaces.
  1106. *
  1107. * The caller must own the device lock.
  1108. *
  1109. * Returns zero on success, else a negative error code.
  1110. */
  1111. int usb_reset_configuration(struct usb_device *dev)
  1112. {
  1113. int i, retval;
  1114. struct usb_host_config *config;
  1115. if (dev->state == USB_STATE_SUSPENDED)
  1116. return -EHOSTUNREACH;
  1117. /* caller must have locked the device and must own
  1118. * the usb bus readlock (so driver bindings are stable);
  1119. * calls during probe() are fine
  1120. */
  1121. for (i = 1; i < 16; ++i) {
  1122. usb_disable_endpoint(dev, i);
  1123. usb_disable_endpoint(dev, i + USB_DIR_IN);
  1124. }
  1125. config = dev->actconfig;
  1126. retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  1127. USB_REQ_SET_CONFIGURATION, 0,
  1128. config->desc.bConfigurationValue, 0,
  1129. NULL, 0, USB_CTRL_SET_TIMEOUT);
  1130. if (retval < 0)
  1131. return retval;
  1132. dev->toggle[0] = dev->toggle[1] = 0;
  1133. /* re-init hc/hcd interface/endpoint state */
  1134. for (i = 0; i < config->desc.bNumInterfaces; i++) {
  1135. struct usb_interface *intf = config->interface[i];
  1136. struct usb_host_interface *alt;
  1137. if (device_is_registered(&intf->dev))
  1138. usb_remove_sysfs_intf_files(intf);
  1139. alt = usb_altnum_to_altsetting(intf, 0);
  1140. /* No altsetting 0? We'll assume the first altsetting.
  1141. * We could use a GetInterface call, but if a device is
  1142. * so non-compliant that it doesn't have altsetting 0
  1143. * then I wouldn't trust its reply anyway.
  1144. */
  1145. if (!alt)
  1146. alt = &intf->altsetting[0];
  1147. intf->cur_altsetting = alt;
  1148. usb_enable_interface(dev, intf);
  1149. if (device_is_registered(&intf->dev))
  1150. usb_create_sysfs_intf_files(intf);
  1151. }
  1152. return 0;
  1153. }
  1154. static void release_interface(struct device *dev)
  1155. {
  1156. struct usb_interface *intf = to_usb_interface(dev);
  1157. struct usb_interface_cache *intfc =
  1158. altsetting_to_usb_interface_cache(intf->altsetting);
  1159. kref_put(&intfc->ref, usb_release_interface_cache);
  1160. kfree(intf);
  1161. }
  1162. /*
  1163. * usb_set_configuration - Makes a particular device setting be current
  1164. * @dev: the device whose configuration is being updated
  1165. * @configuration: the configuration being chosen.
  1166. * Context: !in_interrupt(), caller owns the device lock
  1167. *
  1168. * This is used to enable non-default device modes. Not all devices
  1169. * use this kind of configurability; many devices only have one
  1170. * configuration.
  1171. *
  1172. * USB device configurations may affect Linux interoperability,
  1173. * power consumption and the functionality available. For example,
  1174. * the default configuration is limited to using 100mA of bus power,
  1175. * so that when certain device functionality requires more power,
  1176. * and the device is bus powered, that functionality should be in some
  1177. * non-default device configuration. Other device modes may also be
  1178. * reflected as configuration options, such as whether two ISDN
  1179. * channels are available independently; and choosing between open
  1180. * standard device protocols (like CDC) or proprietary ones.
  1181. *
  1182. * Note that USB has an additional level of device configurability,
  1183. * associated with interfaces. That configurability is accessed using
  1184. * usb_set_interface().
  1185. *
  1186. * This call is synchronous. The calling context must be able to sleep,
  1187. * must own the device lock, and must not hold the driver model's USB
  1188. * bus rwsem; usb device driver probe() methods cannot use this routine.
  1189. *
  1190. * Returns zero on success, or else the status code returned by the
  1191. * underlying call that failed. On successful completion, each interface
  1192. * in the original device configuration has been destroyed, and each one
  1193. * in the new configuration has been probed by all relevant usb device
  1194. * drivers currently known to the kernel.
  1195. */
  1196. int usb_set_configuration(struct usb_device *dev, int configuration)
  1197. {
  1198. int i, ret;
  1199. struct usb_host_config *cp = NULL;
  1200. struct usb_interface **new_interfaces = NULL;
  1201. int n, nintf;
  1202. for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
  1203. if (dev->config[i].desc.bConfigurationValue == configuration) {
  1204. cp = &dev->config[i];
  1205. break;
  1206. }
  1207. }
  1208. if ((!cp && configuration != 0))
  1209. return -EINVAL;
  1210. /* The USB spec says configuration 0 means unconfigured.
  1211. * But if a device includes a configuration numbered 0,
  1212. * we will accept it as a correctly configured state.
  1213. */
  1214. if (cp && configuration == 0)
  1215. dev_warn(&dev->dev, "config 0 descriptor??\n");
  1216. /* Allocate memory for new interfaces before doing anything else,
  1217. * so that if we run out then nothing will have changed. */
  1218. n = nintf = 0;
  1219. if (cp) {
  1220. nintf = cp->desc.bNumInterfaces;
  1221. new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
  1222. GFP_KERNEL);
  1223. if (!new_interfaces) {
  1224. dev_err(&dev->dev, "Out of memory");
  1225. return -ENOMEM;
  1226. }
  1227. for (; n < nintf; ++n) {
  1228. new_interfaces[n] = kzalloc(
  1229. sizeof(struct usb_interface),
  1230. GFP_KERNEL);
  1231. if (!new_interfaces[n]) {
  1232. dev_err(&dev->dev, "Out of memory");
  1233. ret = -ENOMEM;
  1234. free_interfaces:
  1235. while (--n >= 0)
  1236. kfree(new_interfaces[n]);
  1237. kfree(new_interfaces);
  1238. return ret;
  1239. }
  1240. }
  1241. i = dev->bus_mA - cp->desc.bMaxPower * 2;
  1242. if (i < 0)
  1243. dev_warn(&dev->dev, "new config #%d exceeds power "
  1244. "limit by %dmA\n",
  1245. configuration, -i);
  1246. }
  1247. /* Wake up the device so we can send it the Set-Config request */
  1248. ret = usb_autoresume_device(dev, 1);
  1249. if (ret)
  1250. goto free_interfaces;
  1251. /* if it's already configured, clear out old state first.
  1252. * getting rid of old interfaces means unbinding their drivers.
  1253. */
  1254. if (dev->state != USB_STATE_ADDRESS)
  1255. usb_disable_device (dev, 1); // Skip ep0
  1256. if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  1257. USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
  1258. NULL, 0, USB_CTRL_SET_TIMEOUT)) < 0) {
  1259. /* All the old state is gone, so what else can we do?
  1260. * The device is probably useless now anyway.
  1261. */
  1262. cp = NULL;
  1263. }
  1264. dev->actconfig = cp;
  1265. if (!cp) {
  1266. usb_set_device_state(dev, USB_STATE_ADDRESS);
  1267. usb_autosuspend_device(dev, 1);
  1268. goto free_interfaces;
  1269. }
  1270. usb_set_device_state(dev, USB_STATE_CONFIGURED);
  1271. /* Initialize the new interface structures and the
  1272. * hc/hcd/usbcore interface/endpoint state.
  1273. */
  1274. for (i = 0; i < nintf; ++i) {
  1275. struct usb_interface_cache *intfc;
  1276. struct usb_interface *intf;
  1277. struct usb_host_interface *alt;
  1278. cp->interface[i] = intf = new_interfaces[i];
  1279. intfc = cp->intf_cache[i];
  1280. intf->altsetting = intfc->altsetting;
  1281. intf->num_altsetting = intfc->num_altsetting;
  1282. kref_get(&intfc->ref);
  1283. alt = usb_altnum_to_altsetting(intf, 0);
  1284. /* No altsetting 0? We'll assume the first altsetting.
  1285. * We could use a GetInterface call, but if a device is
  1286. * so non-compliant that it doesn't have altsetting 0
  1287. * then I wouldn't trust its reply anyway.
  1288. */
  1289. if (!alt)
  1290. alt = &intf->altsetting[0];
  1291. intf->cur_altsetting = alt;
  1292. usb_enable_interface(dev, intf);
  1293. intf->dev.parent = &dev->dev;
  1294. intf->dev.driver = NULL;
  1295. intf->dev.bus = &usb_bus_type;
  1296. intf->dev.dma_mask = dev->dev.dma_mask;
  1297. intf->dev.release = release_interface;
  1298. device_initialize (&intf->dev);
  1299. mark_quiesced(intf);
  1300. sprintf (&intf->dev.bus_id[0], "%d-%s:%d.%d",
  1301. dev->bus->busnum, dev->devpath,
  1302. configuration, alt->desc.bInterfaceNumber);
  1303. }
  1304. kfree(new_interfaces);
  1305. if (cp->string == NULL)
  1306. cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
  1307. /* Now that all the interfaces are set up, register them
  1308. * to trigger binding of drivers to interfaces. probe()
  1309. * routines may install different altsettings and may
  1310. * claim() any interfaces not yet bound. Many class drivers
  1311. * need that: CDC, audio, video, etc.
  1312. */
  1313. for (i = 0; i < nintf; ++i) {
  1314. struct usb_interface *intf = cp->interface[i];
  1315. dev_dbg (&dev->dev,
  1316. "adding %s (config #%d, interface %d)\n",
  1317. intf->dev.bus_id, configuration,
  1318. intf->cur_altsetting->desc.bInterfaceNumber);
  1319. ret = device_add (&intf->dev);
  1320. if (ret != 0) {
  1321. dev_err(&dev->dev, "device_add(%s) --> %d\n",
  1322. intf->dev.bus_id, ret);
  1323. continue;
  1324. }
  1325. usb_create_sysfs_intf_files (intf);
  1326. }
  1327. usb_autosuspend_device(dev, 1);
  1328. return 0;
  1329. }
  1330. struct set_config_request {
  1331. struct usb_device *udev;
  1332. int config;
  1333. struct work_struct work;
  1334. };
  1335. /* Worker routine for usb_driver_set_configuration() */
  1336. static void driver_set_config_work(void *_req)
  1337. {
  1338. struct set_config_request *req = _req;
  1339. usb_lock_device(req->udev);
  1340. usb_set_configuration(req->udev, req->config);
  1341. usb_unlock_device(req->udev);
  1342. usb_put_dev(req->udev);
  1343. kfree(req);
  1344. }
  1345. /**
  1346. * usb_driver_set_configuration - Provide a way for drivers to change device configurations
  1347. * @udev: the device whose configuration is being updated
  1348. * @config: the configuration being chosen.
  1349. * Context: In process context, must be able to sleep
  1350. *
  1351. * Device interface drivers are not allowed to change device configurations.
  1352. * This is because changing configurations will destroy the interface the
  1353. * driver is bound to and create new ones; it would be like a floppy-disk
  1354. * driver telling the computer to replace the floppy-disk drive with a
  1355. * tape drive!
  1356. *
  1357. * Still, in certain specialized circumstances the need may arise. This
  1358. * routine gets around the normal restrictions by using a work thread to
  1359. * submit the change-config request.
  1360. *
  1361. * Returns 0 if the request was succesfully queued, error code otherwise.
  1362. * The caller has no way to know whether the queued request will eventually
  1363. * succeed.
  1364. */
  1365. int usb_driver_set_configuration(struct usb_device *udev, int config)
  1366. {
  1367. struct set_config_request *req;
  1368. req = kmalloc(sizeof(*req), GFP_KERNEL);
  1369. if (!req)
  1370. return -ENOMEM;
  1371. req->udev = udev;
  1372. req->config = config;
  1373. INIT_WORK(&req->work, driver_set_config_work, req);
  1374. usb_get_dev(udev);
  1375. if (!schedule_work(&req->work)) {
  1376. usb_put_dev(udev);
  1377. kfree(req);
  1378. return -EINVAL;
  1379. }
  1380. return 0;
  1381. }
  1382. EXPORT_SYMBOL_GPL(usb_driver_set_configuration);
  1383. // synchronous request completion model
  1384. EXPORT_SYMBOL(usb_control_msg);
  1385. EXPORT_SYMBOL(usb_bulk_msg);
  1386. EXPORT_SYMBOL(usb_sg_init);
  1387. EXPORT_SYMBOL(usb_sg_cancel);
  1388. EXPORT_SYMBOL(usb_sg_wait);
  1389. // synchronous control message convenience routines
  1390. EXPORT_SYMBOL(usb_get_descriptor);
  1391. EXPORT_SYMBOL(usb_get_status);
  1392. EXPORT_SYMBOL(usb_string);
  1393. // synchronous calls that also maintain usbcore state
  1394. EXPORT_SYMBOL(usb_clear_halt);
  1395. EXPORT_SYMBOL(usb_reset_configuration);
  1396. EXPORT_SYMBOL(usb_set_interface);