message.c 53 KB

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