message.c 67 KB

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