message.c 46 KB

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