message.c 45 KB

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