message.c 49 KB

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