message.c 65 KB

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