message.c 59 KB

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