message.c 67 KB

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