message.c 58 KB

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