message.c 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465
  1. /*
  2. * message.c - synchronous message handling
  3. */
  4. #include <linux/config.h>
  5. #ifdef CONFIG_USB_DEBUG
  6. #define DEBUG
  7. #else
  8. #undef DEBUG
  9. #endif
  10. #include <linux/pci.h> /* for scatterlist macros */
  11. #include <linux/usb.h>
  12. #include <linux/module.h>
  13. #include <linux/slab.h>
  14. #include <linux/init.h>
  15. #include <linux/mm.h>
  16. #include <linux/timer.h>
  17. #include <linux/ctype.h>
  18. #include <linux/device.h>
  19. #include <asm/byteorder.h>
  20. #include "hcd.h" /* for usbcore internals */
  21. #include "usb.h"
  22. static void usb_api_blocking_completion(struct urb *urb, struct pt_regs *regs)
  23. {
  24. complete((struct completion *)urb->context);
  25. }
  26. static void timeout_kill(unsigned long data)
  27. {
  28. struct urb *urb = (struct urb *) data;
  29. usb_unlink_urb(urb);
  30. }
  31. // Starts urb and waits for completion or timeout
  32. // note that this call is NOT interruptible, while
  33. // many device driver i/o requests should be interruptible
  34. static int usb_start_wait_urb(struct urb *urb, int timeout, int* actual_length)
  35. {
  36. struct completion done;
  37. struct timer_list timer;
  38. int status;
  39. init_completion(&done);
  40. urb->context = &done;
  41. urb->actual_length = 0;
  42. status = usb_submit_urb(urb, GFP_NOIO);
  43. if (status == 0) {
  44. if (timeout > 0) {
  45. init_timer(&timer);
  46. timer.expires = jiffies + msecs_to_jiffies(timeout);
  47. timer.data = (unsigned long)urb;
  48. timer.function = timeout_kill;
  49. /* grr. timeout _should_ include submit delays. */
  50. add_timer(&timer);
  51. }
  52. wait_for_completion(&done);
  53. status = urb->status;
  54. /* note: HCDs return ETIMEDOUT for other reasons too */
  55. if (status == -ECONNRESET) {
  56. dev_dbg(&urb->dev->dev,
  57. "%s timed out on ep%d%s len=%d/%d\n",
  58. current->comm,
  59. usb_pipeendpoint(urb->pipe),
  60. usb_pipein(urb->pipe) ? "in" : "out",
  61. urb->actual_length,
  62. urb->transfer_buffer_length
  63. );
  64. if (urb->actual_length > 0)
  65. status = 0;
  66. else
  67. status = -ETIMEDOUT;
  68. }
  69. if (timeout > 0)
  70. del_timer_sync(&timer);
  71. }
  72. if (actual_length)
  73. *actual_length = urb->actual_length;
  74. usb_free_urb(urb);
  75. return status;
  76. }
  77. /*-------------------------------------------------------------------*/
  78. // returns status (negative) or length (positive)
  79. static int usb_internal_control_msg(struct usb_device *usb_dev,
  80. unsigned int pipe,
  81. struct usb_ctrlrequest *cmd,
  82. void *data, int len, int timeout)
  83. {
  84. struct urb *urb;
  85. int retv;
  86. int length;
  87. urb = usb_alloc_urb(0, GFP_NOIO);
  88. if (!urb)
  89. return -ENOMEM;
  90. usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
  91. len, usb_api_blocking_completion, NULL);
  92. retv = usb_start_wait_urb(urb, timeout, &length);
  93. if (retv < 0)
  94. return retv;
  95. else
  96. return length;
  97. }
  98. /**
  99. * usb_control_msg - Builds a control urb, sends it off and waits for completion
  100. * @dev: pointer to the usb device to send the message to
  101. * @pipe: endpoint "pipe" to send the message to
  102. * @request: USB message request value
  103. * @requesttype: USB message request type value
  104. * @value: USB message value
  105. * @index: USB message index value
  106. * @data: pointer to the data to send
  107. * @size: length in bytes of the data to send
  108. * @timeout: time in msecs to wait for the message to complete before
  109. * timing out (if 0 the wait is forever)
  110. * Context: !in_interrupt ()
  111. *
  112. * This function sends a simple control message to a specified endpoint
  113. * and waits for the message to complete, or timeout.
  114. *
  115. * If successful, it returns the number of bytes transferred, otherwise a negative error number.
  116. *
  117. * Don't use this function from within an interrupt context, like a
  118. * bottom half handler. If you need an asynchronous message, or need to send
  119. * a message from within interrupt context, use usb_submit_urb()
  120. * If a thread in your driver uses this call, make sure your disconnect()
  121. * method can wait for it to complete. Since you don't have a handle on
  122. * the URB used, you can't cancel the request.
  123. */
  124. int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype,
  125. __u16 value, __u16 index, void *data, __u16 size, int timeout)
  126. {
  127. struct usb_ctrlrequest *dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
  128. int ret;
  129. if (!dr)
  130. return -ENOMEM;
  131. dr->bRequestType= requesttype;
  132. dr->bRequest = request;
  133. dr->wValue = cpu_to_le16p(&value);
  134. dr->wIndex = cpu_to_le16p(&index);
  135. dr->wLength = cpu_to_le16p(&size);
  136. //dbg("usb_control_msg");
  137. ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
  138. kfree(dr);
  139. return ret;
  140. }
  141. /**
  142. * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
  143. * @usb_dev: pointer to the usb device to send the message to
  144. * @pipe: endpoint "pipe" to send the message to
  145. * @data: pointer to the data to send
  146. * @len: length in bytes of the data to send
  147. * @actual_length: pointer to a location to put the actual length transferred in bytes
  148. * @timeout: time in msecs to wait for the message to complete before
  149. * timing out (if 0 the wait is forever)
  150. * Context: !in_interrupt ()
  151. *
  152. * This function sends a simple bulk message to a specified endpoint
  153. * and waits for the message to complete, or timeout.
  154. *
  155. * If successful, it returns 0, otherwise a negative error number.
  156. * The number of actual bytes transferred will be stored in the
  157. * actual_length paramater.
  158. *
  159. * Don't use this function from within an interrupt context, like a
  160. * bottom half handler. If you need an asynchronous message, or need to
  161. * send a message from within interrupt context, use usb_submit_urb()
  162. * If a thread in your driver uses this call, make sure your disconnect()
  163. * method can wait for it to complete. Since you don't have a handle on
  164. * the URB used, you can't cancel the request.
  165. */
  166. int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
  167. void *data, int len, int *actual_length, int timeout)
  168. {
  169. struct urb *urb;
  170. if (len < 0)
  171. return -EINVAL;
  172. urb=usb_alloc_urb(0, GFP_KERNEL);
  173. if (!urb)
  174. return -ENOMEM;
  175. usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
  176. usb_api_blocking_completion, NULL);
  177. return usb_start_wait_urb(urb, timeout, actual_length);
  178. }
  179. /*-------------------------------------------------------------------*/
  180. static void sg_clean (struct usb_sg_request *io)
  181. {
  182. if (io->urbs) {
  183. while (io->entries--)
  184. usb_free_urb (io->urbs [io->entries]);
  185. kfree (io->urbs);
  186. io->urbs = NULL;
  187. }
  188. if (io->dev->dev.dma_mask != NULL)
  189. usb_buffer_unmap_sg (io->dev, io->pipe, io->sg, io->nents);
  190. io->dev = NULL;
  191. }
  192. static void sg_complete (struct urb *urb, struct pt_regs *regs)
  193. {
  194. struct usb_sg_request *io = (struct usb_sg_request *) urb->context;
  195. spin_lock (&io->lock);
  196. /* In 2.5 we require hcds' endpoint queues not to progress after fault
  197. * reports, until the completion callback (this!) returns. That lets
  198. * device driver code (like this routine) unlink queued urbs first,
  199. * if it needs to, since the HC won't work on them at all. So it's
  200. * not possible for page N+1 to overwrite page N, and so on.
  201. *
  202. * That's only for "hard" faults; "soft" faults (unlinks) sometimes
  203. * complete before the HCD can get requests away from hardware,
  204. * though never during cleanup after a hard fault.
  205. */
  206. if (io->status
  207. && (io->status != -ECONNRESET
  208. || urb->status != -ECONNRESET)
  209. && urb->actual_length) {
  210. dev_err (io->dev->bus->controller,
  211. "dev %s ep%d%s scatterlist error %d/%d\n",
  212. io->dev->devpath,
  213. usb_pipeendpoint (urb->pipe),
  214. usb_pipein (urb->pipe) ? "in" : "out",
  215. urb->status, io->status);
  216. // BUG ();
  217. }
  218. if (io->status == 0 && urb->status && urb->status != -ECONNRESET) {
  219. int i, found, status;
  220. io->status = urb->status;
  221. /* the previous urbs, and this one, completed already.
  222. * unlink pending urbs so they won't rx/tx bad data.
  223. * careful: unlink can sometimes be synchronous...
  224. */
  225. spin_unlock (&io->lock);
  226. for (i = 0, found = 0; i < io->entries; i++) {
  227. if (!io->urbs [i] || !io->urbs [i]->dev)
  228. continue;
  229. if (found) {
  230. status = usb_unlink_urb (io->urbs [i]);
  231. if (status != -EINPROGRESS
  232. && status != -ENODEV
  233. && status != -EBUSY)
  234. dev_err (&io->dev->dev,
  235. "%s, unlink --> %d\n",
  236. __FUNCTION__, status);
  237. } else if (urb == io->urbs [i])
  238. found = 1;
  239. }
  240. spin_lock (&io->lock);
  241. }
  242. urb->dev = NULL;
  243. /* on the last completion, signal usb_sg_wait() */
  244. io->bytes += urb->actual_length;
  245. io->count--;
  246. if (!io->count)
  247. complete (&io->complete);
  248. spin_unlock (&io->lock);
  249. }
  250. /**
  251. * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
  252. * @io: request block being initialized. until usb_sg_wait() returns,
  253. * treat this as a pointer to an opaque block of memory,
  254. * @dev: the usb device that will send or receive the data
  255. * @pipe: endpoint "pipe" used to transfer the data
  256. * @period: polling rate for interrupt endpoints, in frames or
  257. * (for high speed endpoints) microframes; ignored for bulk
  258. * @sg: scatterlist entries
  259. * @nents: how many entries in the scatterlist
  260. * @length: how many bytes to send from the scatterlist, or zero to
  261. * send every byte identified in the list.
  262. * @mem_flags: SLAB_* flags affecting memory allocations in this call
  263. *
  264. * Returns zero for success, else a negative errno value. This initializes a
  265. * scatter/gather request, allocating resources such as I/O mappings and urb
  266. * memory (except maybe memory used by USB controller drivers).
  267. *
  268. * The request must be issued using usb_sg_wait(), which waits for the I/O to
  269. * complete (or to be canceled) and then cleans up all resources allocated by
  270. * usb_sg_init().
  271. *
  272. * The request may be canceled with usb_sg_cancel(), either before or after
  273. * usb_sg_wait() is called.
  274. */
  275. int usb_sg_init (
  276. struct usb_sg_request *io,
  277. struct usb_device *dev,
  278. unsigned pipe,
  279. unsigned period,
  280. struct scatterlist *sg,
  281. int nents,
  282. size_t length,
  283. unsigned mem_flags
  284. )
  285. {
  286. int i;
  287. int urb_flags;
  288. int dma;
  289. if (!io || !dev || !sg
  290. || usb_pipecontrol (pipe)
  291. || usb_pipeisoc (pipe)
  292. || nents <= 0)
  293. return -EINVAL;
  294. spin_lock_init (&io->lock);
  295. io->dev = dev;
  296. io->pipe = pipe;
  297. io->sg = sg;
  298. io->nents = nents;
  299. /* not all host controllers use DMA (like the mainstream pci ones);
  300. * they can use PIO (sl811) or be software over another transport.
  301. */
  302. dma = (dev->dev.dma_mask != NULL);
  303. if (dma)
  304. io->entries = usb_buffer_map_sg (dev, pipe, sg, nents);
  305. else
  306. io->entries = nents;
  307. /* initialize all the urbs we'll use */
  308. if (io->entries <= 0)
  309. return io->entries;
  310. io->count = io->entries;
  311. io->urbs = kmalloc (io->entries * sizeof *io->urbs, mem_flags);
  312. if (!io->urbs)
  313. goto nomem;
  314. urb_flags = URB_NO_TRANSFER_DMA_MAP | URB_NO_INTERRUPT;
  315. if (usb_pipein (pipe))
  316. urb_flags |= URB_SHORT_NOT_OK;
  317. for (i = 0; i < io->entries; i++) {
  318. unsigned len;
  319. io->urbs [i] = usb_alloc_urb (0, mem_flags);
  320. if (!io->urbs [i]) {
  321. io->entries = i;
  322. goto nomem;
  323. }
  324. io->urbs [i]->dev = NULL;
  325. io->urbs [i]->pipe = pipe;
  326. io->urbs [i]->interval = period;
  327. io->urbs [i]->transfer_flags = urb_flags;
  328. io->urbs [i]->complete = sg_complete;
  329. io->urbs [i]->context = io;
  330. io->urbs [i]->status = -EINPROGRESS;
  331. io->urbs [i]->actual_length = 0;
  332. if (dma) {
  333. /* hc may use _only_ transfer_dma */
  334. io->urbs [i]->transfer_dma = sg_dma_address (sg + i);
  335. len = sg_dma_len (sg + i);
  336. } else {
  337. /* hc may use _only_ transfer_buffer */
  338. io->urbs [i]->transfer_buffer =
  339. page_address (sg [i].page) + sg [i].offset;
  340. len = sg [i].length;
  341. }
  342. if (length) {
  343. len = min_t (unsigned, len, length);
  344. length -= len;
  345. if (length == 0)
  346. io->entries = i + 1;
  347. }
  348. io->urbs [i]->transfer_buffer_length = len;
  349. }
  350. io->urbs [--i]->transfer_flags &= ~URB_NO_INTERRUPT;
  351. /* transaction state */
  352. io->status = 0;
  353. io->bytes = 0;
  354. init_completion (&io->complete);
  355. return 0;
  356. nomem:
  357. sg_clean (io);
  358. return -ENOMEM;
  359. }
  360. /**
  361. * usb_sg_wait - synchronously execute scatter/gather request
  362. * @io: request block handle, as initialized with usb_sg_init().
  363. * some fields become accessible when this call returns.
  364. * Context: !in_interrupt ()
  365. *
  366. * This function blocks until the specified I/O operation completes. It
  367. * leverages the grouping of the related I/O requests to get good transfer
  368. * rates, by queueing the requests. At higher speeds, such queuing can
  369. * significantly improve USB throughput.
  370. *
  371. * There are three kinds of completion for this function.
  372. * (1) success, where io->status is zero. The number of io->bytes
  373. * transferred is as requested.
  374. * (2) error, where io->status is a negative errno value. The number
  375. * of io->bytes transferred before the error is usually less
  376. * than requested, and can be nonzero.
  377. * (3) cancellation, a type of error with status -ECONNRESET that
  378. * is initiated by usb_sg_cancel().
  379. *
  380. * When this function returns, all memory allocated through usb_sg_init() or
  381. * this call will have been freed. The request block parameter may still be
  382. * passed to usb_sg_cancel(), or it may be freed. It could also be
  383. * reinitialized and then reused.
  384. *
  385. * Data Transfer Rates:
  386. *
  387. * Bulk transfers are valid for full or high speed endpoints.
  388. * The best full speed data rate is 19 packets of 64 bytes each
  389. * per frame, or 1216 bytes per millisecond.
  390. * The best high speed data rate is 13 packets of 512 bytes each
  391. * per microframe, or 52 KBytes per millisecond.
  392. *
  393. * The reason to use interrupt transfers through this API would most likely
  394. * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
  395. * could be transferred. That capability is less useful for low or full
  396. * speed interrupt endpoints, which allow at most one packet per millisecond,
  397. * of at most 8 or 64 bytes (respectively).
  398. */
  399. void usb_sg_wait (struct usb_sg_request *io)
  400. {
  401. int i, entries = io->entries;
  402. /* queue the urbs. */
  403. spin_lock_irq (&io->lock);
  404. for (i = 0; i < entries && !io->status; i++) {
  405. int retval;
  406. io->urbs [i]->dev = io->dev;
  407. retval = usb_submit_urb (io->urbs [i], SLAB_ATOMIC);
  408. /* after we submit, let completions or cancelations fire;
  409. * we handshake using io->status.
  410. */
  411. spin_unlock_irq (&io->lock);
  412. switch (retval) {
  413. /* maybe we retrying will recover */
  414. case -ENXIO: // hc didn't queue this one
  415. case -EAGAIN:
  416. case -ENOMEM:
  417. io->urbs[i]->dev = NULL;
  418. retval = 0;
  419. i--;
  420. yield ();
  421. break;
  422. /* no error? continue immediately.
  423. *
  424. * NOTE: to work better with UHCI (4K I/O buffer may
  425. * need 3K of TDs) it may be good to limit how many
  426. * URBs are queued at once; N milliseconds?
  427. */
  428. case 0:
  429. cpu_relax ();
  430. break;
  431. /* fail any uncompleted urbs */
  432. default:
  433. io->urbs [i]->dev = NULL;
  434. io->urbs [i]->status = retval;
  435. dev_dbg (&io->dev->dev, "%s, submit --> %d\n",
  436. __FUNCTION__, retval);
  437. usb_sg_cancel (io);
  438. }
  439. spin_lock_irq (&io->lock);
  440. if (retval && (io->status == 0 || io->status == -ECONNRESET))
  441. io->status = retval;
  442. }
  443. io->count -= entries - i;
  444. if (io->count == 0)
  445. complete (&io->complete);
  446. spin_unlock_irq (&io->lock);
  447. /* OK, yes, this could be packaged as non-blocking.
  448. * So could the submit loop above ... but it's easier to
  449. * solve neither problem than to solve both!
  450. */
  451. wait_for_completion (&io->complete);
  452. sg_clean (io);
  453. }
  454. /**
  455. * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
  456. * @io: request block, initialized with usb_sg_init()
  457. *
  458. * This stops a request after it has been started by usb_sg_wait().
  459. * It can also prevents one initialized by usb_sg_init() from starting,
  460. * so that call just frees resources allocated to the request.
  461. */
  462. void usb_sg_cancel (struct usb_sg_request *io)
  463. {
  464. unsigned long flags;
  465. spin_lock_irqsave (&io->lock, flags);
  466. /* shut everything down, if it didn't already */
  467. if (!io->status) {
  468. int i;
  469. io->status = -ECONNRESET;
  470. spin_unlock (&io->lock);
  471. for (i = 0; i < io->entries; i++) {
  472. int retval;
  473. if (!io->urbs [i]->dev)
  474. continue;
  475. retval = usb_unlink_urb (io->urbs [i]);
  476. if (retval != -EINPROGRESS && retval != -EBUSY)
  477. dev_warn (&io->dev->dev, "%s, unlink --> %d\n",
  478. __FUNCTION__, retval);
  479. }
  480. spin_lock (&io->lock);
  481. }
  482. spin_unlock_irqrestore (&io->lock, flags);
  483. }
  484. /*-------------------------------------------------------------------*/
  485. /**
  486. * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
  487. * @dev: the device whose descriptor is being retrieved
  488. * @type: the descriptor type (USB_DT_*)
  489. * @index: the number of the descriptor
  490. * @buf: where to put the descriptor
  491. * @size: how big is "buf"?
  492. * Context: !in_interrupt ()
  493. *
  494. * Gets a USB descriptor. Convenience functions exist to simplify
  495. * getting some types of descriptors. Use
  496. * usb_get_string() or usb_string() for USB_DT_STRING.
  497. * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
  498. * are part of the device structure.
  499. * In addition to a number of USB-standard descriptors, some
  500. * devices also use class-specific or vendor-specific descriptors.
  501. *
  502. * This call is synchronous, and may not be used in an interrupt context.
  503. *
  504. * Returns the number of bytes received on success, or else the status code
  505. * returned by the underlying usb_control_msg() call.
  506. */
  507. int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
  508. {
  509. int i;
  510. int result;
  511. memset(buf,0,size); // Make sure we parse really received data
  512. for (i = 0; i < 3; ++i) {
  513. /* retry on length 0 or stall; some devices are flakey */
  514. result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  515. USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
  516. (type << 8) + index, 0, buf, size,
  517. USB_CTRL_GET_TIMEOUT);
  518. if (result == 0 || result == -EPIPE)
  519. continue;
  520. if (result > 1 && ((u8 *)buf)[1] != type) {
  521. result = -EPROTO;
  522. continue;
  523. }
  524. break;
  525. }
  526. return result;
  527. }
  528. /**
  529. * usb_get_string - gets a string descriptor
  530. * @dev: the device whose string descriptor is being retrieved
  531. * @langid: code for language chosen (from string descriptor zero)
  532. * @index: the number of the descriptor
  533. * @buf: where to put the string
  534. * @size: how big is "buf"?
  535. * Context: !in_interrupt ()
  536. *
  537. * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
  538. * in little-endian byte order).
  539. * The usb_string() function will often be a convenient way to turn
  540. * these strings into kernel-printable form.
  541. *
  542. * Strings may be referenced in device, configuration, interface, or other
  543. * descriptors, and could also be used in vendor-specific ways.
  544. *
  545. * This call is synchronous, and may not be used in an interrupt context.
  546. *
  547. * Returns the number of bytes received on success, or else the status code
  548. * returned by the underlying usb_control_msg() call.
  549. */
  550. int usb_get_string(struct usb_device *dev, unsigned short langid,
  551. unsigned char index, void *buf, int size)
  552. {
  553. int i;
  554. int result;
  555. for (i = 0; i < 3; ++i) {
  556. /* retry on length 0 or stall; some devices are flakey */
  557. result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  558. USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
  559. (USB_DT_STRING << 8) + index, langid, buf, size,
  560. USB_CTRL_GET_TIMEOUT);
  561. if (!(result == 0 || result == -EPIPE))
  562. break;
  563. }
  564. return result;
  565. }
  566. static void usb_try_string_workarounds(unsigned char *buf, int *length)
  567. {
  568. int newlength, oldlength = *length;
  569. for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
  570. if (!isprint(buf[newlength]) || buf[newlength + 1])
  571. break;
  572. if (newlength > 2) {
  573. buf[0] = newlength;
  574. *length = newlength;
  575. }
  576. }
  577. static int usb_string_sub(struct usb_device *dev, unsigned int langid,
  578. unsigned int index, unsigned char *buf)
  579. {
  580. int rc;
  581. /* Try to read the string descriptor by asking for the maximum
  582. * possible number of bytes */
  583. rc = usb_get_string(dev, langid, index, buf, 255);
  584. /* If that failed try to read the descriptor length, then
  585. * ask for just that many bytes */
  586. if (rc < 2) {
  587. rc = usb_get_string(dev, langid, index, buf, 2);
  588. if (rc == 2)
  589. rc = usb_get_string(dev, langid, index, buf, buf[0]);
  590. }
  591. if (rc >= 2) {
  592. if (!buf[0] && !buf[1])
  593. usb_try_string_workarounds(buf, &rc);
  594. /* There might be extra junk at the end of the descriptor */
  595. if (buf[0] < rc)
  596. rc = buf[0];
  597. rc = rc - (rc & 1); /* force a multiple of two */
  598. }
  599. if (rc < 2)
  600. rc = (rc < 0 ? rc : -EINVAL);
  601. return rc;
  602. }
  603. /**
  604. * usb_string - returns ISO 8859-1 version of a string descriptor
  605. * @dev: the device whose string descriptor is being retrieved
  606. * @index: the number of the descriptor
  607. * @buf: where to put the string
  608. * @size: how big is "buf"?
  609. * Context: !in_interrupt ()
  610. *
  611. * This converts the UTF-16LE encoded strings returned by devices, from
  612. * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
  613. * that are more usable in most kernel contexts. Note that all characters
  614. * in the chosen descriptor that can't be encoded using ISO-8859-1
  615. * are converted to the question mark ("?") character, and this function
  616. * chooses strings in the first language supported by the device.
  617. *
  618. * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
  619. * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
  620. * and is appropriate for use many uses of English and several other
  621. * Western European languages. (But it doesn't include the "Euro" symbol.)
  622. *
  623. * This call is synchronous, and may not be used in an interrupt context.
  624. *
  625. * Returns length of the string (>= 0) or usb_control_msg status (< 0).
  626. */
  627. int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
  628. {
  629. unsigned char *tbuf;
  630. int err;
  631. unsigned int u, idx;
  632. if (dev->state == USB_STATE_SUSPENDED)
  633. return -EHOSTUNREACH;
  634. if (size <= 0 || !buf || !index)
  635. return -EINVAL;
  636. buf[0] = 0;
  637. tbuf = kmalloc(256, GFP_KERNEL);
  638. if (!tbuf)
  639. return -ENOMEM;
  640. /* get langid for strings if it's not yet known */
  641. if (!dev->have_langid) {
  642. err = usb_string_sub(dev, 0, 0, tbuf);
  643. if (err < 0) {
  644. dev_err (&dev->dev,
  645. "string descriptor 0 read error: %d\n",
  646. err);
  647. goto errout;
  648. } else if (err < 4) {
  649. dev_err (&dev->dev, "string descriptor 0 too short\n");
  650. err = -EINVAL;
  651. goto errout;
  652. } else {
  653. dev->have_langid = -1;
  654. dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
  655. /* always use the first langid listed */
  656. dev_dbg (&dev->dev, "default language 0x%04x\n",
  657. dev->string_langid);
  658. }
  659. }
  660. err = usb_string_sub(dev, dev->string_langid, index, tbuf);
  661. if (err < 0)
  662. goto errout;
  663. size--; /* leave room for trailing NULL char in output buffer */
  664. for (idx = 0, u = 2; u < err; u += 2) {
  665. if (idx >= size)
  666. break;
  667. if (tbuf[u+1]) /* high byte */
  668. buf[idx++] = '?'; /* non ISO-8859-1 character */
  669. else
  670. buf[idx++] = tbuf[u];
  671. }
  672. buf[idx] = 0;
  673. err = idx;
  674. if (tbuf[1] != USB_DT_STRING)
  675. dev_dbg(&dev->dev, "wrong descriptor type %02x for string %d (\"%s\")\n", tbuf[1], index, buf);
  676. errout:
  677. kfree(tbuf);
  678. return err;
  679. }
  680. /*
  681. * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
  682. * @dev: the device whose device descriptor is being updated
  683. * @size: how much of the descriptor to read
  684. * Context: !in_interrupt ()
  685. *
  686. * Updates the copy of the device descriptor stored in the device structure,
  687. * which dedicates space for this purpose. Note that several fields are
  688. * converted to the host CPU's byte order: the USB version (bcdUSB), and
  689. * vendors product and version fields (idVendor, idProduct, and bcdDevice).
  690. * That lets device drivers compare against non-byteswapped constants.
  691. *
  692. * Not exported, only for use by the core. If drivers really want to read
  693. * the device descriptor directly, they can call usb_get_descriptor() with
  694. * type = USB_DT_DEVICE and index = 0.
  695. *
  696. * This call is synchronous, and may not be used in an interrupt context.
  697. *
  698. * Returns the number of bytes received on success, or else the status code
  699. * returned by the underlying usb_control_msg() call.
  700. */
  701. int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
  702. {
  703. struct usb_device_descriptor *desc;
  704. int ret;
  705. if (size > sizeof(*desc))
  706. return -EINVAL;
  707. desc = kmalloc(sizeof(*desc), GFP_NOIO);
  708. if (!desc)
  709. return -ENOMEM;
  710. ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
  711. if (ret >= 0)
  712. memcpy(&dev->descriptor, desc, size);
  713. kfree(desc);
  714. return ret;
  715. }
  716. /**
  717. * usb_get_status - issues a GET_STATUS call
  718. * @dev: the device whose status is being checked
  719. * @type: USB_RECIP_*; for device, interface, or endpoint
  720. * @target: zero (for device), else interface or endpoint number
  721. * @data: pointer to two bytes of bitmap data
  722. * Context: !in_interrupt ()
  723. *
  724. * Returns device, interface, or endpoint status. Normally only of
  725. * interest to see if the device is self powered, or has enabled the
  726. * remote wakeup facility; or whether a bulk or interrupt endpoint
  727. * is halted ("stalled").
  728. *
  729. * Bits in these status bitmaps are set using the SET_FEATURE request,
  730. * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
  731. * function should be used to clear halt ("stall") status.
  732. *
  733. * This call is synchronous, and may not be used in an interrupt context.
  734. *
  735. * Returns the number of bytes received on success, or else the status code
  736. * returned by the underlying usb_control_msg() call.
  737. */
  738. int usb_get_status(struct usb_device *dev, int type, int target, void *data)
  739. {
  740. int ret;
  741. u16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
  742. if (!status)
  743. return -ENOMEM;
  744. ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  745. USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
  746. sizeof(*status), USB_CTRL_GET_TIMEOUT);
  747. *(u16 *)data = *status;
  748. kfree(status);
  749. return ret;
  750. }
  751. /**
  752. * usb_clear_halt - tells device to clear endpoint halt/stall condition
  753. * @dev: device whose endpoint is halted
  754. * @pipe: endpoint "pipe" being cleared
  755. * Context: !in_interrupt ()
  756. *
  757. * This is used to clear halt conditions for bulk and interrupt endpoints,
  758. * as reported by URB completion status. Endpoints that are halted are
  759. * sometimes referred to as being "stalled". Such endpoints are unable
  760. * to transmit or receive data until the halt status is cleared. Any URBs
  761. * queued for such an endpoint should normally be unlinked by the driver
  762. * before clearing the halt condition, as described in sections 5.7.5
  763. * and 5.8.5 of the USB 2.0 spec.
  764. *
  765. * Note that control and isochronous endpoints don't halt, although control
  766. * endpoints report "protocol stall" (for unsupported requests) using the
  767. * same status code used to report a true stall.
  768. *
  769. * This call is synchronous, and may not be used in an interrupt context.
  770. *
  771. * Returns zero on success, or else the status code returned by the
  772. * underlying usb_control_msg() call.
  773. */
  774. int usb_clear_halt(struct usb_device *dev, int pipe)
  775. {
  776. int result;
  777. int endp = usb_pipeendpoint(pipe);
  778. if (usb_pipein (pipe))
  779. endp |= USB_DIR_IN;
  780. /* we don't care if it wasn't halted first. in fact some devices
  781. * (like some ibmcam model 1 units) seem to expect hosts to make
  782. * this request for iso endpoints, which can't halt!
  783. */
  784. result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  785. USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
  786. USB_ENDPOINT_HALT, endp, NULL, 0,
  787. USB_CTRL_SET_TIMEOUT);
  788. /* don't un-halt or force to DATA0 except on success */
  789. if (result < 0)
  790. return result;
  791. /* NOTE: seems like Microsoft and Apple don't bother verifying
  792. * the clear "took", so some devices could lock up if you check...
  793. * such as the Hagiwara FlashGate DUAL. So we won't bother.
  794. *
  795. * NOTE: make sure the logic here doesn't diverge much from
  796. * the copy in usb-storage, for as long as we need two copies.
  797. */
  798. /* toggle was reset by the clear */
  799. usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
  800. return 0;
  801. }
  802. /**
  803. * usb_disable_endpoint -- Disable an endpoint by address
  804. * @dev: the device whose endpoint is being disabled
  805. * @epaddr: the endpoint's address. Endpoint number for output,
  806. * endpoint number + USB_DIR_IN for input
  807. *
  808. * Deallocates hcd/hardware state for this endpoint ... and nukes all
  809. * pending urbs.
  810. *
  811. * If the HCD hasn't registered a disable() function, this sets the
  812. * endpoint's maxpacket size to 0 to prevent further submissions.
  813. */
  814. void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr)
  815. {
  816. unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
  817. struct usb_host_endpoint *ep;
  818. if (!dev)
  819. return;
  820. if (usb_endpoint_out(epaddr)) {
  821. ep = dev->ep_out[epnum];
  822. dev->ep_out[epnum] = NULL;
  823. } else {
  824. ep = dev->ep_in[epnum];
  825. dev->ep_in[epnum] = NULL;
  826. }
  827. if (ep && dev->bus && dev->bus->op && dev->bus->op->disable)
  828. dev->bus->op->disable(dev, ep);
  829. }
  830. /**
  831. * usb_disable_interface -- Disable all endpoints for an interface
  832. * @dev: the device whose interface is being disabled
  833. * @intf: pointer to the interface descriptor
  834. *
  835. * Disables all the endpoints for the interface's current altsetting.
  836. */
  837. void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf)
  838. {
  839. struct usb_host_interface *alt = intf->cur_altsetting;
  840. int i;
  841. for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
  842. usb_disable_endpoint(dev,
  843. alt->endpoint[i].desc.bEndpointAddress);
  844. }
  845. }
  846. /*
  847. * usb_disable_device - Disable all the endpoints for a USB device
  848. * @dev: the device whose endpoints are being disabled
  849. * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
  850. *
  851. * Disables all the device's endpoints, potentially including endpoint 0.
  852. * Deallocates hcd/hardware state for the endpoints (nuking all or most
  853. * pending urbs) and usbcore state for the interfaces, so that usbcore
  854. * must usb_set_configuration() before any interfaces could be used.
  855. */
  856. void usb_disable_device(struct usb_device *dev, int skip_ep0)
  857. {
  858. int i;
  859. dev_dbg(&dev->dev, "%s nuking %s URBs\n", __FUNCTION__,
  860. skip_ep0 ? "non-ep0" : "all");
  861. for (i = skip_ep0; i < 16; ++i) {
  862. usb_disable_endpoint(dev, i);
  863. usb_disable_endpoint(dev, i + USB_DIR_IN);
  864. }
  865. dev->toggle[0] = dev->toggle[1] = 0;
  866. /* getting rid of interfaces will disconnect
  867. * any drivers bound to them (a key side effect)
  868. */
  869. if (dev->actconfig) {
  870. for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
  871. struct usb_interface *interface;
  872. /* remove this interface if it has been registered */
  873. interface = dev->actconfig->interface[i];
  874. if (!klist_node_attached(&interface->dev.knode_bus))
  875. continue;
  876. dev_dbg (&dev->dev, "unregistering interface %s\n",
  877. interface->dev.bus_id);
  878. usb_remove_sysfs_intf_files(interface);
  879. kfree(interface->cur_altsetting->string);
  880. interface->cur_altsetting->string = NULL;
  881. device_del (&interface->dev);
  882. }
  883. /* Now that the interfaces are unbound, nobody should
  884. * try to access them.
  885. */
  886. for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
  887. put_device (&dev->actconfig->interface[i]->dev);
  888. dev->actconfig->interface[i] = NULL;
  889. }
  890. dev->actconfig = NULL;
  891. if (dev->state == USB_STATE_CONFIGURED)
  892. usb_set_device_state(dev, USB_STATE_ADDRESS);
  893. }
  894. }
  895. /*
  896. * usb_enable_endpoint - Enable an endpoint for USB communications
  897. * @dev: the device whose interface is being enabled
  898. * @ep: the endpoint
  899. *
  900. * Resets the endpoint toggle, and sets dev->ep_{in,out} pointers.
  901. * For control endpoints, both the input and output sides are handled.
  902. */
  903. static void
  904. usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep)
  905. {
  906. unsigned int epaddr = ep->desc.bEndpointAddress;
  907. unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
  908. int is_control;
  909. is_control = ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
  910. == USB_ENDPOINT_XFER_CONTROL);
  911. if (usb_endpoint_out(epaddr) || is_control) {
  912. usb_settoggle(dev, epnum, 1, 0);
  913. dev->ep_out[epnum] = ep;
  914. }
  915. if (!usb_endpoint_out(epaddr) || is_control) {
  916. usb_settoggle(dev, epnum, 0, 0);
  917. dev->ep_in[epnum] = ep;
  918. }
  919. }
  920. /*
  921. * usb_enable_interface - Enable all the endpoints for an interface
  922. * @dev: the device whose interface is being enabled
  923. * @intf: pointer to the interface descriptor
  924. *
  925. * Enables all the endpoints for the interface's current altsetting.
  926. */
  927. static void usb_enable_interface(struct usb_device *dev,
  928. struct usb_interface *intf)
  929. {
  930. struct usb_host_interface *alt = intf->cur_altsetting;
  931. int i;
  932. for (i = 0; i < alt->desc.bNumEndpoints; ++i)
  933. usb_enable_endpoint(dev, &alt->endpoint[i]);
  934. }
  935. /**
  936. * usb_set_interface - Makes a particular alternate setting be current
  937. * @dev: the device whose interface is being updated
  938. * @interface: the interface being updated
  939. * @alternate: the setting being chosen.
  940. * Context: !in_interrupt ()
  941. *
  942. * This is used to enable data transfers on interfaces that may not
  943. * be enabled by default. Not all devices support such configurability.
  944. * Only the driver bound to an interface may change its setting.
  945. *
  946. * Within any given configuration, each interface may have several
  947. * alternative settings. These are often used to control levels of
  948. * bandwidth consumption. For example, the default setting for a high
  949. * speed interrupt endpoint may not send more than 64 bytes per microframe,
  950. * while interrupt transfers of up to 3KBytes per microframe are legal.
  951. * Also, isochronous endpoints may never be part of an
  952. * interface's default setting. To access such bandwidth, alternate
  953. * interface settings must be made current.
  954. *
  955. * Note that in the Linux USB subsystem, bandwidth associated with
  956. * an endpoint in a given alternate setting is not reserved until an URB
  957. * is submitted that needs that bandwidth. Some other operating systems
  958. * allocate bandwidth early, when a configuration is chosen.
  959. *
  960. * This call is synchronous, and may not be used in an interrupt context.
  961. * Also, drivers must not change altsettings while urbs are scheduled for
  962. * endpoints in that interface; all such urbs must first be completed
  963. * (perhaps forced by unlinking).
  964. *
  965. * Returns zero on success, or else the status code returned by the
  966. * underlying usb_control_msg() call.
  967. */
  968. int usb_set_interface(struct usb_device *dev, int interface, int alternate)
  969. {
  970. struct usb_interface *iface;
  971. struct usb_host_interface *alt;
  972. int ret;
  973. int manual = 0;
  974. if (dev->state == USB_STATE_SUSPENDED)
  975. return -EHOSTUNREACH;
  976. iface = usb_ifnum_to_if(dev, interface);
  977. if (!iface) {
  978. dev_dbg(&dev->dev, "selecting invalid interface %d\n",
  979. interface);
  980. return -EINVAL;
  981. }
  982. alt = usb_altnum_to_altsetting(iface, alternate);
  983. if (!alt) {
  984. warn("selecting invalid altsetting %d", alternate);
  985. return -EINVAL;
  986. }
  987. ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  988. USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
  989. alternate, interface, NULL, 0, 5000);
  990. /* 9.4.10 says devices don't need this and are free to STALL the
  991. * request if the interface only has one alternate setting.
  992. */
  993. if (ret == -EPIPE && iface->num_altsetting == 1) {
  994. dev_dbg(&dev->dev,
  995. "manual set_interface for iface %d, alt %d\n",
  996. interface, alternate);
  997. manual = 1;
  998. } else if (ret < 0)
  999. return ret;
  1000. /* FIXME drivers shouldn't need to replicate/bugfix the logic here
  1001. * when they implement async or easily-killable versions of this or
  1002. * other "should-be-internal" functions (like clear_halt).
  1003. * should hcd+usbcore postprocess control requests?
  1004. */
  1005. /* prevent submissions using previous endpoint settings */
  1006. usb_disable_interface(dev, iface);
  1007. iface->cur_altsetting = alt;
  1008. /* If the interface only has one altsetting and the device didn't
  1009. * accept the request, we attempt to carry out the equivalent action
  1010. * by manually clearing the HALT feature for each endpoint in the
  1011. * new altsetting.
  1012. */
  1013. if (manual) {
  1014. int i;
  1015. for (i = 0; i < alt->desc.bNumEndpoints; i++) {
  1016. unsigned int epaddr =
  1017. alt->endpoint[i].desc.bEndpointAddress;
  1018. unsigned int pipe =
  1019. __create_pipe(dev, USB_ENDPOINT_NUMBER_MASK & epaddr)
  1020. | (usb_endpoint_out(epaddr) ? USB_DIR_OUT : USB_DIR_IN);
  1021. usb_clear_halt(dev, pipe);
  1022. }
  1023. }
  1024. /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
  1025. *
  1026. * Note:
  1027. * Despite EP0 is always present in all interfaces/AS, the list of
  1028. * endpoints from the descriptor does not contain EP0. Due to its
  1029. * omnipresence one might expect EP0 being considered "affected" by
  1030. * any SetInterface request and hence assume toggles need to be reset.
  1031. * However, EP0 toggles are re-synced for every individual transfer
  1032. * during the SETUP stage - hence EP0 toggles are "don't care" here.
  1033. * (Likewise, EP0 never "halts" on well designed devices.)
  1034. */
  1035. usb_enable_interface(dev, iface);
  1036. return 0;
  1037. }
  1038. /**
  1039. * usb_reset_configuration - lightweight device reset
  1040. * @dev: the device whose configuration is being reset
  1041. *
  1042. * This issues a standard SET_CONFIGURATION request to the device using
  1043. * the current configuration. The effect is to reset most USB-related
  1044. * state in the device, including interface altsettings (reset to zero),
  1045. * endpoint halts (cleared), and data toggle (only for bulk and interrupt
  1046. * endpoints). Other usbcore state is unchanged, including bindings of
  1047. * usb device drivers to interfaces.
  1048. *
  1049. * Because this affects multiple interfaces, avoid using this with composite
  1050. * (multi-interface) devices. Instead, the driver for each interface may
  1051. * use usb_set_interface() on the interfaces it claims. Be careful though;
  1052. * some devices don't support the SET_INTERFACE request, and others won't
  1053. * reset all the interface state (notably data toggles). Resetting the whole
  1054. * configuration would affect other drivers' interfaces.
  1055. *
  1056. * The caller must own the device lock.
  1057. *
  1058. * Returns zero on success, else a negative error code.
  1059. */
  1060. int usb_reset_configuration(struct usb_device *dev)
  1061. {
  1062. int i, retval;
  1063. struct usb_host_config *config;
  1064. if (dev->state == USB_STATE_SUSPENDED)
  1065. return -EHOSTUNREACH;
  1066. /* caller must have locked the device and must own
  1067. * the usb bus readlock (so driver bindings are stable);
  1068. * calls during probe() are fine
  1069. */
  1070. for (i = 1; i < 16; ++i) {
  1071. usb_disable_endpoint(dev, i);
  1072. usb_disable_endpoint(dev, i + USB_DIR_IN);
  1073. }
  1074. config = dev->actconfig;
  1075. retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  1076. USB_REQ_SET_CONFIGURATION, 0,
  1077. config->desc.bConfigurationValue, 0,
  1078. NULL, 0, USB_CTRL_SET_TIMEOUT);
  1079. if (retval < 0) {
  1080. usb_set_device_state(dev, USB_STATE_ADDRESS);
  1081. return retval;
  1082. }
  1083. dev->toggle[0] = dev->toggle[1] = 0;
  1084. /* re-init hc/hcd interface/endpoint state */
  1085. for (i = 0; i < config->desc.bNumInterfaces; i++) {
  1086. struct usb_interface *intf = config->interface[i];
  1087. struct usb_host_interface *alt;
  1088. alt = usb_altnum_to_altsetting(intf, 0);
  1089. /* No altsetting 0? We'll assume the first altsetting.
  1090. * We could use a GetInterface call, but if a device is
  1091. * so non-compliant that it doesn't have altsetting 0
  1092. * then I wouldn't trust its reply anyway.
  1093. */
  1094. if (!alt)
  1095. alt = &intf->altsetting[0];
  1096. intf->cur_altsetting = alt;
  1097. usb_enable_interface(dev, intf);
  1098. }
  1099. return 0;
  1100. }
  1101. static void release_interface(struct device *dev)
  1102. {
  1103. struct usb_interface *intf = to_usb_interface(dev);
  1104. struct usb_interface_cache *intfc =
  1105. altsetting_to_usb_interface_cache(intf->altsetting);
  1106. kref_put(&intfc->ref, usb_release_interface_cache);
  1107. kfree(intf);
  1108. }
  1109. /*
  1110. * usb_set_configuration - Makes a particular device setting be current
  1111. * @dev: the device whose configuration is being updated
  1112. * @configuration: the configuration being chosen.
  1113. * Context: !in_interrupt(), caller owns the device lock
  1114. *
  1115. * This is used to enable non-default device modes. Not all devices
  1116. * use this kind of configurability; many devices only have one
  1117. * configuration.
  1118. *
  1119. * USB device configurations may affect Linux interoperability,
  1120. * power consumption and the functionality available. For example,
  1121. * the default configuration is limited to using 100mA of bus power,
  1122. * so that when certain device functionality requires more power,
  1123. * and the device is bus powered, that functionality should be in some
  1124. * non-default device configuration. Other device modes may also be
  1125. * reflected as configuration options, such as whether two ISDN
  1126. * channels are available independently; and choosing between open
  1127. * standard device protocols (like CDC) or proprietary ones.
  1128. *
  1129. * Note that USB has an additional level of device configurability,
  1130. * associated with interfaces. That configurability is accessed using
  1131. * usb_set_interface().
  1132. *
  1133. * This call is synchronous. The calling context must be able to sleep,
  1134. * must own the device lock, and must not hold the driver model's USB
  1135. * bus rwsem; usb device driver probe() methods cannot use this routine.
  1136. *
  1137. * Returns zero on success, or else the status code returned by the
  1138. * underlying call that failed. On successful completion, each interface
  1139. * in the original device configuration has been destroyed, and each one
  1140. * in the new configuration has been probed by all relevant usb device
  1141. * drivers currently known to the kernel.
  1142. */
  1143. int usb_set_configuration(struct usb_device *dev, int configuration)
  1144. {
  1145. int i, ret;
  1146. struct usb_host_config *cp = NULL;
  1147. struct usb_interface **new_interfaces = NULL;
  1148. int n, nintf;
  1149. for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
  1150. if (dev->config[i].desc.bConfigurationValue == configuration) {
  1151. cp = &dev->config[i];
  1152. break;
  1153. }
  1154. }
  1155. if ((!cp && configuration != 0))
  1156. return -EINVAL;
  1157. /* The USB spec says configuration 0 means unconfigured.
  1158. * But if a device includes a configuration numbered 0,
  1159. * we will accept it as a correctly configured state.
  1160. */
  1161. if (cp && configuration == 0)
  1162. dev_warn(&dev->dev, "config 0 descriptor??\n");
  1163. if (dev->state == USB_STATE_SUSPENDED)
  1164. return -EHOSTUNREACH;
  1165. /* Allocate memory for new interfaces before doing anything else,
  1166. * so that if we run out then nothing will have changed. */
  1167. n = nintf = 0;
  1168. if (cp) {
  1169. nintf = cp->desc.bNumInterfaces;
  1170. new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
  1171. GFP_KERNEL);
  1172. if (!new_interfaces) {
  1173. dev_err(&dev->dev, "Out of memory");
  1174. return -ENOMEM;
  1175. }
  1176. for (; n < nintf; ++n) {
  1177. new_interfaces[n] = kmalloc(
  1178. sizeof(struct usb_interface),
  1179. GFP_KERNEL);
  1180. if (!new_interfaces[n]) {
  1181. dev_err(&dev->dev, "Out of memory");
  1182. ret = -ENOMEM;
  1183. free_interfaces:
  1184. while (--n >= 0)
  1185. kfree(new_interfaces[n]);
  1186. kfree(new_interfaces);
  1187. return ret;
  1188. }
  1189. }
  1190. }
  1191. /* if it's already configured, clear out old state first.
  1192. * getting rid of old interfaces means unbinding their drivers.
  1193. */
  1194. if (dev->state != USB_STATE_ADDRESS)
  1195. usb_disable_device (dev, 1); // Skip ep0
  1196. if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  1197. USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
  1198. NULL, 0, USB_CTRL_SET_TIMEOUT)) < 0)
  1199. goto free_interfaces;
  1200. dev->actconfig = cp;
  1201. if (!cp)
  1202. usb_set_device_state(dev, USB_STATE_ADDRESS);
  1203. else {
  1204. usb_set_device_state(dev, USB_STATE_CONFIGURED);
  1205. /* Initialize the new interface structures and the
  1206. * hc/hcd/usbcore interface/endpoint state.
  1207. */
  1208. for (i = 0; i < nintf; ++i) {
  1209. struct usb_interface_cache *intfc;
  1210. struct usb_interface *intf;
  1211. struct usb_host_interface *alt;
  1212. cp->interface[i] = intf = new_interfaces[i];
  1213. memset(intf, 0, sizeof(*intf));
  1214. intfc = cp->intf_cache[i];
  1215. intf->altsetting = intfc->altsetting;
  1216. intf->num_altsetting = intfc->num_altsetting;
  1217. kref_get(&intfc->ref);
  1218. alt = usb_altnum_to_altsetting(intf, 0);
  1219. /* No altsetting 0? We'll assume the first altsetting.
  1220. * We could use a GetInterface call, but if a device is
  1221. * so non-compliant that it doesn't have altsetting 0
  1222. * then I wouldn't trust its reply anyway.
  1223. */
  1224. if (!alt)
  1225. alt = &intf->altsetting[0];
  1226. intf->cur_altsetting = alt;
  1227. usb_enable_interface(dev, intf);
  1228. intf->dev.parent = &dev->dev;
  1229. intf->dev.driver = NULL;
  1230. intf->dev.bus = &usb_bus_type;
  1231. intf->dev.dma_mask = dev->dev.dma_mask;
  1232. intf->dev.release = release_interface;
  1233. device_initialize (&intf->dev);
  1234. sprintf (&intf->dev.bus_id[0], "%d-%s:%d.%d",
  1235. dev->bus->busnum, dev->devpath,
  1236. configuration,
  1237. alt->desc.bInterfaceNumber);
  1238. }
  1239. kfree(new_interfaces);
  1240. if ((cp->desc.iConfiguration) &&
  1241. (cp->string == NULL)) {
  1242. cp->string = kmalloc(256, GFP_KERNEL);
  1243. if (cp->string)
  1244. usb_string(dev, cp->desc.iConfiguration, cp->string, 256);
  1245. }
  1246. /* Now that all the interfaces are set up, register them
  1247. * to trigger binding of drivers to interfaces. probe()
  1248. * routines may install different altsettings and may
  1249. * claim() any interfaces not yet bound. Many class drivers
  1250. * need that: CDC, audio, video, etc.
  1251. */
  1252. for (i = 0; i < nintf; ++i) {
  1253. struct usb_interface *intf = cp->interface[i];
  1254. struct usb_interface_descriptor *desc;
  1255. desc = &intf->altsetting [0].desc;
  1256. dev_dbg (&dev->dev,
  1257. "adding %s (config #%d, interface %d)\n",
  1258. intf->dev.bus_id, configuration,
  1259. desc->bInterfaceNumber);
  1260. ret = device_add (&intf->dev);
  1261. if (ret != 0) {
  1262. dev_err(&dev->dev,
  1263. "device_add(%s) --> %d\n",
  1264. intf->dev.bus_id,
  1265. ret);
  1266. continue;
  1267. }
  1268. if ((intf->cur_altsetting->desc.iInterface) &&
  1269. (intf->cur_altsetting->string == NULL)) {
  1270. intf->cur_altsetting->string = kmalloc(256, GFP_KERNEL);
  1271. if (intf->cur_altsetting->string)
  1272. usb_string(dev, intf->cur_altsetting->desc.iInterface,
  1273. intf->cur_altsetting->string, 256);
  1274. }
  1275. usb_create_sysfs_intf_files (intf);
  1276. }
  1277. }
  1278. return 0;
  1279. }
  1280. // synchronous request completion model
  1281. EXPORT_SYMBOL(usb_control_msg);
  1282. EXPORT_SYMBOL(usb_bulk_msg);
  1283. EXPORT_SYMBOL(usb_sg_init);
  1284. EXPORT_SYMBOL(usb_sg_cancel);
  1285. EXPORT_SYMBOL(usb_sg_wait);
  1286. // synchronous control message convenience routines
  1287. EXPORT_SYMBOL(usb_get_descriptor);
  1288. EXPORT_SYMBOL(usb_get_status);
  1289. EXPORT_SYMBOL(usb_get_string);
  1290. EXPORT_SYMBOL(usb_string);
  1291. // synchronous calls that also maintain usbcore state
  1292. EXPORT_SYMBOL(usb_clear_halt);
  1293. EXPORT_SYMBOL(usb_reset_configuration);
  1294. EXPORT_SYMBOL(usb_set_interface);