message.c 47 KB

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