message.c 65 KB

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