message.c 61 KB

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