message.c 53 KB

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