message.c 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593
  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. if (dma) {
  364. /* hc may use _only_ transfer_dma */
  365. io->urbs [i]->transfer_dma = sg_dma_address (sg + i);
  366. len = sg_dma_len (sg + i);
  367. } else {
  368. /* hc may use _only_ transfer_buffer */
  369. io->urbs [i]->transfer_buffer =
  370. page_address (sg [i].page) + sg [i].offset;
  371. len = sg [i].length;
  372. }
  373. if (length) {
  374. len = min_t (unsigned, len, length);
  375. length -= len;
  376. if (length == 0)
  377. io->entries = i + 1;
  378. }
  379. io->urbs [i]->transfer_buffer_length = len;
  380. }
  381. io->urbs [--i]->transfer_flags &= ~URB_NO_INTERRUPT;
  382. /* transaction state */
  383. io->status = 0;
  384. io->bytes = 0;
  385. init_completion (&io->complete);
  386. return 0;
  387. nomem:
  388. sg_clean (io);
  389. return -ENOMEM;
  390. }
  391. /**
  392. * usb_sg_wait - synchronously execute scatter/gather request
  393. * @io: request block handle, as initialized with usb_sg_init().
  394. * some fields become accessible when this call returns.
  395. * Context: !in_interrupt ()
  396. *
  397. * This function blocks until the specified I/O operation completes. It
  398. * leverages the grouping of the related I/O requests to get good transfer
  399. * rates, by queueing the requests. At higher speeds, such queuing can
  400. * significantly improve USB throughput.
  401. *
  402. * There are three kinds of completion for this function.
  403. * (1) success, where io->status is zero. The number of io->bytes
  404. * transferred is as requested.
  405. * (2) error, where io->status is a negative errno value. The number
  406. * of io->bytes transferred before the error is usually less
  407. * than requested, and can be nonzero.
  408. * (3) cancellation, a type of error with status -ECONNRESET that
  409. * is initiated by usb_sg_cancel().
  410. *
  411. * When this function returns, all memory allocated through usb_sg_init() or
  412. * this call will have been freed. The request block parameter may still be
  413. * passed to usb_sg_cancel(), or it may be freed. It could also be
  414. * reinitialized and then reused.
  415. *
  416. * Data Transfer Rates:
  417. *
  418. * Bulk transfers are valid for full or high speed endpoints.
  419. * The best full speed data rate is 19 packets of 64 bytes each
  420. * per frame, or 1216 bytes per millisecond.
  421. * The best high speed data rate is 13 packets of 512 bytes each
  422. * per microframe, or 52 KBytes per millisecond.
  423. *
  424. * The reason to use interrupt transfers through this API would most likely
  425. * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
  426. * could be transferred. That capability is less useful for low or full
  427. * speed interrupt endpoints, which allow at most one packet per millisecond,
  428. * of at most 8 or 64 bytes (respectively).
  429. */
  430. void usb_sg_wait (struct usb_sg_request *io)
  431. {
  432. int i, entries = io->entries;
  433. /* queue the urbs. */
  434. spin_lock_irq (&io->lock);
  435. for (i = 0; i < entries && !io->status; i++) {
  436. int retval;
  437. io->urbs [i]->dev = io->dev;
  438. retval = usb_submit_urb (io->urbs [i], GFP_ATOMIC);
  439. /* after we submit, let completions or cancelations fire;
  440. * we handshake using io->status.
  441. */
  442. spin_unlock_irq (&io->lock);
  443. switch (retval) {
  444. /* maybe we retrying will recover */
  445. case -ENXIO: // hc didn't queue this one
  446. case -EAGAIN:
  447. case -ENOMEM:
  448. io->urbs[i]->dev = NULL;
  449. retval = 0;
  450. i--;
  451. yield ();
  452. break;
  453. /* no error? continue immediately.
  454. *
  455. * NOTE: to work better with UHCI (4K I/O buffer may
  456. * need 3K of TDs) it may be good to limit how many
  457. * URBs are queued at once; N milliseconds?
  458. */
  459. case 0:
  460. cpu_relax ();
  461. break;
  462. /* fail any uncompleted urbs */
  463. default:
  464. io->urbs [i]->dev = NULL;
  465. io->urbs [i]->status = retval;
  466. dev_dbg (&io->dev->dev, "%s, submit --> %d\n",
  467. __FUNCTION__, retval);
  468. usb_sg_cancel (io);
  469. }
  470. spin_lock_irq (&io->lock);
  471. if (retval && (io->status == 0 || io->status == -ECONNRESET))
  472. io->status = retval;
  473. }
  474. io->count -= entries - i;
  475. if (io->count == 0)
  476. complete (&io->complete);
  477. spin_unlock_irq (&io->lock);
  478. /* OK, yes, this could be packaged as non-blocking.
  479. * So could the submit loop above ... but it's easier to
  480. * solve neither problem than to solve both!
  481. */
  482. wait_for_completion (&io->complete);
  483. sg_clean (io);
  484. }
  485. /**
  486. * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
  487. * @io: request block, initialized with usb_sg_init()
  488. *
  489. * This stops a request after it has been started by usb_sg_wait().
  490. * It can also prevents one initialized by usb_sg_init() from starting,
  491. * so that call just frees resources allocated to the request.
  492. */
  493. void usb_sg_cancel (struct usb_sg_request *io)
  494. {
  495. unsigned long flags;
  496. spin_lock_irqsave (&io->lock, flags);
  497. /* shut everything down, if it didn't already */
  498. if (!io->status) {
  499. int i;
  500. io->status = -ECONNRESET;
  501. spin_unlock (&io->lock);
  502. for (i = 0; i < io->entries; i++) {
  503. int retval;
  504. if (!io->urbs [i]->dev)
  505. continue;
  506. retval = usb_unlink_urb (io->urbs [i]);
  507. if (retval != -EINPROGRESS && retval != -EBUSY)
  508. dev_warn (&io->dev->dev, "%s, unlink --> %d\n",
  509. __FUNCTION__, retval);
  510. }
  511. spin_lock (&io->lock);
  512. }
  513. spin_unlock_irqrestore (&io->lock, flags);
  514. }
  515. /*-------------------------------------------------------------------*/
  516. /**
  517. * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
  518. * @dev: the device whose descriptor is being retrieved
  519. * @type: the descriptor type (USB_DT_*)
  520. * @index: the number of the descriptor
  521. * @buf: where to put the descriptor
  522. * @size: how big is "buf"?
  523. * Context: !in_interrupt ()
  524. *
  525. * Gets a USB descriptor. Convenience functions exist to simplify
  526. * getting some types of descriptors. Use
  527. * usb_get_string() or usb_string() for USB_DT_STRING.
  528. * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
  529. * are part of the device structure.
  530. * In addition to a number of USB-standard descriptors, some
  531. * devices also use class-specific or vendor-specific descriptors.
  532. *
  533. * This call is synchronous, and may not be used in an interrupt context.
  534. *
  535. * Returns the number of bytes received on success, or else the status code
  536. * returned by the underlying usb_control_msg() call.
  537. */
  538. int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
  539. {
  540. int i;
  541. int result;
  542. memset(buf,0,size); // Make sure we parse really received data
  543. for (i = 0; i < 3; ++i) {
  544. /* retry on length 0 or stall; some devices are flakey */
  545. result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  546. USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
  547. (type << 8) + index, 0, buf, size,
  548. USB_CTRL_GET_TIMEOUT);
  549. if (result == 0 || result == -EPIPE)
  550. continue;
  551. if (result > 1 && ((u8 *)buf)[1] != type) {
  552. result = -EPROTO;
  553. continue;
  554. }
  555. break;
  556. }
  557. return result;
  558. }
  559. /**
  560. * usb_get_string - gets a string descriptor
  561. * @dev: the device whose string descriptor is being retrieved
  562. * @langid: code for language chosen (from string descriptor zero)
  563. * @index: the number of the descriptor
  564. * @buf: where to put the string
  565. * @size: how big is "buf"?
  566. * Context: !in_interrupt ()
  567. *
  568. * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
  569. * in little-endian byte order).
  570. * The usb_string() function will often be a convenient way to turn
  571. * these strings into kernel-printable form.
  572. *
  573. * Strings may be referenced in device, configuration, interface, or other
  574. * descriptors, and could also be used in vendor-specific ways.
  575. *
  576. * This call is synchronous, and may not be used in an interrupt context.
  577. *
  578. * Returns the number of bytes received on success, or else the status code
  579. * returned by the underlying usb_control_msg() call.
  580. */
  581. static int usb_get_string(struct usb_device *dev, unsigned short langid,
  582. unsigned char index, void *buf, int size)
  583. {
  584. int i;
  585. int result;
  586. for (i = 0; i < 3; ++i) {
  587. /* retry on length 0 or stall; some devices are flakey */
  588. result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  589. USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
  590. (USB_DT_STRING << 8) + index, langid, buf, size,
  591. USB_CTRL_GET_TIMEOUT);
  592. if (!(result == 0 || result == -EPIPE))
  593. break;
  594. }
  595. return result;
  596. }
  597. static void usb_try_string_workarounds(unsigned char *buf, int *length)
  598. {
  599. int newlength, oldlength = *length;
  600. for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
  601. if (!isprint(buf[newlength]) || buf[newlength + 1])
  602. break;
  603. if (newlength > 2) {
  604. buf[0] = newlength;
  605. *length = newlength;
  606. }
  607. }
  608. static int usb_string_sub(struct usb_device *dev, unsigned int langid,
  609. unsigned int index, unsigned char *buf)
  610. {
  611. int rc;
  612. /* Try to read the string descriptor by asking for the maximum
  613. * possible number of bytes */
  614. if (dev->quirks & USB_QUIRK_STRING_FETCH_255)
  615. rc = -EIO;
  616. else
  617. rc = usb_get_string(dev, langid, index, buf, 255);
  618. /* If that failed try to read the descriptor length, then
  619. * ask for just that many bytes */
  620. if (rc < 2) {
  621. rc = usb_get_string(dev, langid, index, buf, 2);
  622. if (rc == 2)
  623. rc = usb_get_string(dev, langid, index, buf, buf[0]);
  624. }
  625. if (rc >= 2) {
  626. if (!buf[0] && !buf[1])
  627. usb_try_string_workarounds(buf, &rc);
  628. /* There might be extra junk at the end of the descriptor */
  629. if (buf[0] < rc)
  630. rc = buf[0];
  631. rc = rc - (rc & 1); /* force a multiple of two */
  632. }
  633. if (rc < 2)
  634. rc = (rc < 0 ? rc : -EINVAL);
  635. return rc;
  636. }
  637. /**
  638. * usb_string - returns ISO 8859-1 version of a string descriptor
  639. * @dev: the device whose string descriptor is being retrieved
  640. * @index: the number of the descriptor
  641. * @buf: where to put the string
  642. * @size: how big is "buf"?
  643. * Context: !in_interrupt ()
  644. *
  645. * This converts the UTF-16LE encoded strings returned by devices, from
  646. * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
  647. * that are more usable in most kernel contexts. Note that all characters
  648. * in the chosen descriptor that can't be encoded using ISO-8859-1
  649. * are converted to the question mark ("?") character, and this function
  650. * chooses strings in the first language supported by the device.
  651. *
  652. * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
  653. * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
  654. * and is appropriate for use many uses of English and several other
  655. * Western European languages. (But it doesn't include the "Euro" symbol.)
  656. *
  657. * This call is synchronous, and may not be used in an interrupt context.
  658. *
  659. * Returns length of the string (>= 0) or usb_control_msg status (< 0).
  660. */
  661. int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
  662. {
  663. unsigned char *tbuf;
  664. int err;
  665. unsigned int u, idx;
  666. if (dev->state == USB_STATE_SUSPENDED)
  667. return -EHOSTUNREACH;
  668. if (size <= 0 || !buf || !index)
  669. return -EINVAL;
  670. buf[0] = 0;
  671. tbuf = kmalloc(256, GFP_KERNEL);
  672. if (!tbuf)
  673. return -ENOMEM;
  674. /* get langid for strings if it's not yet known */
  675. if (!dev->have_langid) {
  676. err = usb_string_sub(dev, 0, 0, tbuf);
  677. if (err < 0) {
  678. dev_err (&dev->dev,
  679. "string descriptor 0 read error: %d\n",
  680. err);
  681. goto errout;
  682. } else if (err < 4) {
  683. dev_err (&dev->dev, "string descriptor 0 too short\n");
  684. err = -EINVAL;
  685. goto errout;
  686. } else {
  687. dev->have_langid = 1;
  688. dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
  689. /* always use the first langid listed */
  690. dev_dbg (&dev->dev, "default language 0x%04x\n",
  691. dev->string_langid);
  692. }
  693. }
  694. err = usb_string_sub(dev, dev->string_langid, index, tbuf);
  695. if (err < 0)
  696. goto errout;
  697. size--; /* leave room for trailing NULL char in output buffer */
  698. for (idx = 0, u = 2; u < err; u += 2) {
  699. if (idx >= size)
  700. break;
  701. if (tbuf[u+1]) /* high byte */
  702. buf[idx++] = '?'; /* non ISO-8859-1 character */
  703. else
  704. buf[idx++] = tbuf[u];
  705. }
  706. buf[idx] = 0;
  707. err = idx;
  708. if (tbuf[1] != USB_DT_STRING)
  709. dev_dbg(&dev->dev, "wrong descriptor type %02x for string %d (\"%s\")\n", tbuf[1], index, buf);
  710. errout:
  711. kfree(tbuf);
  712. return err;
  713. }
  714. /**
  715. * usb_cache_string - read a string descriptor and cache it for later use
  716. * @udev: the device whose string descriptor is being read
  717. * @index: the descriptor index
  718. *
  719. * Returns a pointer to a kmalloc'ed buffer containing the descriptor string,
  720. * or NULL if the index is 0 or the string could not be read.
  721. */
  722. char *usb_cache_string(struct usb_device *udev, int index)
  723. {
  724. char *buf;
  725. char *smallbuf = NULL;
  726. int len;
  727. if (index > 0 && (buf = kmalloc(256, GFP_KERNEL)) != NULL) {
  728. if ((len = usb_string(udev, index, buf, 256)) > 0) {
  729. if ((smallbuf = kmalloc(++len, GFP_KERNEL)) == NULL)
  730. return buf;
  731. memcpy(smallbuf, buf, len);
  732. }
  733. kfree(buf);
  734. }
  735. return smallbuf;
  736. }
  737. /*
  738. * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
  739. * @dev: the device whose device descriptor is being updated
  740. * @size: how much of the descriptor to read
  741. * Context: !in_interrupt ()
  742. *
  743. * Updates the copy of the device descriptor stored in the device structure,
  744. * which dedicates space for this purpose.
  745. *
  746. * Not exported, only for use by the core. If drivers really want to read
  747. * the device descriptor directly, they can call usb_get_descriptor() with
  748. * type = USB_DT_DEVICE and index = 0.
  749. *
  750. * This call is synchronous, and may not be used in an interrupt context.
  751. *
  752. * Returns the number of bytes received on success, or else the status code
  753. * returned by the underlying usb_control_msg() call.
  754. */
  755. int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
  756. {
  757. struct usb_device_descriptor *desc;
  758. int ret;
  759. if (size > sizeof(*desc))
  760. return -EINVAL;
  761. desc = kmalloc(sizeof(*desc), GFP_NOIO);
  762. if (!desc)
  763. return -ENOMEM;
  764. ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
  765. if (ret >= 0)
  766. memcpy(&dev->descriptor, desc, size);
  767. kfree(desc);
  768. return ret;
  769. }
  770. /**
  771. * usb_get_status - issues a GET_STATUS call
  772. * @dev: the device whose status is being checked
  773. * @type: USB_RECIP_*; for device, interface, or endpoint
  774. * @target: zero (for device), else interface or endpoint number
  775. * @data: pointer to two bytes of bitmap data
  776. * Context: !in_interrupt ()
  777. *
  778. * Returns device, interface, or endpoint status. Normally only of
  779. * interest to see if the device is self powered, or has enabled the
  780. * remote wakeup facility; or whether a bulk or interrupt endpoint
  781. * is halted ("stalled").
  782. *
  783. * Bits in these status bitmaps are set using the SET_FEATURE request,
  784. * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
  785. * function should be used to clear halt ("stall") status.
  786. *
  787. * This call is synchronous, and may not be used in an interrupt context.
  788. *
  789. * Returns the number of bytes received on success, or else the status code
  790. * returned by the underlying usb_control_msg() call.
  791. */
  792. int usb_get_status(struct usb_device *dev, int type, int target, void *data)
  793. {
  794. int ret;
  795. u16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
  796. if (!status)
  797. return -ENOMEM;
  798. ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  799. USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
  800. sizeof(*status), USB_CTRL_GET_TIMEOUT);
  801. *(u16 *)data = *status;
  802. kfree(status);
  803. return ret;
  804. }
  805. /**
  806. * usb_clear_halt - tells device to clear endpoint halt/stall condition
  807. * @dev: device whose endpoint is halted
  808. * @pipe: endpoint "pipe" being cleared
  809. * Context: !in_interrupt ()
  810. *
  811. * This is used to clear halt conditions for bulk and interrupt endpoints,
  812. * as reported by URB completion status. Endpoints that are halted are
  813. * sometimes referred to as being "stalled". Such endpoints are unable
  814. * to transmit or receive data until the halt status is cleared. Any URBs
  815. * queued for such an endpoint should normally be unlinked by the driver
  816. * before clearing the halt condition, as described in sections 5.7.5
  817. * and 5.8.5 of the USB 2.0 spec.
  818. *
  819. * Note that control and isochronous endpoints don't halt, although control
  820. * endpoints report "protocol stall" (for unsupported requests) using the
  821. * same status code used to report a true stall.
  822. *
  823. * This call is synchronous, and may not be used in an interrupt context.
  824. *
  825. * Returns zero on success, or else the status code returned by the
  826. * underlying usb_control_msg() call.
  827. */
  828. int usb_clear_halt(struct usb_device *dev, int pipe)
  829. {
  830. int result;
  831. int endp = usb_pipeendpoint(pipe);
  832. if (usb_pipein (pipe))
  833. endp |= USB_DIR_IN;
  834. /* we don't care if it wasn't halted first. in fact some devices
  835. * (like some ibmcam model 1 units) seem to expect hosts to make
  836. * this request for iso endpoints, which can't halt!
  837. */
  838. result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  839. USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
  840. USB_ENDPOINT_HALT, endp, NULL, 0,
  841. USB_CTRL_SET_TIMEOUT);
  842. /* don't un-halt or force to DATA0 except on success */
  843. if (result < 0)
  844. return result;
  845. /* NOTE: seems like Microsoft and Apple don't bother verifying
  846. * the clear "took", so some devices could lock up if you check...
  847. * such as the Hagiwara FlashGate DUAL. So we won't bother.
  848. *
  849. * NOTE: make sure the logic here doesn't diverge much from
  850. * the copy in usb-storage, for as long as we need two copies.
  851. */
  852. /* toggle was reset by the clear */
  853. usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
  854. return 0;
  855. }
  856. /**
  857. * usb_disable_endpoint -- Disable an endpoint by address
  858. * @dev: the device whose endpoint is being disabled
  859. * @epaddr: the endpoint's address. Endpoint number for output,
  860. * endpoint number + USB_DIR_IN for input
  861. *
  862. * Deallocates hcd/hardware state for this endpoint ... and nukes all
  863. * pending urbs.
  864. *
  865. * If the HCD hasn't registered a disable() function, this sets the
  866. * endpoint's maxpacket size to 0 to prevent further submissions.
  867. */
  868. void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr)
  869. {
  870. unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
  871. struct usb_host_endpoint *ep;
  872. if (!dev)
  873. return;
  874. if (usb_endpoint_out(epaddr)) {
  875. ep = dev->ep_out[epnum];
  876. dev->ep_out[epnum] = NULL;
  877. } else {
  878. ep = dev->ep_in[epnum];
  879. dev->ep_in[epnum] = NULL;
  880. }
  881. if (ep && dev->bus)
  882. usb_hcd_endpoint_disable(dev, ep);
  883. }
  884. /**
  885. * usb_disable_interface -- Disable all endpoints for an interface
  886. * @dev: the device whose interface is being disabled
  887. * @intf: pointer to the interface descriptor
  888. *
  889. * Disables all the endpoints for the interface's current altsetting.
  890. */
  891. void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf)
  892. {
  893. struct usb_host_interface *alt = intf->cur_altsetting;
  894. int i;
  895. for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
  896. usb_disable_endpoint(dev,
  897. alt->endpoint[i].desc.bEndpointAddress);
  898. }
  899. }
  900. /*
  901. * usb_disable_device - Disable all the endpoints for a USB device
  902. * @dev: the device whose endpoints are being disabled
  903. * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
  904. *
  905. * Disables all the device's endpoints, potentially including endpoint 0.
  906. * Deallocates hcd/hardware state for the endpoints (nuking all or most
  907. * pending urbs) and usbcore state for the interfaces, so that usbcore
  908. * must usb_set_configuration() before any interfaces could be used.
  909. */
  910. void usb_disable_device(struct usb_device *dev, int skip_ep0)
  911. {
  912. int i;
  913. dev_dbg(&dev->dev, "%s nuking %s URBs\n", __FUNCTION__,
  914. skip_ep0 ? "non-ep0" : "all");
  915. for (i = skip_ep0; i < 16; ++i) {
  916. usb_disable_endpoint(dev, i);
  917. usb_disable_endpoint(dev, i + USB_DIR_IN);
  918. }
  919. dev->toggle[0] = dev->toggle[1] = 0;
  920. /* getting rid of interfaces will disconnect
  921. * any drivers bound to them (a key side effect)
  922. */
  923. if (dev->actconfig) {
  924. for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
  925. struct usb_interface *interface;
  926. /* remove this interface if it has been registered */
  927. interface = dev->actconfig->interface[i];
  928. if (!device_is_registered(&interface->dev))
  929. continue;
  930. dev_dbg (&dev->dev, "unregistering interface %s\n",
  931. interface->dev.bus_id);
  932. usb_remove_sysfs_intf_files(interface);
  933. device_del (&interface->dev);
  934. }
  935. /* Now that the interfaces are unbound, nobody should
  936. * try to access them.
  937. */
  938. for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
  939. put_device (&dev->actconfig->interface[i]->dev);
  940. dev->actconfig->interface[i] = NULL;
  941. }
  942. dev->actconfig = NULL;
  943. if (dev->state == USB_STATE_CONFIGURED)
  944. usb_set_device_state(dev, USB_STATE_ADDRESS);
  945. }
  946. }
  947. /*
  948. * usb_enable_endpoint - Enable an endpoint for USB communications
  949. * @dev: the device whose interface is being enabled
  950. * @ep: the endpoint
  951. *
  952. * Resets the endpoint toggle, and sets dev->ep_{in,out} pointers.
  953. * For control endpoints, both the input and output sides are handled.
  954. */
  955. static void
  956. usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep)
  957. {
  958. unsigned int epaddr = ep->desc.bEndpointAddress;
  959. unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
  960. int is_control;
  961. is_control = ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
  962. == USB_ENDPOINT_XFER_CONTROL);
  963. if (usb_endpoint_out(epaddr) || is_control) {
  964. usb_settoggle(dev, epnum, 1, 0);
  965. dev->ep_out[epnum] = ep;
  966. }
  967. if (!usb_endpoint_out(epaddr) || is_control) {
  968. usb_settoggle(dev, epnum, 0, 0);
  969. dev->ep_in[epnum] = ep;
  970. }
  971. }
  972. /*
  973. * usb_enable_interface - Enable all the endpoints for an interface
  974. * @dev: the device whose interface is being enabled
  975. * @intf: pointer to the interface descriptor
  976. *
  977. * Enables all the endpoints for the interface's current altsetting.
  978. */
  979. static void usb_enable_interface(struct usb_device *dev,
  980. struct usb_interface *intf)
  981. {
  982. struct usb_host_interface *alt = intf->cur_altsetting;
  983. int i;
  984. for (i = 0; i < alt->desc.bNumEndpoints; ++i)
  985. usb_enable_endpoint(dev, &alt->endpoint[i]);
  986. }
  987. /**
  988. * usb_set_interface - Makes a particular alternate setting be current
  989. * @dev: the device whose interface is being updated
  990. * @interface: the interface being updated
  991. * @alternate: the setting being chosen.
  992. * Context: !in_interrupt ()
  993. *
  994. * This is used to enable data transfers on interfaces that may not
  995. * be enabled by default. Not all devices support such configurability.
  996. * Only the driver bound to an interface may change its setting.
  997. *
  998. * Within any given configuration, each interface may have several
  999. * alternative settings. These are often used to control levels of
  1000. * bandwidth consumption. For example, the default setting for a high
  1001. * speed interrupt endpoint may not send more than 64 bytes per microframe,
  1002. * while interrupt transfers of up to 3KBytes per microframe are legal.
  1003. * Also, isochronous endpoints may never be part of an
  1004. * interface's default setting. To access such bandwidth, alternate
  1005. * interface settings must be made current.
  1006. *
  1007. * Note that in the Linux USB subsystem, bandwidth associated with
  1008. * an endpoint in a given alternate setting is not reserved until an URB
  1009. * is submitted that needs that bandwidth. Some other operating systems
  1010. * allocate bandwidth early, when a configuration is chosen.
  1011. *
  1012. * This call is synchronous, and may not be used in an interrupt context.
  1013. * Also, drivers must not change altsettings while urbs are scheduled for
  1014. * endpoints in that interface; all such urbs must first be completed
  1015. * (perhaps forced by unlinking).
  1016. *
  1017. * Returns zero on success, or else the status code returned by the
  1018. * underlying usb_control_msg() call.
  1019. */
  1020. int usb_set_interface(struct usb_device *dev, int interface, int alternate)
  1021. {
  1022. struct usb_interface *iface;
  1023. struct usb_host_interface *alt;
  1024. int ret;
  1025. int manual = 0;
  1026. if (dev->state == USB_STATE_SUSPENDED)
  1027. return -EHOSTUNREACH;
  1028. iface = usb_ifnum_to_if(dev, interface);
  1029. if (!iface) {
  1030. dev_dbg(&dev->dev, "selecting invalid interface %d\n",
  1031. interface);
  1032. return -EINVAL;
  1033. }
  1034. alt = usb_altnum_to_altsetting(iface, alternate);
  1035. if (!alt) {
  1036. warn("selecting invalid altsetting %d", alternate);
  1037. return -EINVAL;
  1038. }
  1039. ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  1040. USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
  1041. alternate, interface, NULL, 0, 5000);
  1042. /* 9.4.10 says devices don't need this and are free to STALL the
  1043. * request if the interface only has one alternate setting.
  1044. */
  1045. if (ret == -EPIPE && iface->num_altsetting == 1) {
  1046. dev_dbg(&dev->dev,
  1047. "manual set_interface for iface %d, alt %d\n",
  1048. interface, alternate);
  1049. manual = 1;
  1050. } else if (ret < 0)
  1051. return ret;
  1052. /* FIXME drivers shouldn't need to replicate/bugfix the logic here
  1053. * when they implement async or easily-killable versions of this or
  1054. * other "should-be-internal" functions (like clear_halt).
  1055. * should hcd+usbcore postprocess control requests?
  1056. */
  1057. /* prevent submissions using previous endpoint settings */
  1058. if (device_is_registered(&iface->dev))
  1059. usb_remove_sysfs_intf_files(iface);
  1060. usb_disable_interface(dev, iface);
  1061. iface->cur_altsetting = alt;
  1062. /* If the interface only has one altsetting and the device didn't
  1063. * accept the request, we attempt to carry out the equivalent action
  1064. * by manually clearing the HALT feature for each endpoint in the
  1065. * new altsetting.
  1066. */
  1067. if (manual) {
  1068. int i;
  1069. for (i = 0; i < alt->desc.bNumEndpoints; i++) {
  1070. unsigned int epaddr =
  1071. alt->endpoint[i].desc.bEndpointAddress;
  1072. unsigned int pipe =
  1073. __create_pipe(dev, USB_ENDPOINT_NUMBER_MASK & epaddr)
  1074. | (usb_endpoint_out(epaddr) ? USB_DIR_OUT : USB_DIR_IN);
  1075. usb_clear_halt(dev, pipe);
  1076. }
  1077. }
  1078. /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
  1079. *
  1080. * Note:
  1081. * Despite EP0 is always present in all interfaces/AS, the list of
  1082. * endpoints from the descriptor does not contain EP0. Due to its
  1083. * omnipresence one might expect EP0 being considered "affected" by
  1084. * any SetInterface request and hence assume toggles need to be reset.
  1085. * However, EP0 toggles are re-synced for every individual transfer
  1086. * during the SETUP stage - hence EP0 toggles are "don't care" here.
  1087. * (Likewise, EP0 never "halts" on well designed devices.)
  1088. */
  1089. usb_enable_interface(dev, iface);
  1090. if (device_is_registered(&iface->dev))
  1091. usb_create_sysfs_intf_files(iface);
  1092. return 0;
  1093. }
  1094. /**
  1095. * usb_reset_configuration - lightweight device reset
  1096. * @dev: the device whose configuration is being reset
  1097. *
  1098. * This issues a standard SET_CONFIGURATION request to the device using
  1099. * the current configuration. The effect is to reset most USB-related
  1100. * state in the device, including interface altsettings (reset to zero),
  1101. * endpoint halts (cleared), and data toggle (only for bulk and interrupt
  1102. * endpoints). Other usbcore state is unchanged, including bindings of
  1103. * usb device drivers to interfaces.
  1104. *
  1105. * Because this affects multiple interfaces, avoid using this with composite
  1106. * (multi-interface) devices. Instead, the driver for each interface may
  1107. * use usb_set_interface() on the interfaces it claims. Be careful though;
  1108. * some devices don't support the SET_INTERFACE request, and others won't
  1109. * reset all the interface state (notably data toggles). Resetting the whole
  1110. * configuration would affect other drivers' interfaces.
  1111. *
  1112. * The caller must own the device lock.
  1113. *
  1114. * Returns zero on success, else a negative error code.
  1115. */
  1116. int usb_reset_configuration(struct usb_device *dev)
  1117. {
  1118. int i, retval;
  1119. struct usb_host_config *config;
  1120. if (dev->state == USB_STATE_SUSPENDED)
  1121. return -EHOSTUNREACH;
  1122. /* caller must have locked the device and must own
  1123. * the usb bus readlock (so driver bindings are stable);
  1124. * calls during probe() are fine
  1125. */
  1126. for (i = 1; i < 16; ++i) {
  1127. usb_disable_endpoint(dev, i);
  1128. usb_disable_endpoint(dev, i + USB_DIR_IN);
  1129. }
  1130. config = dev->actconfig;
  1131. retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  1132. USB_REQ_SET_CONFIGURATION, 0,
  1133. config->desc.bConfigurationValue, 0,
  1134. NULL, 0, USB_CTRL_SET_TIMEOUT);
  1135. if (retval < 0)
  1136. return retval;
  1137. dev->toggle[0] = dev->toggle[1] = 0;
  1138. /* re-init hc/hcd interface/endpoint state */
  1139. for (i = 0; i < config->desc.bNumInterfaces; i++) {
  1140. struct usb_interface *intf = config->interface[i];
  1141. struct usb_host_interface *alt;
  1142. if (device_is_registered(&intf->dev))
  1143. usb_remove_sysfs_intf_files(intf);
  1144. alt = usb_altnum_to_altsetting(intf, 0);
  1145. /* No altsetting 0? We'll assume the first altsetting.
  1146. * We could use a GetInterface call, but if a device is
  1147. * so non-compliant that it doesn't have altsetting 0
  1148. * then I wouldn't trust its reply anyway.
  1149. */
  1150. if (!alt)
  1151. alt = &intf->altsetting[0];
  1152. intf->cur_altsetting = alt;
  1153. usb_enable_interface(dev, intf);
  1154. if (device_is_registered(&intf->dev))
  1155. usb_create_sysfs_intf_files(intf);
  1156. }
  1157. return 0;
  1158. }
  1159. static void release_interface(struct device *dev)
  1160. {
  1161. struct usb_interface *intf = to_usb_interface(dev);
  1162. struct usb_interface_cache *intfc =
  1163. altsetting_to_usb_interface_cache(intf->altsetting);
  1164. kref_put(&intfc->ref, usb_release_interface_cache);
  1165. kfree(intf);
  1166. }
  1167. /*
  1168. * usb_set_configuration - Makes a particular device setting be current
  1169. * @dev: the device whose configuration is being updated
  1170. * @configuration: the configuration being chosen.
  1171. * Context: !in_interrupt(), caller owns the device lock
  1172. *
  1173. * This is used to enable non-default device modes. Not all devices
  1174. * use this kind of configurability; many devices only have one
  1175. * configuration.
  1176. *
  1177. * @configuration is the value of the configuration to be installed.
  1178. * According to the USB spec (e.g. section 9.1.1.5), configuration values
  1179. * must be non-zero; a value of zero indicates that the device in
  1180. * unconfigured. However some devices erroneously use 0 as one of their
  1181. * configuration values. To help manage such devices, this routine will
  1182. * accept @configuration = -1 as indicating the device should be put in
  1183. * an unconfigured state.
  1184. *
  1185. * USB device configurations may affect Linux interoperability,
  1186. * power consumption and the functionality available. For example,
  1187. * the default configuration is limited to using 100mA of bus power,
  1188. * so that when certain device functionality requires more power,
  1189. * and the device is bus powered, that functionality should be in some
  1190. * non-default device configuration. Other device modes may also be
  1191. * reflected as configuration options, such as whether two ISDN
  1192. * channels are available independently; and choosing between open
  1193. * standard device protocols (like CDC) or proprietary ones.
  1194. *
  1195. * Note that USB has an additional level of device configurability,
  1196. * associated with interfaces. That configurability is accessed using
  1197. * usb_set_interface().
  1198. *
  1199. * This call is synchronous. The calling context must be able to sleep,
  1200. * must own the device lock, and must not hold the driver model's USB
  1201. * bus rwsem; usb device driver probe() methods cannot use this routine.
  1202. *
  1203. * Returns zero on success, or else the status code returned by the
  1204. * underlying call that failed. On successful completion, each interface
  1205. * in the original device configuration has been destroyed, and each one
  1206. * in the new configuration has been probed by all relevant usb device
  1207. * drivers currently known to the kernel.
  1208. */
  1209. int usb_set_configuration(struct usb_device *dev, int configuration)
  1210. {
  1211. int i, ret;
  1212. struct usb_host_config *cp = NULL;
  1213. struct usb_interface **new_interfaces = NULL;
  1214. int n, nintf;
  1215. if (configuration == -1)
  1216. configuration = 0;
  1217. else {
  1218. for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
  1219. if (dev->config[i].desc.bConfigurationValue ==
  1220. configuration) {
  1221. cp = &dev->config[i];
  1222. break;
  1223. }
  1224. }
  1225. }
  1226. if ((!cp && configuration != 0))
  1227. return -EINVAL;
  1228. /* The USB spec says configuration 0 means unconfigured.
  1229. * But if a device includes a configuration numbered 0,
  1230. * we will accept it as a correctly configured state.
  1231. * Use -1 if you really want to unconfigure the device.
  1232. */
  1233. if (cp && configuration == 0)
  1234. dev_warn(&dev->dev, "config 0 descriptor??\n");
  1235. /* Allocate memory for new interfaces before doing anything else,
  1236. * so that if we run out then nothing will have changed. */
  1237. n = nintf = 0;
  1238. if (cp) {
  1239. nintf = cp->desc.bNumInterfaces;
  1240. new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
  1241. GFP_KERNEL);
  1242. if (!new_interfaces) {
  1243. dev_err(&dev->dev, "Out of memory");
  1244. return -ENOMEM;
  1245. }
  1246. for (; n < nintf; ++n) {
  1247. new_interfaces[n] = kzalloc(
  1248. sizeof(struct usb_interface),
  1249. GFP_KERNEL);
  1250. if (!new_interfaces[n]) {
  1251. dev_err(&dev->dev, "Out of memory");
  1252. ret = -ENOMEM;
  1253. free_interfaces:
  1254. while (--n >= 0)
  1255. kfree(new_interfaces[n]);
  1256. kfree(new_interfaces);
  1257. return ret;
  1258. }
  1259. }
  1260. i = dev->bus_mA - cp->desc.bMaxPower * 2;
  1261. if (i < 0)
  1262. dev_warn(&dev->dev, "new config #%d exceeds power "
  1263. "limit by %dmA\n",
  1264. configuration, -i);
  1265. }
  1266. /* Wake up the device so we can send it the Set-Config request */
  1267. ret = usb_autoresume_device(dev);
  1268. if (ret)
  1269. goto free_interfaces;
  1270. /* if it's already configured, clear out old state first.
  1271. * getting rid of old interfaces means unbinding their drivers.
  1272. */
  1273. if (dev->state != USB_STATE_ADDRESS)
  1274. usb_disable_device (dev, 1); // Skip ep0
  1275. if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  1276. USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
  1277. NULL, 0, USB_CTRL_SET_TIMEOUT)) < 0) {
  1278. /* All the old state is gone, so what else can we do?
  1279. * The device is probably useless now anyway.
  1280. */
  1281. cp = NULL;
  1282. }
  1283. dev->actconfig = cp;
  1284. if (!cp) {
  1285. usb_set_device_state(dev, USB_STATE_ADDRESS);
  1286. usb_autosuspend_device(dev);
  1287. goto free_interfaces;
  1288. }
  1289. usb_set_device_state(dev, USB_STATE_CONFIGURED);
  1290. /* Initialize the new interface structures and the
  1291. * hc/hcd/usbcore interface/endpoint state.
  1292. */
  1293. for (i = 0; i < nintf; ++i) {
  1294. struct usb_interface_cache *intfc;
  1295. struct usb_interface *intf;
  1296. struct usb_host_interface *alt;
  1297. cp->interface[i] = intf = new_interfaces[i];
  1298. intfc = cp->intf_cache[i];
  1299. intf->altsetting = intfc->altsetting;
  1300. intf->num_altsetting = intfc->num_altsetting;
  1301. kref_get(&intfc->ref);
  1302. alt = usb_altnum_to_altsetting(intf, 0);
  1303. /* No altsetting 0? We'll assume the first altsetting.
  1304. * We could use a GetInterface call, but if a device is
  1305. * so non-compliant that it doesn't have altsetting 0
  1306. * then I wouldn't trust its reply anyway.
  1307. */
  1308. if (!alt)
  1309. alt = &intf->altsetting[0];
  1310. intf->cur_altsetting = alt;
  1311. usb_enable_interface(dev, intf);
  1312. intf->dev.parent = &dev->dev;
  1313. intf->dev.driver = NULL;
  1314. intf->dev.bus = &usb_bus_type;
  1315. intf->dev.dma_mask = dev->dev.dma_mask;
  1316. intf->dev.release = release_interface;
  1317. device_initialize (&intf->dev);
  1318. mark_quiesced(intf);
  1319. sprintf (&intf->dev.bus_id[0], "%d-%s:%d.%d",
  1320. dev->bus->busnum, dev->devpath,
  1321. configuration, alt->desc.bInterfaceNumber);
  1322. }
  1323. kfree(new_interfaces);
  1324. if (cp->string == NULL)
  1325. cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
  1326. /* Now that all the interfaces are set up, register them
  1327. * to trigger binding of drivers to interfaces. probe()
  1328. * routines may install different altsettings and may
  1329. * claim() any interfaces not yet bound. Many class drivers
  1330. * need that: CDC, audio, video, etc.
  1331. */
  1332. for (i = 0; i < nintf; ++i) {
  1333. struct usb_interface *intf = cp->interface[i];
  1334. dev_dbg (&dev->dev,
  1335. "adding %s (config #%d, interface %d)\n",
  1336. intf->dev.bus_id, configuration,
  1337. intf->cur_altsetting->desc.bInterfaceNumber);
  1338. ret = device_add (&intf->dev);
  1339. if (ret != 0) {
  1340. dev_err(&dev->dev, "device_add(%s) --> %d\n",
  1341. intf->dev.bus_id, ret);
  1342. continue;
  1343. }
  1344. usb_create_sysfs_intf_files (intf);
  1345. }
  1346. usb_autosuspend_device(dev);
  1347. return 0;
  1348. }
  1349. struct set_config_request {
  1350. struct usb_device *udev;
  1351. int config;
  1352. struct work_struct work;
  1353. };
  1354. /* Worker routine for usb_driver_set_configuration() */
  1355. static void driver_set_config_work(struct work_struct *work)
  1356. {
  1357. struct set_config_request *req =
  1358. container_of(work, struct set_config_request, work);
  1359. usb_lock_device(req->udev);
  1360. usb_set_configuration(req->udev, req->config);
  1361. usb_unlock_device(req->udev);
  1362. usb_put_dev(req->udev);
  1363. kfree(req);
  1364. }
  1365. /**
  1366. * usb_driver_set_configuration - Provide a way for drivers to change device configurations
  1367. * @udev: the device whose configuration is being updated
  1368. * @config: the configuration being chosen.
  1369. * Context: In process context, must be able to sleep
  1370. *
  1371. * Device interface drivers are not allowed to change device configurations.
  1372. * This is because changing configurations will destroy the interface the
  1373. * driver is bound to and create new ones; it would be like a floppy-disk
  1374. * driver telling the computer to replace the floppy-disk drive with a
  1375. * tape drive!
  1376. *
  1377. * Still, in certain specialized circumstances the need may arise. This
  1378. * routine gets around the normal restrictions by using a work thread to
  1379. * submit the change-config request.
  1380. *
  1381. * Returns 0 if the request was succesfully queued, error code otherwise.
  1382. * The caller has no way to know whether the queued request will eventually
  1383. * succeed.
  1384. */
  1385. int usb_driver_set_configuration(struct usb_device *udev, int config)
  1386. {
  1387. struct set_config_request *req;
  1388. req = kmalloc(sizeof(*req), GFP_KERNEL);
  1389. if (!req)
  1390. return -ENOMEM;
  1391. req->udev = udev;
  1392. req->config = config;
  1393. INIT_WORK(&req->work, driver_set_config_work);
  1394. usb_get_dev(udev);
  1395. schedule_work(&req->work);
  1396. return 0;
  1397. }
  1398. EXPORT_SYMBOL_GPL(usb_driver_set_configuration);
  1399. // synchronous request completion model
  1400. EXPORT_SYMBOL(usb_control_msg);
  1401. EXPORT_SYMBOL(usb_bulk_msg);
  1402. EXPORT_SYMBOL(usb_sg_init);
  1403. EXPORT_SYMBOL(usb_sg_cancel);
  1404. EXPORT_SYMBOL(usb_sg_wait);
  1405. // synchronous control message convenience routines
  1406. EXPORT_SYMBOL(usb_get_descriptor);
  1407. EXPORT_SYMBOL(usb_get_status);
  1408. EXPORT_SYMBOL(usb_string);
  1409. // synchronous calls that also maintain usbcore state
  1410. EXPORT_SYMBOL(usb_clear_halt);
  1411. EXPORT_SYMBOL(usb_reset_configuration);
  1412. EXPORT_SYMBOL(usb_set_interface);