message.c 49 KB

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