message.c 47 KB

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