message.c 66 KB

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