message.c 58 KB

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