message.c 60 KB

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