message.c 60 KB

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