message.c 58 KB

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