message.c 65 KB

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