message.c 52 KB

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