message.c 60 KB

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