message.c 67 KB

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