message.c 66 KB

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