message.c 46 KB

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