message.c 52 KB

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