message.c 52 KB

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