message.c 45 KB

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