message.c 59 KB

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