message.c 66 KB

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