message.c 52 KB

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