message.c 51 KB

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