message.c 46 KB

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