message.c 61 KB

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