message.c 67 KB

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