message.c 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252
  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_set_isoch_delay - informs the device of the packet transmit delay
  815. * @dev: the device whose delay is to be informed
  816. * Context: !in_interrupt()
  817. *
  818. * Since this is an optional request, we don't bother if it fails.
  819. */
  820. int usb_set_isoch_delay(struct usb_device *dev)
  821. {
  822. /* skip hub devices */
  823. if (dev->descriptor.bDeviceClass == USB_CLASS_HUB)
  824. return 0;
  825. /* skip non-SS/non-SSP devices */
  826. if (dev->speed < USB_SPEED_SUPER)
  827. return 0;
  828. return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  829. USB_REQ_SET_ISOCH_DELAY,
  830. USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_DEVICE,
  831. cpu_to_le16(dev->hub_delay), 0, NULL, 0,
  832. USB_CTRL_SET_TIMEOUT);
  833. }
  834. /**
  835. * usb_get_status - issues a GET_STATUS call
  836. * @dev: the device whose status is being checked
  837. * @recip: USB_RECIP_*; for device, interface, or endpoint
  838. * @type: USB_STATUS_TYPE_*; for standard or PTM status types
  839. * @target: zero (for device), else interface or endpoint number
  840. * @data: pointer to two bytes of bitmap data
  841. * Context: !in_interrupt ()
  842. *
  843. * Returns device, interface, or endpoint status. Normally only of
  844. * interest to see if the device is self powered, or has enabled the
  845. * remote wakeup facility; or whether a bulk or interrupt endpoint
  846. * is halted ("stalled").
  847. *
  848. * Bits in these status bitmaps are set using the SET_FEATURE request,
  849. * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
  850. * function should be used to clear halt ("stall") status.
  851. *
  852. * This call is synchronous, and may not be used in an interrupt context.
  853. *
  854. * Returns 0 and the status value in *@data (in host byte order) on success,
  855. * or else the status code from the underlying usb_control_msg() call.
  856. */
  857. int usb_get_status(struct usb_device *dev, int recip, int type, int target,
  858. void *data)
  859. {
  860. int ret;
  861. void *status;
  862. int length;
  863. switch (type) {
  864. case USB_STATUS_TYPE_STANDARD:
  865. length = 2;
  866. break;
  867. case USB_STATUS_TYPE_PTM:
  868. if (recip != USB_RECIP_DEVICE)
  869. return -EINVAL;
  870. length = 4;
  871. break;
  872. default:
  873. return -EINVAL;
  874. }
  875. status = kmalloc(length, GFP_KERNEL);
  876. if (!status)
  877. return -ENOMEM;
  878. ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  879. USB_REQ_GET_STATUS, USB_DIR_IN | recip, USB_STATUS_TYPE_STANDARD,
  880. target, status, length, USB_CTRL_GET_TIMEOUT);
  881. switch (ret) {
  882. case 4:
  883. if (type != USB_STATUS_TYPE_PTM) {
  884. ret = -EIO;
  885. break;
  886. }
  887. *(u32 *) data = le32_to_cpu(*(__le32 *) status);
  888. ret = 0;
  889. break;
  890. case 2:
  891. if (type != USB_STATUS_TYPE_STANDARD) {
  892. ret = -EIO;
  893. break;
  894. }
  895. *(u16 *) data = le16_to_cpu(*(__le16 *) status);
  896. ret = 0;
  897. break;
  898. default:
  899. ret = -EIO;
  900. }
  901. kfree(status);
  902. return ret;
  903. }
  904. EXPORT_SYMBOL_GPL(usb_get_status);
  905. /**
  906. * usb_clear_halt - tells device to clear endpoint halt/stall condition
  907. * @dev: device whose endpoint is halted
  908. * @pipe: endpoint "pipe" being cleared
  909. * Context: !in_interrupt ()
  910. *
  911. * This is used to clear halt conditions for bulk and interrupt endpoints,
  912. * as reported by URB completion status. Endpoints that are halted are
  913. * sometimes referred to as being "stalled". Such endpoints are unable
  914. * to transmit or receive data until the halt status is cleared. Any URBs
  915. * queued for such an endpoint should normally be unlinked by the driver
  916. * before clearing the halt condition, as described in sections 5.7.5
  917. * and 5.8.5 of the USB 2.0 spec.
  918. *
  919. * Note that control and isochronous endpoints don't halt, although control
  920. * endpoints report "protocol stall" (for unsupported requests) using the
  921. * same status code used to report a true stall.
  922. *
  923. * This call is synchronous, and may not be used in an interrupt context.
  924. *
  925. * Return: Zero on success, or else the status code returned by the
  926. * underlying usb_control_msg() call.
  927. */
  928. int usb_clear_halt(struct usb_device *dev, int pipe)
  929. {
  930. int result;
  931. int endp = usb_pipeendpoint(pipe);
  932. if (usb_pipein(pipe))
  933. endp |= USB_DIR_IN;
  934. /* we don't care if it wasn't halted first. in fact some devices
  935. * (like some ibmcam model 1 units) seem to expect hosts to make
  936. * this request for iso endpoints, which can't halt!
  937. */
  938. result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  939. USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
  940. USB_ENDPOINT_HALT, endp, NULL, 0,
  941. USB_CTRL_SET_TIMEOUT);
  942. /* don't un-halt or force to DATA0 except on success */
  943. if (result < 0)
  944. return result;
  945. /* NOTE: seems like Microsoft and Apple don't bother verifying
  946. * the clear "took", so some devices could lock up if you check...
  947. * such as the Hagiwara FlashGate DUAL. So we won't bother.
  948. *
  949. * NOTE: make sure the logic here doesn't diverge much from
  950. * the copy in usb-storage, for as long as we need two copies.
  951. */
  952. usb_reset_endpoint(dev, endp);
  953. return 0;
  954. }
  955. EXPORT_SYMBOL_GPL(usb_clear_halt);
  956. static int create_intf_ep_devs(struct usb_interface *intf)
  957. {
  958. struct usb_device *udev = interface_to_usbdev(intf);
  959. struct usb_host_interface *alt = intf->cur_altsetting;
  960. int i;
  961. if (intf->ep_devs_created || intf->unregistering)
  962. return 0;
  963. for (i = 0; i < alt->desc.bNumEndpoints; ++i)
  964. (void) usb_create_ep_devs(&intf->dev, &alt->endpoint[i], udev);
  965. intf->ep_devs_created = 1;
  966. return 0;
  967. }
  968. static void remove_intf_ep_devs(struct usb_interface *intf)
  969. {
  970. struct usb_host_interface *alt = intf->cur_altsetting;
  971. int i;
  972. if (!intf->ep_devs_created)
  973. return;
  974. for (i = 0; i < alt->desc.bNumEndpoints; ++i)
  975. usb_remove_ep_devs(&alt->endpoint[i]);
  976. intf->ep_devs_created = 0;
  977. }
  978. /**
  979. * usb_disable_endpoint -- Disable an endpoint by address
  980. * @dev: the device whose endpoint is being disabled
  981. * @epaddr: the endpoint's address. Endpoint number for output,
  982. * endpoint number + USB_DIR_IN for input
  983. * @reset_hardware: flag to erase any endpoint state stored in the
  984. * controller hardware
  985. *
  986. * Disables the endpoint for URB submission and nukes all pending URBs.
  987. * If @reset_hardware is set then also deallocates hcd/hardware state
  988. * for the endpoint.
  989. */
  990. void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr,
  991. bool reset_hardware)
  992. {
  993. unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
  994. struct usb_host_endpoint *ep;
  995. if (!dev)
  996. return;
  997. if (usb_endpoint_out(epaddr)) {
  998. ep = dev->ep_out[epnum];
  999. if (reset_hardware)
  1000. dev->ep_out[epnum] = NULL;
  1001. } else {
  1002. ep = dev->ep_in[epnum];
  1003. if (reset_hardware)
  1004. dev->ep_in[epnum] = NULL;
  1005. }
  1006. if (ep) {
  1007. ep->enabled = 0;
  1008. usb_hcd_flush_endpoint(dev, ep);
  1009. if (reset_hardware)
  1010. usb_hcd_disable_endpoint(dev, ep);
  1011. }
  1012. }
  1013. /**
  1014. * usb_reset_endpoint - Reset an endpoint's state.
  1015. * @dev: the device whose endpoint is to be reset
  1016. * @epaddr: the endpoint's address. Endpoint number for output,
  1017. * endpoint number + USB_DIR_IN for input
  1018. *
  1019. * Resets any host-side endpoint state such as the toggle bit,
  1020. * sequence number or current window.
  1021. */
  1022. void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr)
  1023. {
  1024. unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
  1025. struct usb_host_endpoint *ep;
  1026. if (usb_endpoint_out(epaddr))
  1027. ep = dev->ep_out[epnum];
  1028. else
  1029. ep = dev->ep_in[epnum];
  1030. if (ep)
  1031. usb_hcd_reset_endpoint(dev, ep);
  1032. }
  1033. EXPORT_SYMBOL_GPL(usb_reset_endpoint);
  1034. /**
  1035. * usb_disable_interface -- Disable all endpoints for an interface
  1036. * @dev: the device whose interface is being disabled
  1037. * @intf: pointer to the interface descriptor
  1038. * @reset_hardware: flag to erase any endpoint state stored in the
  1039. * controller hardware
  1040. *
  1041. * Disables all the endpoints for the interface's current altsetting.
  1042. */
  1043. void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf,
  1044. bool reset_hardware)
  1045. {
  1046. struct usb_host_interface *alt = intf->cur_altsetting;
  1047. int i;
  1048. for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
  1049. usb_disable_endpoint(dev,
  1050. alt->endpoint[i].desc.bEndpointAddress,
  1051. reset_hardware);
  1052. }
  1053. }
  1054. /**
  1055. * usb_disable_device - Disable all the endpoints for a USB device
  1056. * @dev: the device whose endpoints are being disabled
  1057. * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
  1058. *
  1059. * Disables all the device's endpoints, potentially including endpoint 0.
  1060. * Deallocates hcd/hardware state for the endpoints (nuking all or most
  1061. * pending urbs) and usbcore state for the interfaces, so that usbcore
  1062. * must usb_set_configuration() before any interfaces could be used.
  1063. */
  1064. void usb_disable_device(struct usb_device *dev, int skip_ep0)
  1065. {
  1066. int i;
  1067. struct usb_hcd *hcd = bus_to_hcd(dev->bus);
  1068. /* getting rid of interfaces will disconnect
  1069. * any drivers bound to them (a key side effect)
  1070. */
  1071. if (dev->actconfig) {
  1072. /*
  1073. * FIXME: In order to avoid self-deadlock involving the
  1074. * bandwidth_mutex, we have to mark all the interfaces
  1075. * before unregistering any of them.
  1076. */
  1077. for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++)
  1078. dev->actconfig->interface[i]->unregistering = 1;
  1079. for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
  1080. struct usb_interface *interface;
  1081. /* remove this interface if it has been registered */
  1082. interface = dev->actconfig->interface[i];
  1083. if (!device_is_registered(&interface->dev))
  1084. continue;
  1085. dev_dbg(&dev->dev, "unregistering interface %s\n",
  1086. dev_name(&interface->dev));
  1087. remove_intf_ep_devs(interface);
  1088. device_del(&interface->dev);
  1089. }
  1090. /* Now that the interfaces are unbound, nobody should
  1091. * try to access them.
  1092. */
  1093. for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
  1094. put_device(&dev->actconfig->interface[i]->dev);
  1095. dev->actconfig->interface[i] = NULL;
  1096. }
  1097. if (dev->usb2_hw_lpm_enabled == 1)
  1098. usb_set_usb2_hardware_lpm(dev, 0);
  1099. usb_unlocked_disable_lpm(dev);
  1100. usb_disable_ltm(dev);
  1101. dev->actconfig = NULL;
  1102. if (dev->state == USB_STATE_CONFIGURED)
  1103. usb_set_device_state(dev, USB_STATE_ADDRESS);
  1104. }
  1105. dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__,
  1106. skip_ep0 ? "non-ep0" : "all");
  1107. if (hcd->driver->check_bandwidth) {
  1108. /* First pass: Cancel URBs, leave endpoint pointers intact. */
  1109. for (i = skip_ep0; i < 16; ++i) {
  1110. usb_disable_endpoint(dev, i, false);
  1111. usb_disable_endpoint(dev, i + USB_DIR_IN, false);
  1112. }
  1113. /* Remove endpoints from the host controller internal state */
  1114. mutex_lock(hcd->bandwidth_mutex);
  1115. usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
  1116. mutex_unlock(hcd->bandwidth_mutex);
  1117. /* Second pass: remove endpoint pointers */
  1118. }
  1119. for (i = skip_ep0; i < 16; ++i) {
  1120. usb_disable_endpoint(dev, i, true);
  1121. usb_disable_endpoint(dev, i + USB_DIR_IN, true);
  1122. }
  1123. }
  1124. /**
  1125. * usb_enable_endpoint - Enable an endpoint for USB communications
  1126. * @dev: the device whose interface is being enabled
  1127. * @ep: the endpoint
  1128. * @reset_ep: flag to reset the endpoint state
  1129. *
  1130. * Resets the endpoint state if asked, and sets dev->ep_{in,out} pointers.
  1131. * For control endpoints, both the input and output sides are handled.
  1132. */
  1133. void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep,
  1134. bool reset_ep)
  1135. {
  1136. int epnum = usb_endpoint_num(&ep->desc);
  1137. int is_out = usb_endpoint_dir_out(&ep->desc);
  1138. int is_control = usb_endpoint_xfer_control(&ep->desc);
  1139. if (reset_ep)
  1140. usb_hcd_reset_endpoint(dev, ep);
  1141. if (is_out || is_control)
  1142. dev->ep_out[epnum] = ep;
  1143. if (!is_out || is_control)
  1144. dev->ep_in[epnum] = ep;
  1145. ep->enabled = 1;
  1146. }
  1147. /**
  1148. * usb_enable_interface - Enable all the endpoints for an interface
  1149. * @dev: the device whose interface is being enabled
  1150. * @intf: pointer to the interface descriptor
  1151. * @reset_eps: flag to reset the endpoints' state
  1152. *
  1153. * Enables all the endpoints for the interface's current altsetting.
  1154. */
  1155. void usb_enable_interface(struct usb_device *dev,
  1156. struct usb_interface *intf, bool reset_eps)
  1157. {
  1158. struct usb_host_interface *alt = intf->cur_altsetting;
  1159. int i;
  1160. for (i = 0; i < alt->desc.bNumEndpoints; ++i)
  1161. usb_enable_endpoint(dev, &alt->endpoint[i], reset_eps);
  1162. }
  1163. /**
  1164. * usb_set_interface - Makes a particular alternate setting be current
  1165. * @dev: the device whose interface is being updated
  1166. * @interface: the interface being updated
  1167. * @alternate: the setting being chosen.
  1168. * Context: !in_interrupt ()
  1169. *
  1170. * This is used to enable data transfers on interfaces that may not
  1171. * be enabled by default. Not all devices support such configurability.
  1172. * Only the driver bound to an interface may change its setting.
  1173. *
  1174. * Within any given configuration, each interface may have several
  1175. * alternative settings. These are often used to control levels of
  1176. * bandwidth consumption. For example, the default setting for a high
  1177. * speed interrupt endpoint may not send more than 64 bytes per microframe,
  1178. * while interrupt transfers of up to 3KBytes per microframe are legal.
  1179. * Also, isochronous endpoints may never be part of an
  1180. * interface's default setting. To access such bandwidth, alternate
  1181. * interface settings must be made current.
  1182. *
  1183. * Note that in the Linux USB subsystem, bandwidth associated with
  1184. * an endpoint in a given alternate setting is not reserved until an URB
  1185. * is submitted that needs that bandwidth. Some other operating systems
  1186. * allocate bandwidth early, when a configuration is chosen.
  1187. *
  1188. * This call is synchronous, and may not be used in an interrupt context.
  1189. * Also, drivers must not change altsettings while urbs are scheduled for
  1190. * endpoints in that interface; all such urbs must first be completed
  1191. * (perhaps forced by unlinking).
  1192. *
  1193. * Return: Zero on success, or else the status code returned by the
  1194. * underlying usb_control_msg() call.
  1195. */
  1196. int usb_set_interface(struct usb_device *dev, int interface, int alternate)
  1197. {
  1198. struct usb_interface *iface;
  1199. struct usb_host_interface *alt;
  1200. struct usb_hcd *hcd = bus_to_hcd(dev->bus);
  1201. int i, ret, manual = 0;
  1202. unsigned int epaddr;
  1203. unsigned int pipe;
  1204. if (dev->state == USB_STATE_SUSPENDED)
  1205. return -EHOSTUNREACH;
  1206. iface = usb_ifnum_to_if(dev, interface);
  1207. if (!iface) {
  1208. dev_dbg(&dev->dev, "selecting invalid interface %d\n",
  1209. interface);
  1210. return -EINVAL;
  1211. }
  1212. if (iface->unregistering)
  1213. return -ENODEV;
  1214. alt = usb_altnum_to_altsetting(iface, alternate);
  1215. if (!alt) {
  1216. dev_warn(&dev->dev, "selecting invalid altsetting %d\n",
  1217. alternate);
  1218. return -EINVAL;
  1219. }
  1220. /* Make sure we have enough bandwidth for this alternate interface.
  1221. * Remove the current alt setting and add the new alt setting.
  1222. */
  1223. mutex_lock(hcd->bandwidth_mutex);
  1224. /* Disable LPM, and re-enable it once the new alt setting is installed,
  1225. * so that the xHCI driver can recalculate the U1/U2 timeouts.
  1226. */
  1227. if (usb_disable_lpm(dev)) {
  1228. dev_err(&iface->dev, "%s Failed to disable LPM\n", __func__);
  1229. mutex_unlock(hcd->bandwidth_mutex);
  1230. return -ENOMEM;
  1231. }
  1232. /* Changing alt-setting also frees any allocated streams */
  1233. for (i = 0; i < iface->cur_altsetting->desc.bNumEndpoints; i++)
  1234. iface->cur_altsetting->endpoint[i].streams = 0;
  1235. ret = usb_hcd_alloc_bandwidth(dev, NULL, iface->cur_altsetting, alt);
  1236. if (ret < 0) {
  1237. dev_info(&dev->dev, "Not enough bandwidth for altsetting %d\n",
  1238. alternate);
  1239. usb_enable_lpm(dev);
  1240. mutex_unlock(hcd->bandwidth_mutex);
  1241. return ret;
  1242. }
  1243. if (dev->quirks & USB_QUIRK_NO_SET_INTF)
  1244. ret = -EPIPE;
  1245. else
  1246. ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  1247. USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
  1248. alternate, interface, NULL, 0, 5000);
  1249. /* 9.4.10 says devices don't need this and are free to STALL the
  1250. * request if the interface only has one alternate setting.
  1251. */
  1252. if (ret == -EPIPE && iface->num_altsetting == 1) {
  1253. dev_dbg(&dev->dev,
  1254. "manual set_interface for iface %d, alt %d\n",
  1255. interface, alternate);
  1256. manual = 1;
  1257. } else if (ret < 0) {
  1258. /* Re-instate the old alt setting */
  1259. usb_hcd_alloc_bandwidth(dev, NULL, alt, iface->cur_altsetting);
  1260. usb_enable_lpm(dev);
  1261. mutex_unlock(hcd->bandwidth_mutex);
  1262. return ret;
  1263. }
  1264. mutex_unlock(hcd->bandwidth_mutex);
  1265. /* FIXME drivers shouldn't need to replicate/bugfix the logic here
  1266. * when they implement async or easily-killable versions of this or
  1267. * other "should-be-internal" functions (like clear_halt).
  1268. * should hcd+usbcore postprocess control requests?
  1269. */
  1270. /* prevent submissions using previous endpoint settings */
  1271. if (iface->cur_altsetting != alt) {
  1272. remove_intf_ep_devs(iface);
  1273. usb_remove_sysfs_intf_files(iface);
  1274. }
  1275. usb_disable_interface(dev, iface, true);
  1276. iface->cur_altsetting = alt;
  1277. /* Now that the interface is installed, re-enable LPM. */
  1278. usb_unlocked_enable_lpm(dev);
  1279. /* If the interface only has one altsetting and the device didn't
  1280. * accept the request, we attempt to carry out the equivalent action
  1281. * by manually clearing the HALT feature for each endpoint in the
  1282. * new altsetting.
  1283. */
  1284. if (manual) {
  1285. for (i = 0; i < alt->desc.bNumEndpoints; i++) {
  1286. epaddr = alt->endpoint[i].desc.bEndpointAddress;
  1287. pipe = __create_pipe(dev,
  1288. USB_ENDPOINT_NUMBER_MASK & epaddr) |
  1289. (usb_endpoint_out(epaddr) ?
  1290. USB_DIR_OUT : USB_DIR_IN);
  1291. usb_clear_halt(dev, pipe);
  1292. }
  1293. }
  1294. /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
  1295. *
  1296. * Note:
  1297. * Despite EP0 is always present in all interfaces/AS, the list of
  1298. * endpoints from the descriptor does not contain EP0. Due to its
  1299. * omnipresence one might expect EP0 being considered "affected" by
  1300. * any SetInterface request and hence assume toggles need to be reset.
  1301. * However, EP0 toggles are re-synced for every individual transfer
  1302. * during the SETUP stage - hence EP0 toggles are "don't care" here.
  1303. * (Likewise, EP0 never "halts" on well designed devices.)
  1304. */
  1305. usb_enable_interface(dev, iface, true);
  1306. if (device_is_registered(&iface->dev)) {
  1307. usb_create_sysfs_intf_files(iface);
  1308. create_intf_ep_devs(iface);
  1309. }
  1310. return 0;
  1311. }
  1312. EXPORT_SYMBOL_GPL(usb_set_interface);
  1313. /**
  1314. * usb_reset_configuration - lightweight device reset
  1315. * @dev: the device whose configuration is being reset
  1316. *
  1317. * This issues a standard SET_CONFIGURATION request to the device using
  1318. * the current configuration. The effect is to reset most USB-related
  1319. * state in the device, including interface altsettings (reset to zero),
  1320. * endpoint halts (cleared), and endpoint state (only for bulk and interrupt
  1321. * endpoints). Other usbcore state is unchanged, including bindings of
  1322. * usb device drivers to interfaces.
  1323. *
  1324. * Because this affects multiple interfaces, avoid using this with composite
  1325. * (multi-interface) devices. Instead, the driver for each interface may
  1326. * use usb_set_interface() on the interfaces it claims. Be careful though;
  1327. * some devices don't support the SET_INTERFACE request, and others won't
  1328. * reset all the interface state (notably endpoint state). Resetting the whole
  1329. * configuration would affect other drivers' interfaces.
  1330. *
  1331. * The caller must own the device lock.
  1332. *
  1333. * Return: Zero on success, else a negative error code.
  1334. */
  1335. int usb_reset_configuration(struct usb_device *dev)
  1336. {
  1337. int i, retval;
  1338. struct usb_host_config *config;
  1339. struct usb_hcd *hcd = bus_to_hcd(dev->bus);
  1340. if (dev->state == USB_STATE_SUSPENDED)
  1341. return -EHOSTUNREACH;
  1342. /* caller must have locked the device and must own
  1343. * the usb bus readlock (so driver bindings are stable);
  1344. * calls during probe() are fine
  1345. */
  1346. for (i = 1; i < 16; ++i) {
  1347. usb_disable_endpoint(dev, i, true);
  1348. usb_disable_endpoint(dev, i + USB_DIR_IN, true);
  1349. }
  1350. config = dev->actconfig;
  1351. retval = 0;
  1352. mutex_lock(hcd->bandwidth_mutex);
  1353. /* Disable LPM, and re-enable it once the configuration is reset, so
  1354. * that the xHCI driver can recalculate the U1/U2 timeouts.
  1355. */
  1356. if (usb_disable_lpm(dev)) {
  1357. dev_err(&dev->dev, "%s Failed to disable LPM\n", __func__);
  1358. mutex_unlock(hcd->bandwidth_mutex);
  1359. return -ENOMEM;
  1360. }
  1361. /* Make sure we have enough bandwidth for each alternate setting 0 */
  1362. for (i = 0; i < config->desc.bNumInterfaces; i++) {
  1363. struct usb_interface *intf = config->interface[i];
  1364. struct usb_host_interface *alt;
  1365. alt = usb_altnum_to_altsetting(intf, 0);
  1366. if (!alt)
  1367. alt = &intf->altsetting[0];
  1368. if (alt != intf->cur_altsetting)
  1369. retval = usb_hcd_alloc_bandwidth(dev, NULL,
  1370. intf->cur_altsetting, alt);
  1371. if (retval < 0)
  1372. break;
  1373. }
  1374. /* If not, reinstate the old alternate settings */
  1375. if (retval < 0) {
  1376. reset_old_alts:
  1377. for (i--; i >= 0; i--) {
  1378. struct usb_interface *intf = config->interface[i];
  1379. struct usb_host_interface *alt;
  1380. alt = usb_altnum_to_altsetting(intf, 0);
  1381. if (!alt)
  1382. alt = &intf->altsetting[0];
  1383. if (alt != intf->cur_altsetting)
  1384. usb_hcd_alloc_bandwidth(dev, NULL,
  1385. alt, intf->cur_altsetting);
  1386. }
  1387. usb_enable_lpm(dev);
  1388. mutex_unlock(hcd->bandwidth_mutex);
  1389. return retval;
  1390. }
  1391. retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  1392. USB_REQ_SET_CONFIGURATION, 0,
  1393. config->desc.bConfigurationValue, 0,
  1394. NULL, 0, USB_CTRL_SET_TIMEOUT);
  1395. if (retval < 0)
  1396. goto reset_old_alts;
  1397. mutex_unlock(hcd->bandwidth_mutex);
  1398. /* re-init hc/hcd interface/endpoint state */
  1399. for (i = 0; i < config->desc.bNumInterfaces; i++) {
  1400. struct usb_interface *intf = config->interface[i];
  1401. struct usb_host_interface *alt;
  1402. alt = usb_altnum_to_altsetting(intf, 0);
  1403. /* No altsetting 0? We'll assume the first altsetting.
  1404. * We could use a GetInterface call, but if a device is
  1405. * so non-compliant that it doesn't have altsetting 0
  1406. * then I wouldn't trust its reply anyway.
  1407. */
  1408. if (!alt)
  1409. alt = &intf->altsetting[0];
  1410. if (alt != intf->cur_altsetting) {
  1411. remove_intf_ep_devs(intf);
  1412. usb_remove_sysfs_intf_files(intf);
  1413. }
  1414. intf->cur_altsetting = alt;
  1415. usb_enable_interface(dev, intf, true);
  1416. if (device_is_registered(&intf->dev)) {
  1417. usb_create_sysfs_intf_files(intf);
  1418. create_intf_ep_devs(intf);
  1419. }
  1420. }
  1421. /* Now that the interfaces are installed, re-enable LPM. */
  1422. usb_unlocked_enable_lpm(dev);
  1423. return 0;
  1424. }
  1425. EXPORT_SYMBOL_GPL(usb_reset_configuration);
  1426. static void usb_release_interface(struct device *dev)
  1427. {
  1428. struct usb_interface *intf = to_usb_interface(dev);
  1429. struct usb_interface_cache *intfc =
  1430. altsetting_to_usb_interface_cache(intf->altsetting);
  1431. kref_put(&intfc->ref, usb_release_interface_cache);
  1432. usb_put_dev(interface_to_usbdev(intf));
  1433. of_node_put(dev->of_node);
  1434. kfree(intf);
  1435. }
  1436. /*
  1437. * usb_deauthorize_interface - deauthorize an USB interface
  1438. *
  1439. * @intf: USB interface structure
  1440. */
  1441. void usb_deauthorize_interface(struct usb_interface *intf)
  1442. {
  1443. struct device *dev = &intf->dev;
  1444. device_lock(dev->parent);
  1445. if (intf->authorized) {
  1446. device_lock(dev);
  1447. intf->authorized = 0;
  1448. device_unlock(dev);
  1449. usb_forced_unbind_intf(intf);
  1450. }
  1451. device_unlock(dev->parent);
  1452. }
  1453. /*
  1454. * usb_authorize_interface - authorize an USB interface
  1455. *
  1456. * @intf: USB interface structure
  1457. */
  1458. void usb_authorize_interface(struct usb_interface *intf)
  1459. {
  1460. struct device *dev = &intf->dev;
  1461. if (!intf->authorized) {
  1462. device_lock(dev);
  1463. intf->authorized = 1; /* authorize interface */
  1464. device_unlock(dev);
  1465. }
  1466. }
  1467. static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env)
  1468. {
  1469. struct usb_device *usb_dev;
  1470. struct usb_interface *intf;
  1471. struct usb_host_interface *alt;
  1472. intf = to_usb_interface(dev);
  1473. usb_dev = interface_to_usbdev(intf);
  1474. alt = intf->cur_altsetting;
  1475. if (add_uevent_var(env, "INTERFACE=%d/%d/%d",
  1476. alt->desc.bInterfaceClass,
  1477. alt->desc.bInterfaceSubClass,
  1478. alt->desc.bInterfaceProtocol))
  1479. return -ENOMEM;
  1480. if (add_uevent_var(env,
  1481. "MODALIAS=usb:"
  1482. "v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02Xin%02X",
  1483. le16_to_cpu(usb_dev->descriptor.idVendor),
  1484. le16_to_cpu(usb_dev->descriptor.idProduct),
  1485. le16_to_cpu(usb_dev->descriptor.bcdDevice),
  1486. usb_dev->descriptor.bDeviceClass,
  1487. usb_dev->descriptor.bDeviceSubClass,
  1488. usb_dev->descriptor.bDeviceProtocol,
  1489. alt->desc.bInterfaceClass,
  1490. alt->desc.bInterfaceSubClass,
  1491. alt->desc.bInterfaceProtocol,
  1492. alt->desc.bInterfaceNumber))
  1493. return -ENOMEM;
  1494. return 0;
  1495. }
  1496. struct device_type usb_if_device_type = {
  1497. .name = "usb_interface",
  1498. .release = usb_release_interface,
  1499. .uevent = usb_if_uevent,
  1500. };
  1501. static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev,
  1502. struct usb_host_config *config,
  1503. u8 inum)
  1504. {
  1505. struct usb_interface_assoc_descriptor *retval = NULL;
  1506. struct usb_interface_assoc_descriptor *intf_assoc;
  1507. int first_intf;
  1508. int last_intf;
  1509. int i;
  1510. for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) {
  1511. intf_assoc = config->intf_assoc[i];
  1512. if (intf_assoc->bInterfaceCount == 0)
  1513. continue;
  1514. first_intf = intf_assoc->bFirstInterface;
  1515. last_intf = first_intf + (intf_assoc->bInterfaceCount - 1);
  1516. if (inum >= first_intf && inum <= last_intf) {
  1517. if (!retval)
  1518. retval = intf_assoc;
  1519. else
  1520. dev_err(&dev->dev, "Interface #%d referenced"
  1521. " by multiple IADs\n", inum);
  1522. }
  1523. }
  1524. return retval;
  1525. }
  1526. /*
  1527. * Internal function to queue a device reset
  1528. * See usb_queue_reset_device() for more details
  1529. */
  1530. static void __usb_queue_reset_device(struct work_struct *ws)
  1531. {
  1532. int rc;
  1533. struct usb_interface *iface =
  1534. container_of(ws, struct usb_interface, reset_ws);
  1535. struct usb_device *udev = interface_to_usbdev(iface);
  1536. rc = usb_lock_device_for_reset(udev, iface);
  1537. if (rc >= 0) {
  1538. usb_reset_device(udev);
  1539. usb_unlock_device(udev);
  1540. }
  1541. usb_put_intf(iface); /* Undo _get_ in usb_queue_reset_device() */
  1542. }
  1543. /*
  1544. * usb_set_configuration - Makes a particular device setting be current
  1545. * @dev: the device whose configuration is being updated
  1546. * @configuration: the configuration being chosen.
  1547. * Context: !in_interrupt(), caller owns the device lock
  1548. *
  1549. * This is used to enable non-default device modes. Not all devices
  1550. * use this kind of configurability; many devices only have one
  1551. * configuration.
  1552. *
  1553. * @configuration is the value of the configuration to be installed.
  1554. * According to the USB spec (e.g. section 9.1.1.5), configuration values
  1555. * must be non-zero; a value of zero indicates that the device in
  1556. * unconfigured. However some devices erroneously use 0 as one of their
  1557. * configuration values. To help manage such devices, this routine will
  1558. * accept @configuration = -1 as indicating the device should be put in
  1559. * an unconfigured state.
  1560. *
  1561. * USB device configurations may affect Linux interoperability,
  1562. * power consumption and the functionality available. For example,
  1563. * the default configuration is limited to using 100mA of bus power,
  1564. * so that when certain device functionality requires more power,
  1565. * and the device is bus powered, that functionality should be in some
  1566. * non-default device configuration. Other device modes may also be
  1567. * reflected as configuration options, such as whether two ISDN
  1568. * channels are available independently; and choosing between open
  1569. * standard device protocols (like CDC) or proprietary ones.
  1570. *
  1571. * Note that a non-authorized device (dev->authorized == 0) will only
  1572. * be put in unconfigured mode.
  1573. *
  1574. * Note that USB has an additional level of device configurability,
  1575. * associated with interfaces. That configurability is accessed using
  1576. * usb_set_interface().
  1577. *
  1578. * This call is synchronous. The calling context must be able to sleep,
  1579. * must own the device lock, and must not hold the driver model's USB
  1580. * bus mutex; usb interface driver probe() methods cannot use this routine.
  1581. *
  1582. * Returns zero on success, or else the status code returned by the
  1583. * underlying call that failed. On successful completion, each interface
  1584. * in the original device configuration has been destroyed, and each one
  1585. * in the new configuration has been probed by all relevant usb device
  1586. * drivers currently known to the kernel.
  1587. */
  1588. int usb_set_configuration(struct usb_device *dev, int configuration)
  1589. {
  1590. int i, ret;
  1591. struct usb_host_config *cp = NULL;
  1592. struct usb_interface **new_interfaces = NULL;
  1593. struct usb_hcd *hcd = bus_to_hcd(dev->bus);
  1594. int n, nintf;
  1595. if (dev->authorized == 0 || configuration == -1)
  1596. configuration = 0;
  1597. else {
  1598. for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
  1599. if (dev->config[i].desc.bConfigurationValue ==
  1600. configuration) {
  1601. cp = &dev->config[i];
  1602. break;
  1603. }
  1604. }
  1605. }
  1606. if ((!cp && configuration != 0))
  1607. return -EINVAL;
  1608. /* The USB spec says configuration 0 means unconfigured.
  1609. * But if a device includes a configuration numbered 0,
  1610. * we will accept it as a correctly configured state.
  1611. * Use -1 if you really want to unconfigure the device.
  1612. */
  1613. if (cp && configuration == 0)
  1614. dev_warn(&dev->dev, "config 0 descriptor??\n");
  1615. /* Allocate memory for new interfaces before doing anything else,
  1616. * so that if we run out then nothing will have changed. */
  1617. n = nintf = 0;
  1618. if (cp) {
  1619. nintf = cp->desc.bNumInterfaces;
  1620. new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
  1621. GFP_NOIO);
  1622. if (!new_interfaces)
  1623. return -ENOMEM;
  1624. for (; n < nintf; ++n) {
  1625. new_interfaces[n] = kzalloc(
  1626. sizeof(struct usb_interface),
  1627. GFP_NOIO);
  1628. if (!new_interfaces[n]) {
  1629. ret = -ENOMEM;
  1630. free_interfaces:
  1631. while (--n >= 0)
  1632. kfree(new_interfaces[n]);
  1633. kfree(new_interfaces);
  1634. return ret;
  1635. }
  1636. }
  1637. i = dev->bus_mA - usb_get_max_power(dev, cp);
  1638. if (i < 0)
  1639. dev_warn(&dev->dev, "new config #%d exceeds power "
  1640. "limit by %dmA\n",
  1641. configuration, -i);
  1642. }
  1643. /* Wake up the device so we can send it the Set-Config request */
  1644. ret = usb_autoresume_device(dev);
  1645. if (ret)
  1646. goto free_interfaces;
  1647. /* if it's already configured, clear out old state first.
  1648. * getting rid of old interfaces means unbinding their drivers.
  1649. */
  1650. if (dev->state != USB_STATE_ADDRESS)
  1651. usb_disable_device(dev, 1); /* Skip ep0 */
  1652. /* Get rid of pending async Set-Config requests for this device */
  1653. cancel_async_set_config(dev);
  1654. /* Make sure we have bandwidth (and available HCD resources) for this
  1655. * configuration. Remove endpoints from the schedule if we're dropping
  1656. * this configuration to set configuration 0. After this point, the
  1657. * host controller will not allow submissions to dropped endpoints. If
  1658. * this call fails, the device state is unchanged.
  1659. */
  1660. mutex_lock(hcd->bandwidth_mutex);
  1661. /* Disable LPM, and re-enable it once the new configuration is
  1662. * installed, so that the xHCI driver can recalculate the U1/U2
  1663. * timeouts.
  1664. */
  1665. if (dev->actconfig && usb_disable_lpm(dev)) {
  1666. dev_err(&dev->dev, "%s Failed to disable LPM\n", __func__);
  1667. mutex_unlock(hcd->bandwidth_mutex);
  1668. ret = -ENOMEM;
  1669. goto free_interfaces;
  1670. }
  1671. ret = usb_hcd_alloc_bandwidth(dev, cp, NULL, NULL);
  1672. if (ret < 0) {
  1673. if (dev->actconfig)
  1674. usb_enable_lpm(dev);
  1675. mutex_unlock(hcd->bandwidth_mutex);
  1676. usb_autosuspend_device(dev);
  1677. goto free_interfaces;
  1678. }
  1679. /*
  1680. * Initialize the new interface structures and the
  1681. * hc/hcd/usbcore interface/endpoint state.
  1682. */
  1683. for (i = 0; i < nintf; ++i) {
  1684. struct usb_interface_cache *intfc;
  1685. struct usb_interface *intf;
  1686. struct usb_host_interface *alt;
  1687. u8 ifnum;
  1688. cp->interface[i] = intf = new_interfaces[i];
  1689. intfc = cp->intf_cache[i];
  1690. intf->altsetting = intfc->altsetting;
  1691. intf->num_altsetting = intfc->num_altsetting;
  1692. intf->authorized = !!HCD_INTF_AUTHORIZED(hcd);
  1693. kref_get(&intfc->ref);
  1694. alt = usb_altnum_to_altsetting(intf, 0);
  1695. /* No altsetting 0? We'll assume the first altsetting.
  1696. * We could use a GetInterface call, but if a device is
  1697. * so non-compliant that it doesn't have altsetting 0
  1698. * then I wouldn't trust its reply anyway.
  1699. */
  1700. if (!alt)
  1701. alt = &intf->altsetting[0];
  1702. ifnum = alt->desc.bInterfaceNumber;
  1703. intf->intf_assoc = find_iad(dev, cp, ifnum);
  1704. intf->cur_altsetting = alt;
  1705. usb_enable_interface(dev, intf, true);
  1706. intf->dev.parent = &dev->dev;
  1707. if (usb_of_has_combined_node(dev)) {
  1708. device_set_of_node_from_dev(&intf->dev, &dev->dev);
  1709. } else {
  1710. intf->dev.of_node = usb_of_get_interface_node(dev,
  1711. configuration, ifnum);
  1712. }
  1713. intf->dev.driver = NULL;
  1714. intf->dev.bus = &usb_bus_type;
  1715. intf->dev.type = &usb_if_device_type;
  1716. intf->dev.groups = usb_interface_groups;
  1717. /*
  1718. * Please refer to usb_alloc_dev() to see why we set
  1719. * dma_mask and dma_pfn_offset.
  1720. */
  1721. intf->dev.dma_mask = dev->dev.dma_mask;
  1722. intf->dev.dma_pfn_offset = dev->dev.dma_pfn_offset;
  1723. INIT_WORK(&intf->reset_ws, __usb_queue_reset_device);
  1724. intf->minor = -1;
  1725. device_initialize(&intf->dev);
  1726. pm_runtime_no_callbacks(&intf->dev);
  1727. dev_set_name(&intf->dev, "%d-%s:%d.%d", dev->bus->busnum,
  1728. dev->devpath, configuration, ifnum);
  1729. usb_get_dev(dev);
  1730. }
  1731. kfree(new_interfaces);
  1732. ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  1733. USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
  1734. NULL, 0, USB_CTRL_SET_TIMEOUT);
  1735. if (ret < 0 && cp) {
  1736. /*
  1737. * All the old state is gone, so what else can we do?
  1738. * The device is probably useless now anyway.
  1739. */
  1740. usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
  1741. for (i = 0; i < nintf; ++i) {
  1742. usb_disable_interface(dev, cp->interface[i], true);
  1743. put_device(&cp->interface[i]->dev);
  1744. cp->interface[i] = NULL;
  1745. }
  1746. cp = NULL;
  1747. }
  1748. dev->actconfig = cp;
  1749. mutex_unlock(hcd->bandwidth_mutex);
  1750. if (!cp) {
  1751. usb_set_device_state(dev, USB_STATE_ADDRESS);
  1752. /* Leave LPM disabled while the device is unconfigured. */
  1753. usb_autosuspend_device(dev);
  1754. return ret;
  1755. }
  1756. usb_set_device_state(dev, USB_STATE_CONFIGURED);
  1757. if (cp->string == NULL &&
  1758. !(dev->quirks & USB_QUIRK_CONFIG_INTF_STRINGS))
  1759. cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
  1760. /* Now that the interfaces are installed, re-enable LPM. */
  1761. usb_unlocked_enable_lpm(dev);
  1762. /* Enable LTM if it was turned off by usb_disable_device. */
  1763. usb_enable_ltm(dev);
  1764. /* Now that all the interfaces are set up, register them
  1765. * to trigger binding of drivers to interfaces. probe()
  1766. * routines may install different altsettings and may
  1767. * claim() any interfaces not yet bound. Many class drivers
  1768. * need that: CDC, audio, video, etc.
  1769. */
  1770. for (i = 0; i < nintf; ++i) {
  1771. struct usb_interface *intf = cp->interface[i];
  1772. dev_dbg(&dev->dev,
  1773. "adding %s (config #%d, interface %d)\n",
  1774. dev_name(&intf->dev), configuration,
  1775. intf->cur_altsetting->desc.bInterfaceNumber);
  1776. device_enable_async_suspend(&intf->dev);
  1777. ret = device_add(&intf->dev);
  1778. if (ret != 0) {
  1779. dev_err(&dev->dev, "device_add(%s) --> %d\n",
  1780. dev_name(&intf->dev), ret);
  1781. continue;
  1782. }
  1783. create_intf_ep_devs(intf);
  1784. }
  1785. usb_autosuspend_device(dev);
  1786. return 0;
  1787. }
  1788. EXPORT_SYMBOL_GPL(usb_set_configuration);
  1789. static LIST_HEAD(set_config_list);
  1790. static DEFINE_SPINLOCK(set_config_lock);
  1791. struct set_config_request {
  1792. struct usb_device *udev;
  1793. int config;
  1794. struct work_struct work;
  1795. struct list_head node;
  1796. };
  1797. /* Worker routine for usb_driver_set_configuration() */
  1798. static void driver_set_config_work(struct work_struct *work)
  1799. {
  1800. struct set_config_request *req =
  1801. container_of(work, struct set_config_request, work);
  1802. struct usb_device *udev = req->udev;
  1803. usb_lock_device(udev);
  1804. spin_lock(&set_config_lock);
  1805. list_del(&req->node);
  1806. spin_unlock(&set_config_lock);
  1807. if (req->config >= -1) /* Is req still valid? */
  1808. usb_set_configuration(udev, req->config);
  1809. usb_unlock_device(udev);
  1810. usb_put_dev(udev);
  1811. kfree(req);
  1812. }
  1813. /* Cancel pending Set-Config requests for a device whose configuration
  1814. * was just changed
  1815. */
  1816. static void cancel_async_set_config(struct usb_device *udev)
  1817. {
  1818. struct set_config_request *req;
  1819. spin_lock(&set_config_lock);
  1820. list_for_each_entry(req, &set_config_list, node) {
  1821. if (req->udev == udev)
  1822. req->config = -999; /* Mark as cancelled */
  1823. }
  1824. spin_unlock(&set_config_lock);
  1825. }
  1826. /**
  1827. * usb_driver_set_configuration - Provide a way for drivers to change device configurations
  1828. * @udev: the device whose configuration is being updated
  1829. * @config: the configuration being chosen.
  1830. * Context: In process context, must be able to sleep
  1831. *
  1832. * Device interface drivers are not allowed to change device configurations.
  1833. * This is because changing configurations will destroy the interface the
  1834. * driver is bound to and create new ones; it would be like a floppy-disk
  1835. * driver telling the computer to replace the floppy-disk drive with a
  1836. * tape drive!
  1837. *
  1838. * Still, in certain specialized circumstances the need may arise. This
  1839. * routine gets around the normal restrictions by using a work thread to
  1840. * submit the change-config request.
  1841. *
  1842. * Return: 0 if the request was successfully queued, error code otherwise.
  1843. * The caller has no way to know whether the queued request will eventually
  1844. * succeed.
  1845. */
  1846. int usb_driver_set_configuration(struct usb_device *udev, int config)
  1847. {
  1848. struct set_config_request *req;
  1849. req = kmalloc(sizeof(*req), GFP_KERNEL);
  1850. if (!req)
  1851. return -ENOMEM;
  1852. req->udev = udev;
  1853. req->config = config;
  1854. INIT_WORK(&req->work, driver_set_config_work);
  1855. spin_lock(&set_config_lock);
  1856. list_add(&req->node, &set_config_list);
  1857. spin_unlock(&set_config_lock);
  1858. usb_get_dev(udev);
  1859. schedule_work(&req->work);
  1860. return 0;
  1861. }
  1862. EXPORT_SYMBOL_GPL(usb_driver_set_configuration);
  1863. /**
  1864. * cdc_parse_cdc_header - parse the extra headers present in CDC devices
  1865. * @hdr: the place to put the results of the parsing
  1866. * @intf: the interface for which parsing is requested
  1867. * @buffer: pointer to the extra headers to be parsed
  1868. * @buflen: length of the extra headers
  1869. *
  1870. * This evaluates the extra headers present in CDC devices which
  1871. * bind the interfaces for data and control and provide details
  1872. * about the capabilities of the device.
  1873. *
  1874. * Return: number of descriptors parsed or -EINVAL
  1875. * if the header is contradictory beyond salvage
  1876. */
  1877. int cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr,
  1878. struct usb_interface *intf,
  1879. u8 *buffer,
  1880. int buflen)
  1881. {
  1882. /* duplicates are ignored */
  1883. struct usb_cdc_union_desc *union_header = NULL;
  1884. /* duplicates are not tolerated */
  1885. struct usb_cdc_header_desc *header = NULL;
  1886. struct usb_cdc_ether_desc *ether = NULL;
  1887. struct usb_cdc_mdlm_detail_desc *detail = NULL;
  1888. struct usb_cdc_mdlm_desc *desc = NULL;
  1889. unsigned int elength;
  1890. int cnt = 0;
  1891. memset(hdr, 0x00, sizeof(struct usb_cdc_parsed_header));
  1892. hdr->phonet_magic_present = false;
  1893. while (buflen > 0) {
  1894. elength = buffer[0];
  1895. if (!elength) {
  1896. dev_err(&intf->dev, "skipping garbage byte\n");
  1897. elength = 1;
  1898. goto next_desc;
  1899. }
  1900. if ((buflen < elength) || (elength < 3)) {
  1901. dev_err(&intf->dev, "invalid descriptor buffer length\n");
  1902. break;
  1903. }
  1904. if (buffer[1] != USB_DT_CS_INTERFACE) {
  1905. dev_err(&intf->dev, "skipping garbage\n");
  1906. goto next_desc;
  1907. }
  1908. switch (buffer[2]) {
  1909. case USB_CDC_UNION_TYPE: /* we've found it */
  1910. if (elength < sizeof(struct usb_cdc_union_desc))
  1911. goto next_desc;
  1912. if (union_header) {
  1913. dev_err(&intf->dev, "More than one union descriptor, skipping ...\n");
  1914. goto next_desc;
  1915. }
  1916. union_header = (struct usb_cdc_union_desc *)buffer;
  1917. break;
  1918. case USB_CDC_COUNTRY_TYPE:
  1919. if (elength < sizeof(struct usb_cdc_country_functional_desc))
  1920. goto next_desc;
  1921. hdr->usb_cdc_country_functional_desc =
  1922. (struct usb_cdc_country_functional_desc *)buffer;
  1923. break;
  1924. case USB_CDC_HEADER_TYPE:
  1925. if (elength != sizeof(struct usb_cdc_header_desc))
  1926. goto next_desc;
  1927. if (header)
  1928. return -EINVAL;
  1929. header = (struct usb_cdc_header_desc *)buffer;
  1930. break;
  1931. case USB_CDC_ACM_TYPE:
  1932. if (elength < sizeof(struct usb_cdc_acm_descriptor))
  1933. goto next_desc;
  1934. hdr->usb_cdc_acm_descriptor =
  1935. (struct usb_cdc_acm_descriptor *)buffer;
  1936. break;
  1937. case USB_CDC_ETHERNET_TYPE:
  1938. if (elength != sizeof(struct usb_cdc_ether_desc))
  1939. goto next_desc;
  1940. if (ether)
  1941. return -EINVAL;
  1942. ether = (struct usb_cdc_ether_desc *)buffer;
  1943. break;
  1944. case USB_CDC_CALL_MANAGEMENT_TYPE:
  1945. if (elength < sizeof(struct usb_cdc_call_mgmt_descriptor))
  1946. goto next_desc;
  1947. hdr->usb_cdc_call_mgmt_descriptor =
  1948. (struct usb_cdc_call_mgmt_descriptor *)buffer;
  1949. break;
  1950. case USB_CDC_DMM_TYPE:
  1951. if (elength < sizeof(struct usb_cdc_dmm_desc))
  1952. goto next_desc;
  1953. hdr->usb_cdc_dmm_desc =
  1954. (struct usb_cdc_dmm_desc *)buffer;
  1955. break;
  1956. case USB_CDC_MDLM_TYPE:
  1957. if (elength < sizeof(struct usb_cdc_mdlm_desc *))
  1958. goto next_desc;
  1959. if (desc)
  1960. return -EINVAL;
  1961. desc = (struct usb_cdc_mdlm_desc *)buffer;
  1962. break;
  1963. case USB_CDC_MDLM_DETAIL_TYPE:
  1964. if (elength < sizeof(struct usb_cdc_mdlm_detail_desc *))
  1965. goto next_desc;
  1966. if (detail)
  1967. return -EINVAL;
  1968. detail = (struct usb_cdc_mdlm_detail_desc *)buffer;
  1969. break;
  1970. case USB_CDC_NCM_TYPE:
  1971. if (elength < sizeof(struct usb_cdc_ncm_desc))
  1972. goto next_desc;
  1973. hdr->usb_cdc_ncm_desc = (struct usb_cdc_ncm_desc *)buffer;
  1974. break;
  1975. case USB_CDC_MBIM_TYPE:
  1976. if (elength < sizeof(struct usb_cdc_mbim_desc))
  1977. goto next_desc;
  1978. hdr->usb_cdc_mbim_desc = (struct usb_cdc_mbim_desc *)buffer;
  1979. break;
  1980. case USB_CDC_MBIM_EXTENDED_TYPE:
  1981. if (elength < sizeof(struct usb_cdc_mbim_extended_desc))
  1982. break;
  1983. hdr->usb_cdc_mbim_extended_desc =
  1984. (struct usb_cdc_mbim_extended_desc *)buffer;
  1985. break;
  1986. case CDC_PHONET_MAGIC_NUMBER:
  1987. hdr->phonet_magic_present = true;
  1988. break;
  1989. default:
  1990. /*
  1991. * there are LOTS more CDC descriptors that
  1992. * could legitimately be found here.
  1993. */
  1994. dev_dbg(&intf->dev, "Ignoring descriptor: type %02x, length %ud\n",
  1995. buffer[2], elength);
  1996. goto next_desc;
  1997. }
  1998. cnt++;
  1999. next_desc:
  2000. buflen -= elength;
  2001. buffer += elength;
  2002. }
  2003. hdr->usb_cdc_union_desc = union_header;
  2004. hdr->usb_cdc_header_desc = header;
  2005. hdr->usb_cdc_mdlm_detail_desc = detail;
  2006. hdr->usb_cdc_mdlm_desc = desc;
  2007. hdr->usb_cdc_ether_desc = ether;
  2008. return cnt;
  2009. }
  2010. EXPORT_SYMBOL(cdc_parse_cdc_header);