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->transfer_flags |= URB_ASYNC_UNLINK;
  42. urb->actual_length = 0;
  43. status = usb_submit_urb(urb, GFP_NOIO);
  44. if (status == 0) {
  45. if (timeout > 0) {
  46. init_timer(&timer);
  47. timer.expires = jiffies + msecs_to_jiffies(timeout);
  48. timer.data = (unsigned long)urb;
  49. timer.function = timeout_kill;
  50. /* grr. timeout _should_ include submit delays. */
  51. add_timer(&timer);
  52. }
  53. wait_for_completion(&done);
  54. status = urb->status;
  55. /* note: HCDs return ETIMEDOUT for other reasons too */
  56. if (status == -ECONNRESET) {
  57. dev_dbg(&urb->dev->dev,
  58. "%s timed out on ep%d%s len=%d/%d\n",
  59. current->comm,
  60. usb_pipeendpoint(urb->pipe),
  61. usb_pipein(urb->pipe) ? "in" : "out",
  62. urb->actual_length,
  63. urb->transfer_buffer_length
  64. );
  65. if (urb->actual_length > 0)
  66. status = 0;
  67. else
  68. status = -ETIMEDOUT;
  69. }
  70. if (timeout > 0)
  71. del_timer_sync(&timer);
  72. }
  73. if (actual_length)
  74. *actual_length = urb->actual_length;
  75. usb_free_urb(urb);
  76. return status;
  77. }
  78. /*-------------------------------------------------------------------*/
  79. // returns status (negative) or length (positive)
  80. static int usb_internal_control_msg(struct usb_device *usb_dev,
  81. unsigned int pipe,
  82. struct usb_ctrlrequest *cmd,
  83. void *data, int len, int timeout)
  84. {
  85. struct urb *urb;
  86. int retv;
  87. int length;
  88. urb = usb_alloc_urb(0, GFP_NOIO);
  89. if (!urb)
  90. return -ENOMEM;
  91. usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
  92. len, usb_api_blocking_completion, NULL);
  93. retv = usb_start_wait_urb(urb, timeout, &length);
  94. if (retv < 0)
  95. return retv;
  96. else
  97. return length;
  98. }
  99. /**
  100. * usb_control_msg - Builds a control urb, sends it off and waits for completion
  101. * @dev: pointer to the usb device to send the message to
  102. * @pipe: endpoint "pipe" to send the message to
  103. * @request: USB message request value
  104. * @requesttype: USB message request type value
  105. * @value: USB message value
  106. * @index: USB message index value
  107. * @data: pointer to the data to send
  108. * @size: length in bytes of the data to send
  109. * @timeout: time in msecs to wait for the message to complete before
  110. * timing out (if 0 the wait is forever)
  111. * Context: !in_interrupt ()
  112. *
  113. * This function sends a simple control message to a specified endpoint
  114. * and waits for the message to complete, or timeout.
  115. *
  116. * If successful, it returns the number of bytes transferred, otherwise a negative error number.
  117. *
  118. * Don't use this function from within an interrupt context, like a
  119. * bottom half handler. If you need an asynchronous message, or need to send
  120. * a message from within interrupt context, use usb_submit_urb()
  121. * If a thread in your driver uses this call, make sure your disconnect()
  122. * method can wait for it to complete. Since you don't have a handle on
  123. * the URB used, you can't cancel the request.
  124. */
  125. int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype,
  126. __u16 value, __u16 index, void *data, __u16 size, int timeout)
  127. {
  128. struct usb_ctrlrequest *dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
  129. int ret;
  130. if (!dr)
  131. return -ENOMEM;
  132. dr->bRequestType= requesttype;
  133. dr->bRequest = request;
  134. dr->wValue = cpu_to_le16p(&value);
  135. dr->wIndex = cpu_to_le16p(&index);
  136. dr->wLength = cpu_to_le16p(&size);
  137. //dbg("usb_control_msg");
  138. ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
  139. kfree(dr);
  140. return ret;
  141. }
  142. /**
  143. * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
  144. * @usb_dev: pointer to the usb device to send the message to
  145. * @pipe: endpoint "pipe" to send the message to
  146. * @data: pointer to the data to send
  147. * @len: length in bytes of the data to send
  148. * @actual_length: pointer to a location to put the actual length transferred in bytes
  149. * @timeout: time in msecs to wait for the message to complete before
  150. * timing out (if 0 the wait is forever)
  151. * Context: !in_interrupt ()
  152. *
  153. * This function sends a simple bulk message to a specified endpoint
  154. * and waits for the message to complete, or timeout.
  155. *
  156. * If successful, it returns 0, otherwise a negative error number.
  157. * The number of actual bytes transferred will be stored in the
  158. * actual_length paramater.
  159. *
  160. * Don't use this function from within an interrupt context, like a
  161. * bottom half handler. If you need an asynchronous message, or need to
  162. * send a message from within interrupt context, use usb_submit_urb()
  163. * If a thread in your driver uses this call, make sure your disconnect()
  164. * method can wait for it to complete. Since you don't have a handle on
  165. * the URB used, you can't cancel the request.
  166. */
  167. int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
  168. void *data, int len, int *actual_length, int timeout)
  169. {
  170. struct urb *urb;
  171. if (len < 0)
  172. return -EINVAL;
  173. urb=usb_alloc_urb(0, GFP_KERNEL);
  174. if (!urb)
  175. return -ENOMEM;
  176. usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
  177. usb_api_blocking_completion, NULL);
  178. return usb_start_wait_urb(urb, timeout, actual_length);
  179. }
  180. /*-------------------------------------------------------------------*/
  181. static void sg_clean (struct usb_sg_request *io)
  182. {
  183. if (io->urbs) {
  184. while (io->entries--)
  185. usb_free_urb (io->urbs [io->entries]);
  186. kfree (io->urbs);
  187. io->urbs = NULL;
  188. }
  189. if (io->dev->dev.dma_mask != NULL)
  190. usb_buffer_unmap_sg (io->dev, io->pipe, io->sg, io->nents);
  191. io->dev = NULL;
  192. }
  193. static void sg_complete (struct urb *urb, struct pt_regs *regs)
  194. {
  195. struct usb_sg_request *io = (struct usb_sg_request *) urb->context;
  196. spin_lock (&io->lock);
  197. /* In 2.5 we require hcds' endpoint queues not to progress after fault
  198. * reports, until the completion callback (this!) returns. That lets
  199. * device driver code (like this routine) unlink queued urbs first,
  200. * if it needs to, since the HC won't work on them at all. So it's
  201. * not possible for page N+1 to overwrite page N, and so on.
  202. *
  203. * That's only for "hard" faults; "soft" faults (unlinks) sometimes
  204. * complete before the HCD can get requests away from hardware,
  205. * though never during cleanup after a hard fault.
  206. */
  207. if (io->status
  208. && (io->status != -ECONNRESET
  209. || urb->status != -ECONNRESET)
  210. && urb->actual_length) {
  211. dev_err (io->dev->bus->controller,
  212. "dev %s ep%d%s scatterlist error %d/%d\n",
  213. io->dev->devpath,
  214. usb_pipeendpoint (urb->pipe),
  215. usb_pipein (urb->pipe) ? "in" : "out",
  216. urb->status, io->status);
  217. // BUG ();
  218. }
  219. if (io->status == 0 && urb->status && urb->status != -ECONNRESET) {
  220. int i, found, status;
  221. io->status = urb->status;
  222. /* the previous urbs, and this one, completed already.
  223. * unlink pending urbs so they won't rx/tx bad data.
  224. * careful: unlink can sometimes be synchronous...
  225. */
  226. spin_unlock (&io->lock);
  227. for (i = 0, found = 0; i < io->entries; i++) {
  228. if (!io->urbs [i] || !io->urbs [i]->dev)
  229. continue;
  230. if (found) {
  231. status = usb_unlink_urb (io->urbs [i]);
  232. if (status != -EINPROGRESS && status != -EBUSY)
  233. dev_err (&io->dev->dev,
  234. "%s, unlink --> %d\n",
  235. __FUNCTION__, status);
  236. } else if (urb == io->urbs [i])
  237. found = 1;
  238. }
  239. spin_lock (&io->lock);
  240. }
  241. urb->dev = NULL;
  242. /* on the last completion, signal usb_sg_wait() */
  243. io->bytes += urb->actual_length;
  244. io->count--;
  245. if (!io->count)
  246. complete (&io->complete);
  247. spin_unlock (&io->lock);
  248. }
  249. /**
  250. * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
  251. * @io: request block being initialized. until usb_sg_wait() returns,
  252. * treat this as a pointer to an opaque block of memory,
  253. * @dev: the usb device that will send or receive the data
  254. * @pipe: endpoint "pipe" used to transfer the data
  255. * @period: polling rate for interrupt endpoints, in frames or
  256. * (for high speed endpoints) microframes; ignored for bulk
  257. * @sg: scatterlist entries
  258. * @nents: how many entries in the scatterlist
  259. * @length: how many bytes to send from the scatterlist, or zero to
  260. * send every byte identified in the list.
  261. * @mem_flags: SLAB_* flags affecting memory allocations in this call
  262. *
  263. * Returns zero for success, else a negative errno value. This initializes a
  264. * scatter/gather request, allocating resources such as I/O mappings and urb
  265. * memory (except maybe memory used by USB controller drivers).
  266. *
  267. * The request must be issued using usb_sg_wait(), which waits for the I/O to
  268. * complete (or to be canceled) and then cleans up all resources allocated by
  269. * usb_sg_init().
  270. *
  271. * The request may be canceled with usb_sg_cancel(), either before or after
  272. * usb_sg_wait() is called.
  273. */
  274. int usb_sg_init (
  275. struct usb_sg_request *io,
  276. struct usb_device *dev,
  277. unsigned pipe,
  278. unsigned period,
  279. struct scatterlist *sg,
  280. int nents,
  281. size_t length,
  282. int mem_flags
  283. )
  284. {
  285. int i;
  286. int urb_flags;
  287. int dma;
  288. if (!io || !dev || !sg
  289. || usb_pipecontrol (pipe)
  290. || usb_pipeisoc (pipe)
  291. || nents <= 0)
  292. return -EINVAL;
  293. spin_lock_init (&io->lock);
  294. io->dev = dev;
  295. io->pipe = pipe;
  296. io->sg = sg;
  297. io->nents = nents;
  298. /* not all host controllers use DMA (like the mainstream pci ones);
  299. * they can use PIO (sl811) or be software over another transport.
  300. */
  301. dma = (dev->dev.dma_mask != NULL);
  302. if (dma)
  303. io->entries = usb_buffer_map_sg (dev, pipe, sg, nents);
  304. else
  305. io->entries = nents;
  306. /* initialize all the urbs we'll use */
  307. if (io->entries <= 0)
  308. return io->entries;
  309. io->count = io->entries;
  310. io->urbs = kmalloc (io->entries * sizeof *io->urbs, mem_flags);
  311. if (!io->urbs)
  312. goto nomem;
  313. urb_flags = URB_ASYNC_UNLINK | URB_NO_TRANSFER_DMA_MAP
  314. | URB_NO_INTERRUPT;
  315. if (usb_pipein (pipe))
  316. urb_flags |= URB_SHORT_NOT_OK;
  317. for (i = 0; i < io->entries; i++) {
  318. unsigned len;
  319. io->urbs [i] = usb_alloc_urb (0, mem_flags);
  320. if (!io->urbs [i]) {
  321. io->entries = i;
  322. goto nomem;
  323. }
  324. io->urbs [i]->dev = NULL;
  325. io->urbs [i]->pipe = pipe;
  326. io->urbs [i]->interval = period;
  327. io->urbs [i]->transfer_flags = urb_flags;
  328. io->urbs [i]->complete = sg_complete;
  329. io->urbs [i]->context = io;
  330. io->urbs [i]->status = -EINPROGRESS;
  331. io->urbs [i]->actual_length = 0;
  332. if (dma) {
  333. /* hc may use _only_ transfer_dma */
  334. io->urbs [i]->transfer_dma = sg_dma_address (sg + i);
  335. len = sg_dma_len (sg + i);
  336. } else {
  337. /* hc may use _only_ transfer_buffer */
  338. io->urbs [i]->transfer_buffer =
  339. page_address (sg [i].page) + sg [i].offset;
  340. len = sg [i].length;
  341. }
  342. if (length) {
  343. len = min_t (unsigned, len, length);
  344. length -= len;
  345. if (length == 0)
  346. io->entries = i + 1;
  347. }
  348. io->urbs [i]->transfer_buffer_length = len;
  349. }
  350. io->urbs [--i]->transfer_flags &= ~URB_NO_INTERRUPT;
  351. /* transaction state */
  352. io->status = 0;
  353. io->bytes = 0;
  354. init_completion (&io->complete);
  355. return 0;
  356. nomem:
  357. sg_clean (io);
  358. return -ENOMEM;
  359. }
  360. /**
  361. * usb_sg_wait - synchronously execute scatter/gather request
  362. * @io: request block handle, as initialized with usb_sg_init().
  363. * some fields become accessible when this call returns.
  364. * Context: !in_interrupt ()
  365. *
  366. * This function blocks until the specified I/O operation completes. It
  367. * leverages the grouping of the related I/O requests to get good transfer
  368. * rates, by queueing the requests. At higher speeds, such queuing can
  369. * significantly improve USB throughput.
  370. *
  371. * There are three kinds of completion for this function.
  372. * (1) success, where io->status is zero. The number of io->bytes
  373. * transferred is as requested.
  374. * (2) error, where io->status is a negative errno value. The number
  375. * of io->bytes transferred before the error is usually less
  376. * than requested, and can be nonzero.
  377. * (3) cancellation, a type of error with status -ECONNRESET that
  378. * is initiated by usb_sg_cancel().
  379. *
  380. * When this function returns, all memory allocated through usb_sg_init() or
  381. * this call will have been freed. The request block parameter may still be
  382. * passed to usb_sg_cancel(), or it may be freed. It could also be
  383. * reinitialized and then reused.
  384. *
  385. * Data Transfer Rates:
  386. *
  387. * Bulk transfers are valid for full or high speed endpoints.
  388. * The best full speed data rate is 19 packets of 64 bytes each
  389. * per frame, or 1216 bytes per millisecond.
  390. * The best high speed data rate is 13 packets of 512 bytes each
  391. * per microframe, or 52 KBytes per millisecond.
  392. *
  393. * The reason to use interrupt transfers through this API would most likely
  394. * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
  395. * could be transferred. That capability is less useful for low or full
  396. * speed interrupt endpoints, which allow at most one packet per millisecond,
  397. * of at most 8 or 64 bytes (respectively).
  398. */
  399. void usb_sg_wait (struct usb_sg_request *io)
  400. {
  401. int i, entries = io->entries;
  402. /* queue the urbs. */
  403. spin_lock_irq (&io->lock);
  404. for (i = 0; i < entries && !io->status; i++) {
  405. int retval;
  406. io->urbs [i]->dev = io->dev;
  407. retval = usb_submit_urb (io->urbs [i], SLAB_ATOMIC);
  408. /* after we submit, let completions or cancelations fire;
  409. * we handshake using io->status.
  410. */
  411. spin_unlock_irq (&io->lock);
  412. switch (retval) {
  413. /* maybe we retrying will recover */
  414. case -ENXIO: // hc didn't queue this one
  415. case -EAGAIN:
  416. case -ENOMEM:
  417. io->urbs[i]->dev = NULL;
  418. retval = 0;
  419. i--;
  420. yield ();
  421. break;
  422. /* no error? continue immediately.
  423. *
  424. * NOTE: to work better with UHCI (4K I/O buffer may
  425. * need 3K of TDs) it may be good to limit how many
  426. * URBs are queued at once; N milliseconds?
  427. */
  428. case 0:
  429. cpu_relax ();
  430. break;
  431. /* fail any uncompleted urbs */
  432. default:
  433. io->urbs [i]->dev = NULL;
  434. io->urbs [i]->status = retval;
  435. dev_dbg (&io->dev->dev, "%s, submit --> %d\n",
  436. __FUNCTION__, retval);
  437. usb_sg_cancel (io);
  438. }
  439. spin_lock_irq (&io->lock);
  440. if (retval && (io->status == 0 || io->status == -ECONNRESET))
  441. io->status = retval;
  442. }
  443. io->count -= entries - i;
  444. if (io->count == 0)
  445. complete (&io->complete);
  446. spin_unlock_irq (&io->lock);
  447. /* OK, yes, this could be packaged as non-blocking.
  448. * So could the submit loop above ... but it's easier to
  449. * solve neither problem than to solve both!
  450. */
  451. wait_for_completion (&io->complete);
  452. sg_clean (io);
  453. }
  454. /**
  455. * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
  456. * @io: request block, initialized with usb_sg_init()
  457. *
  458. * This stops a request after it has been started by usb_sg_wait().
  459. * It can also prevents one initialized by usb_sg_init() from starting,
  460. * so that call just frees resources allocated to the request.
  461. */
  462. void usb_sg_cancel (struct usb_sg_request *io)
  463. {
  464. unsigned long flags;
  465. spin_lock_irqsave (&io->lock, flags);
  466. /* shut everything down, if it didn't already */
  467. if (!io->status) {
  468. int i;
  469. io->status = -ECONNRESET;
  470. spin_unlock (&io->lock);
  471. for (i = 0; i < io->entries; i++) {
  472. int retval;
  473. if (!io->urbs [i]->dev)
  474. continue;
  475. retval = usb_unlink_urb (io->urbs [i]);
  476. if (retval != -EINPROGRESS && retval != -EBUSY)
  477. dev_warn (&io->dev->dev, "%s, unlink --> %d\n",
  478. __FUNCTION__, retval);
  479. }
  480. spin_lock (&io->lock);
  481. }
  482. spin_unlock_irqrestore (&io->lock, flags);
  483. }
  484. /*-------------------------------------------------------------------*/
  485. /**
  486. * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
  487. * @dev: the device whose descriptor is being retrieved
  488. * @type: the descriptor type (USB_DT_*)
  489. * @index: the number of the descriptor
  490. * @buf: where to put the descriptor
  491. * @size: how big is "buf"?
  492. * Context: !in_interrupt ()
  493. *
  494. * Gets a USB descriptor. Convenience functions exist to simplify
  495. * getting some types of descriptors. Use
  496. * usb_get_string() or usb_string() for USB_DT_STRING.
  497. * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
  498. * are part of the device structure.
  499. * In addition to a number of USB-standard descriptors, some
  500. * devices also use class-specific or vendor-specific descriptors.
  501. *
  502. * This call is synchronous, and may not be used in an interrupt context.
  503. *
  504. * Returns the number of bytes received on success, or else the status code
  505. * returned by the underlying usb_control_msg() call.
  506. */
  507. int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
  508. {
  509. int i;
  510. int result;
  511. memset(buf,0,size); // Make sure we parse really received data
  512. for (i = 0; i < 3; ++i) {
  513. /* retry on length 0 or stall; some devices are flakey */
  514. result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  515. USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
  516. (type << 8) + index, 0, buf, size,
  517. USB_CTRL_GET_TIMEOUT);
  518. if (result == 0 || result == -EPIPE)
  519. continue;
  520. if (result > 1 && ((u8 *)buf)[1] != type) {
  521. result = -EPROTO;
  522. continue;
  523. }
  524. break;
  525. }
  526. return result;
  527. }
  528. /**
  529. * usb_get_string - gets a string descriptor
  530. * @dev: the device whose string descriptor is being retrieved
  531. * @langid: code for language chosen (from string descriptor zero)
  532. * @index: the number of the descriptor
  533. * @buf: where to put the string
  534. * @size: how big is "buf"?
  535. * Context: !in_interrupt ()
  536. *
  537. * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
  538. * in little-endian byte order).
  539. * The usb_string() function will often be a convenient way to turn
  540. * these strings into kernel-printable form.
  541. *
  542. * Strings may be referenced in device, configuration, interface, or other
  543. * descriptors, and could also be used in vendor-specific ways.
  544. *
  545. * This call is synchronous, and may not be used in an interrupt context.
  546. *
  547. * Returns the number of bytes received on success, or else the status code
  548. * returned by the underlying usb_control_msg() call.
  549. */
  550. int usb_get_string(struct usb_device *dev, unsigned short langid,
  551. unsigned char index, void *buf, int size)
  552. {
  553. int i;
  554. int result;
  555. for (i = 0; i < 3; ++i) {
  556. /* retry on length 0 or stall; some devices are flakey */
  557. result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  558. USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
  559. (USB_DT_STRING << 8) + index, langid, buf, size,
  560. USB_CTRL_GET_TIMEOUT);
  561. if (!(result == 0 || result == -EPIPE))
  562. break;
  563. }
  564. return result;
  565. }
  566. static void usb_try_string_workarounds(unsigned char *buf, int *length)
  567. {
  568. int newlength, oldlength = *length;
  569. for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
  570. if (!isprint(buf[newlength]) || buf[newlength + 1])
  571. break;
  572. if (newlength > 2) {
  573. buf[0] = newlength;
  574. *length = newlength;
  575. }
  576. }
  577. static int usb_string_sub(struct usb_device *dev, unsigned int langid,
  578. unsigned int index, unsigned char *buf)
  579. {
  580. int rc;
  581. /* Try to read the string descriptor by asking for the maximum
  582. * possible number of bytes */
  583. rc = usb_get_string(dev, langid, index, buf, 255);
  584. /* If that failed try to read the descriptor length, then
  585. * ask for just that many bytes */
  586. if (rc < 2) {
  587. rc = usb_get_string(dev, langid, index, buf, 2);
  588. if (rc == 2)
  589. rc = usb_get_string(dev, langid, index, buf, buf[0]);
  590. }
  591. if (rc >= 2) {
  592. if (!buf[0] && !buf[1])
  593. usb_try_string_workarounds(buf, &rc);
  594. /* There might be extra junk at the end of the descriptor */
  595. if (buf[0] < rc)
  596. rc = buf[0];
  597. rc = rc - (rc & 1); /* force a multiple of two */
  598. }
  599. if (rc < 2)
  600. rc = (rc < 0 ? rc : -EINVAL);
  601. return rc;
  602. }
  603. /**
  604. * usb_string - returns ISO 8859-1 version of a string descriptor
  605. * @dev: the device whose string descriptor is being retrieved
  606. * @index: the number of the descriptor
  607. * @buf: where to put the string
  608. * @size: how big is "buf"?
  609. * Context: !in_interrupt ()
  610. *
  611. * This converts the UTF-16LE encoded strings returned by devices, from
  612. * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
  613. * that are more usable in most kernel contexts. Note that all characters
  614. * in the chosen descriptor that can't be encoded using ISO-8859-1
  615. * are converted to the question mark ("?") character, and this function
  616. * chooses strings in the first language supported by the device.
  617. *
  618. * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
  619. * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
  620. * and is appropriate for use many uses of English and several other
  621. * Western European languages. (But it doesn't include the "Euro" symbol.)
  622. *
  623. * This call is synchronous, and may not be used in an interrupt context.
  624. *
  625. * Returns length of the string (>= 0) or usb_control_msg status (< 0).
  626. */
  627. int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
  628. {
  629. unsigned char *tbuf;
  630. int err;
  631. unsigned int u, idx;
  632. if (dev->state == USB_STATE_SUSPENDED)
  633. return -EHOSTUNREACH;
  634. if (size <= 0 || !buf || !index)
  635. return -EINVAL;
  636. buf[0] = 0;
  637. tbuf = kmalloc(256, GFP_KERNEL);
  638. if (!tbuf)
  639. return -ENOMEM;
  640. /* get langid for strings if it's not yet known */
  641. if (!dev->have_langid) {
  642. err = usb_string_sub(dev, 0, 0, tbuf);
  643. if (err < 0) {
  644. dev_err (&dev->dev,
  645. "string descriptor 0 read error: %d\n",
  646. err);
  647. goto errout;
  648. } else if (err < 4) {
  649. dev_err (&dev->dev, "string descriptor 0 too short\n");
  650. err = -EINVAL;
  651. goto errout;
  652. } else {
  653. dev->have_langid = -1;
  654. dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
  655. /* always use the first langid listed */
  656. dev_dbg (&dev->dev, "default language 0x%04x\n",
  657. dev->string_langid);
  658. }
  659. }
  660. err = usb_string_sub(dev, dev->string_langid, index, tbuf);
  661. if (err < 0)
  662. goto errout;
  663. size--; /* leave room for trailing NULL char in output buffer */
  664. for (idx = 0, u = 2; u < err; u += 2) {
  665. if (idx >= size)
  666. break;
  667. if (tbuf[u+1]) /* high byte */
  668. buf[idx++] = '?'; /* non ISO-8859-1 character */
  669. else
  670. buf[idx++] = tbuf[u];
  671. }
  672. buf[idx] = 0;
  673. err = idx;
  674. if (tbuf[1] != USB_DT_STRING)
  675. dev_dbg(&dev->dev, "wrong descriptor type %02x for string %d (\"%s\")\n", tbuf[1], index, buf);
  676. errout:
  677. kfree(tbuf);
  678. return err;
  679. }
  680. /*
  681. * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
  682. * @dev: the device whose device descriptor is being updated
  683. * @size: how much of the descriptor to read
  684. * Context: !in_interrupt ()
  685. *
  686. * Updates the copy of the device descriptor stored in the device structure,
  687. * which dedicates space for this purpose. Note that several fields are
  688. * converted to the host CPU's byte order: the USB version (bcdUSB), and
  689. * vendors product and version fields (idVendor, idProduct, and bcdDevice).
  690. * That lets device drivers compare against non-byteswapped constants.
  691. *
  692. * Not exported, only for use by the core. If drivers really want to read
  693. * the device descriptor directly, they can call usb_get_descriptor() with
  694. * type = USB_DT_DEVICE and index = 0.
  695. *
  696. * This call is synchronous, and may not be used in an interrupt context.
  697. *
  698. * Returns the number of bytes received on success, or else the status code
  699. * returned by the underlying usb_control_msg() call.
  700. */
  701. int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
  702. {
  703. struct usb_device_descriptor *desc;
  704. int ret;
  705. if (size > sizeof(*desc))
  706. return -EINVAL;
  707. desc = kmalloc(sizeof(*desc), GFP_NOIO);
  708. if (!desc)
  709. return -ENOMEM;
  710. ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
  711. if (ret >= 0)
  712. memcpy(&dev->descriptor, desc, size);
  713. kfree(desc);
  714. return ret;
  715. }
  716. /**
  717. * usb_get_status - issues a GET_STATUS call
  718. * @dev: the device whose status is being checked
  719. * @type: USB_RECIP_*; for device, interface, or endpoint
  720. * @target: zero (for device), else interface or endpoint number
  721. * @data: pointer to two bytes of bitmap data
  722. * Context: !in_interrupt ()
  723. *
  724. * Returns device, interface, or endpoint status. Normally only of
  725. * interest to see if the device is self powered, or has enabled the
  726. * remote wakeup facility; or whether a bulk or interrupt endpoint
  727. * is halted ("stalled").
  728. *
  729. * Bits in these status bitmaps are set using the SET_FEATURE request,
  730. * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
  731. * function should be used to clear halt ("stall") status.
  732. *
  733. * This call is synchronous, and may not be used in an interrupt context.
  734. *
  735. * Returns the number of bytes received on success, or else the status code
  736. * returned by the underlying usb_control_msg() call.
  737. */
  738. int usb_get_status(struct usb_device *dev, int type, int target, void *data)
  739. {
  740. int ret;
  741. u16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
  742. if (!status)
  743. return -ENOMEM;
  744. ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  745. USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
  746. sizeof(*status), USB_CTRL_GET_TIMEOUT);
  747. *(u16 *)data = *status;
  748. kfree(status);
  749. return ret;
  750. }
  751. /**
  752. * usb_clear_halt - tells device to clear endpoint halt/stall condition
  753. * @dev: device whose endpoint is halted
  754. * @pipe: endpoint "pipe" being cleared
  755. * Context: !in_interrupt ()
  756. *
  757. * This is used to clear halt conditions for bulk and interrupt endpoints,
  758. * as reported by URB completion status. Endpoints that are halted are
  759. * sometimes referred to as being "stalled". Such endpoints are unable
  760. * to transmit or receive data until the halt status is cleared. Any URBs
  761. * queued for such an endpoint should normally be unlinked by the driver
  762. * before clearing the halt condition, as described in sections 5.7.5
  763. * and 5.8.5 of the USB 2.0 spec.
  764. *
  765. * Note that control and isochronous endpoints don't halt, although control
  766. * endpoints report "protocol stall" (for unsupported requests) using the
  767. * same status code used to report a true stall.
  768. *
  769. * This call is synchronous, and may not be used in an interrupt context.
  770. *
  771. * Returns zero on success, or else the status code returned by the
  772. * underlying usb_control_msg() call.
  773. */
  774. int usb_clear_halt(struct usb_device *dev, int pipe)
  775. {
  776. int result;
  777. int endp = usb_pipeendpoint(pipe);
  778. if (usb_pipein (pipe))
  779. endp |= USB_DIR_IN;
  780. /* we don't care if it wasn't halted first. in fact some devices
  781. * (like some ibmcam model 1 units) seem to expect hosts to make
  782. * this request for iso endpoints, which can't halt!
  783. */
  784. result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  785. USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
  786. USB_ENDPOINT_HALT, endp, NULL, 0,
  787. USB_CTRL_SET_TIMEOUT);
  788. /* don't un-halt or force to DATA0 except on success */
  789. if (result < 0)
  790. return result;
  791. /* NOTE: seems like Microsoft and Apple don't bother verifying
  792. * the clear "took", so some devices could lock up if you check...
  793. * such as the Hagiwara FlashGate DUAL. So we won't bother.
  794. *
  795. * NOTE: make sure the logic here doesn't diverge much from
  796. * the copy in usb-storage, for as long as we need two copies.
  797. */
  798. /* toggle was reset by the clear */
  799. usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
  800. return 0;
  801. }
  802. /**
  803. * usb_disable_endpoint -- Disable an endpoint by address
  804. * @dev: the device whose endpoint is being disabled
  805. * @epaddr: the endpoint's address. Endpoint number for output,
  806. * endpoint number + USB_DIR_IN for input
  807. *
  808. * Deallocates hcd/hardware state for this endpoint ... and nukes all
  809. * pending urbs.
  810. *
  811. * If the HCD hasn't registered a disable() function, this sets the
  812. * endpoint's maxpacket size to 0 to prevent further submissions.
  813. */
  814. void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr)
  815. {
  816. unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
  817. struct usb_host_endpoint *ep;
  818. if (!dev)
  819. return;
  820. if (usb_endpoint_out(epaddr)) {
  821. ep = dev->ep_out[epnum];
  822. dev->ep_out[epnum] = NULL;
  823. } else {
  824. ep = dev->ep_in[epnum];
  825. dev->ep_in[epnum] = NULL;
  826. }
  827. if (ep && dev->bus && dev->bus->op && dev->bus->op->disable)
  828. dev->bus->op->disable(dev, ep);
  829. }
  830. /**
  831. * usb_disable_interface -- Disable all endpoints for an interface
  832. * @dev: the device whose interface is being disabled
  833. * @intf: pointer to the interface descriptor
  834. *
  835. * Disables all the endpoints for the interface's current altsetting.
  836. */
  837. void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf)
  838. {
  839. struct usb_host_interface *alt = intf->cur_altsetting;
  840. int i;
  841. for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
  842. usb_disable_endpoint(dev,
  843. alt->endpoint[i].desc.bEndpointAddress);
  844. }
  845. }
  846. /*
  847. * usb_disable_device - Disable all the endpoints for a USB device
  848. * @dev: the device whose endpoints are being disabled
  849. * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
  850. *
  851. * Disables all the device's endpoints, potentially including endpoint 0.
  852. * Deallocates hcd/hardware state for the endpoints (nuking all or most
  853. * pending urbs) and usbcore state for the interfaces, so that usbcore
  854. * must usb_set_configuration() before any interfaces could be used.
  855. */
  856. void usb_disable_device(struct usb_device *dev, int skip_ep0)
  857. {
  858. int i;
  859. dev_dbg(&dev->dev, "%s nuking %s URBs\n", __FUNCTION__,
  860. skip_ep0 ? "non-ep0" : "all");
  861. for (i = skip_ep0; i < 16; ++i) {
  862. usb_disable_endpoint(dev, i);
  863. usb_disable_endpoint(dev, i + USB_DIR_IN);
  864. }
  865. dev->toggle[0] = dev->toggle[1] = 0;
  866. /* getting rid of interfaces will disconnect
  867. * any drivers bound to them (a key side effect)
  868. */
  869. if (dev->actconfig) {
  870. for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
  871. struct usb_interface *interface;
  872. /* remove this interface */
  873. interface = dev->actconfig->interface[i];
  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 ret;
  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);