message.c 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * message.c - synchronous message handling
  4. *
  5. * Released under the GPLv2 only.
  6. */
  7. #include <linux/acpi.h>
  8. #include <linux/pci.h> /* for scatterlist macros */
  9. #include <linux/usb.h>
  10. #include <linux/module.h>
  11. #include <linux/of.h>
  12. #include <linux/slab.h>
  13. #include <linux/mm.h>
  14. #include <linux/timer.h>
  15. #include <linux/ctype.h>
  16. #include <linux/nls.h>
  17. #include <linux/device.h>
  18. #include <linux/scatterlist.h>
  19. #include <linux/usb/cdc.h>
  20. #include <linux/usb/quirks.h>
  21. #include <linux/usb/hcd.h> /* for usbcore internals */
  22. #include <linux/usb/of.h>
  23. #include <asm/byteorder.h>
  24. #include "usb.h"
  25. static void cancel_async_set_config(struct usb_device *udev);
  26. struct api_context {
  27. struct completion done;
  28. int status;
  29. };
  30. static void usb_api_blocking_completion(struct urb *urb)
  31. {
  32. struct api_context *ctx = urb->context;
  33. ctx->status = urb->status;
  34. complete(&ctx->done);
  35. }
  36. /*
  37. * Starts urb and waits for completion or timeout. Note that this call
  38. * is NOT interruptible. Many device driver i/o requests should be
  39. * interruptible and therefore these drivers should implement their
  40. * own interruptible routines.
  41. */
  42. static int usb_start_wait_urb(struct urb *urb, int timeout, int *actual_length)
  43. {
  44. struct api_context ctx;
  45. unsigned long expire;
  46. int retval;
  47. init_completion(&ctx.done);
  48. urb->context = &ctx;
  49. urb->actual_length = 0;
  50. retval = usb_submit_urb(urb, GFP_NOIO);
  51. if (unlikely(retval))
  52. goto out;
  53. expire = timeout ? msecs_to_jiffies(timeout) : MAX_SCHEDULE_TIMEOUT;
  54. if (!wait_for_completion_timeout(&ctx.done, expire)) {
  55. usb_kill_urb(urb);
  56. retval = (ctx.status == -ENOENT ? -ETIMEDOUT : ctx.status);
  57. dev_dbg(&urb->dev->dev,
  58. "%s timed out on ep%d%s len=%u/%u\n",
  59. current->comm,
  60. usb_endpoint_num(&urb->ep->desc),
  61. usb_urb_dir_in(urb) ? "in" : "out",
  62. urb->actual_length,
  63. urb->transfer_buffer_length);
  64. } else
  65. retval = ctx.status;
  66. out:
  67. if (actual_length)
  68. *actual_length = urb->actual_length;
  69. usb_free_urb(urb);
  70. return retval;
  71. }
  72. /*-------------------------------------------------------------------*/
  73. /* returns status (negative) or length (positive) */
  74. static int usb_internal_control_msg(struct usb_device *usb_dev,
  75. unsigned int pipe,
  76. struct usb_ctrlrequest *cmd,
  77. void *data, int len, int timeout)
  78. {
  79. struct urb *urb;
  80. int retv;
  81. int length;
  82. urb = usb_alloc_urb(0, GFP_NOIO);
  83. if (!urb)
  84. return -ENOMEM;
  85. usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
  86. len, usb_api_blocking_completion, NULL);
  87. retv = usb_start_wait_urb(urb, timeout, &length);
  88. if (retv < 0)
  89. return retv;
  90. else
  91. return length;
  92. }
  93. /**
  94. * usb_control_msg - Builds a control urb, sends it off and waits for completion
  95. * @dev: pointer to the usb device to send the message to
  96. * @pipe: endpoint "pipe" to send the message to
  97. * @request: USB message request value
  98. * @requesttype: USB message request type value
  99. * @value: USB message value
  100. * @index: USB message index value
  101. * @data: pointer to the data to send
  102. * @size: length in bytes of the data to send
  103. * @timeout: time in msecs to wait for the message to complete before timing
  104. * out (if 0 the wait is forever)
  105. *
  106. * Context: task context, might sleep.
  107. *
  108. * This function sends a simple control message to a specified endpoint and
  109. * waits for the message to complete, or timeout.
  110. *
  111. * Don't use this function from within an interrupt context. If you need
  112. * an asynchronous message, or need to send a message from within interrupt
  113. * context, use usb_submit_urb(). If a thread in your driver uses this call,
  114. * make sure your disconnect() method can wait for it to complete. Since you
  115. * don't have a handle on the URB used, you can't cancel the request.
  116. *
  117. * Return: If successful, the number of bytes transferred. Otherwise, a negative
  118. * error number.
  119. */
  120. int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request,
  121. __u8 requesttype, __u16 value, __u16 index, void *data,
  122. __u16 size, int timeout)
  123. {
  124. struct usb_ctrlrequest *dr;
  125. int ret;
  126. dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
  127. if (!dr)
  128. return -ENOMEM;
  129. dr->bRequestType = requesttype;
  130. dr->bRequest = request;
  131. dr->wValue = cpu_to_le16(value);
  132. dr->wIndex = cpu_to_le16(index);
  133. dr->wLength = cpu_to_le16(size);
  134. ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
  135. /* Linger a bit, prior to the next control message. */
  136. if (dev->quirks & USB_QUIRK_DELAY_CTRL_MSG)
  137. msleep(200);
  138. kfree(dr);
  139. return ret;
  140. }
  141. EXPORT_SYMBOL_GPL(usb_control_msg);
  142. /**
  143. * usb_control_msg_send - Builds a control "send" message, sends it off and waits for completion
  144. * @dev: pointer to the usb device to send the message to
  145. * @endpoint: endpoint to send the message to
  146. * @request: USB message request value
  147. * @requesttype: USB message request type value
  148. * @value: USB message value
  149. * @index: USB message index value
  150. * @driver_data: pointer to the data to send
  151. * @size: length in bytes of the data to send
  152. * @timeout: time in msecs to wait for the message to complete before timing
  153. * out (if 0 the wait is forever)
  154. * @memflags: the flags for memory allocation for buffers
  155. *
  156. * Context: !in_interrupt ()
  157. *
  158. * This function sends a control message to a specified endpoint that is not
  159. * expected to fill in a response (i.e. a "send message") and waits for the
  160. * message to complete, or timeout.
  161. *
  162. * Do not use this function from within an interrupt context. If you need
  163. * an asynchronous message, or need to send a message from within interrupt
  164. * context, use usb_submit_urb(). If a thread in your driver uses this call,
  165. * make sure your disconnect() method can wait for it to complete. Since you
  166. * don't have a handle on the URB used, you can't cancel the request.
  167. *
  168. * The data pointer can be made to a reference on the stack, or anywhere else,
  169. * as it will not be modified at all. This does not have the restriction that
  170. * usb_control_msg() has where the data pointer must be to dynamically allocated
  171. * memory (i.e. memory that can be successfully DMAed to a device).
  172. *
  173. * Return: If successful, 0 is returned, Otherwise, a negative error number.
  174. */
  175. int usb_control_msg_send(struct usb_device *dev, __u8 endpoint, __u8 request,
  176. __u8 requesttype, __u16 value, __u16 index,
  177. const void *driver_data, __u16 size, int timeout,
  178. gfp_t memflags)
  179. {
  180. unsigned int pipe = usb_sndctrlpipe(dev, endpoint);
  181. int ret;
  182. u8 *data = NULL;
  183. if (size) {
  184. data = kmemdup(driver_data, size, memflags);
  185. if (!data)
  186. return -ENOMEM;
  187. }
  188. ret = usb_control_msg(dev, pipe, request, requesttype, value, index,
  189. data, size, timeout);
  190. kfree(data);
  191. if (ret < 0)
  192. return ret;
  193. return 0;
  194. }
  195. EXPORT_SYMBOL_GPL(usb_control_msg_send);
  196. /**
  197. * usb_control_msg_recv - Builds a control "receive" message, sends it off and waits for completion
  198. * @dev: pointer to the usb device to send the message to
  199. * @endpoint: endpoint to send the message to
  200. * @request: USB message request value
  201. * @requesttype: USB message request type value
  202. * @value: USB message value
  203. * @index: USB message index value
  204. * @driver_data: pointer to the data to be filled in by the message
  205. * @size: length in bytes of the data to be received
  206. * @timeout: time in msecs to wait for the message to complete before timing
  207. * out (if 0 the wait is forever)
  208. * @memflags: the flags for memory allocation for buffers
  209. *
  210. * Context: !in_interrupt ()
  211. *
  212. * This function sends a control message to a specified endpoint that is
  213. * expected to fill in a response (i.e. a "receive message") and waits for the
  214. * message to complete, or timeout.
  215. *
  216. * Do not use this function from within an interrupt context. If you need
  217. * an asynchronous message, or need to send a message from within interrupt
  218. * context, use usb_submit_urb(). If a thread in your driver uses this call,
  219. * make sure your disconnect() method can wait for it to complete. Since you
  220. * don't have a handle on the URB used, you can't cancel the request.
  221. *
  222. * The data pointer can be made to a reference on the stack, or anywhere else
  223. * that can be successfully written to. This function does not have the
  224. * restriction that usb_control_msg() has where the data pointer must be to
  225. * dynamically allocated memory (i.e. memory that can be successfully DMAed to a
  226. * device).
  227. *
  228. * The "whole" message must be properly received from the device in order for
  229. * this function to be successful. If a device returns less than the expected
  230. * amount of data, then the function will fail. Do not use this for messages
  231. * where a variable amount of data might be returned.
  232. *
  233. * Return: If successful, 0 is returned, Otherwise, a negative error number.
  234. */
  235. int usb_control_msg_recv(struct usb_device *dev, __u8 endpoint, __u8 request,
  236. __u8 requesttype, __u16 value, __u16 index,
  237. void *driver_data, __u16 size, int timeout,
  238. gfp_t memflags)
  239. {
  240. unsigned int pipe = usb_rcvctrlpipe(dev, endpoint);
  241. int ret;
  242. u8 *data;
  243. if (!size || !driver_data)
  244. return -EINVAL;
  245. data = kmalloc(size, memflags);
  246. if (!data)
  247. return -ENOMEM;
  248. ret = usb_control_msg(dev, pipe, request, requesttype, value, index,
  249. data, size, timeout);
  250. if (ret < 0)
  251. goto exit;
  252. if (ret == size) {
  253. memcpy(driver_data, data, size);
  254. ret = 0;
  255. } else {
  256. ret = -EREMOTEIO;
  257. }
  258. exit:
  259. kfree(data);
  260. return ret;
  261. }
  262. EXPORT_SYMBOL_GPL(usb_control_msg_recv);
  263. /**
  264. * usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion
  265. * @usb_dev: pointer to the usb device to send the message to
  266. * @pipe: endpoint "pipe" to send the message to
  267. * @data: pointer to the data to send
  268. * @len: length in bytes of the data to send
  269. * @actual_length: pointer to a location to put the actual length transferred
  270. * in bytes
  271. * @timeout: time in msecs to wait for the message to complete before
  272. * timing out (if 0 the wait is forever)
  273. *
  274. * Context: task context, might sleep.
  275. *
  276. * This function sends a simple interrupt message to a specified endpoint and
  277. * waits for the message to complete, or timeout.
  278. *
  279. * Don't use this function from within an interrupt context. If you need
  280. * an asynchronous message, or need to send a message from within interrupt
  281. * context, use usb_submit_urb() If a thread in your driver uses this call,
  282. * make sure your disconnect() method can wait for it to complete. Since you
  283. * don't have a handle on the URB used, you can't cancel the request.
  284. *
  285. * Return:
  286. * If successful, 0. Otherwise a negative error number. The number of actual
  287. * bytes transferred will be stored in the @actual_length parameter.
  288. */
  289. int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe,
  290. void *data, int len, int *actual_length, int timeout)
  291. {
  292. return usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout);
  293. }
  294. EXPORT_SYMBOL_GPL(usb_interrupt_msg);
  295. /**
  296. * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
  297. * @usb_dev: pointer to the usb device to send the message to
  298. * @pipe: endpoint "pipe" to send the message to
  299. * @data: pointer to the data to send
  300. * @len: length in bytes of the data to send
  301. * @actual_length: pointer to a location to put the actual length transferred
  302. * in bytes
  303. * @timeout: time in msecs to wait for the message to complete before
  304. * timing out (if 0 the wait is forever)
  305. *
  306. * Context: task context, might sleep.
  307. *
  308. * This function sends a simple bulk message to a specified endpoint
  309. * and waits for the message to complete, or timeout.
  310. *
  311. * Don't use this function from within an interrupt context. If you need
  312. * an asynchronous message, or need to send a message from within interrupt
  313. * context, use usb_submit_urb() If a thread in your driver uses this call,
  314. * make sure your disconnect() method can wait for it to complete. Since you
  315. * don't have a handle on the URB used, you can't cancel the request.
  316. *
  317. * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT ioctl,
  318. * users are forced to abuse this routine by using it to submit URBs for
  319. * interrupt endpoints. We will take the liberty of creating an interrupt URB
  320. * (with the default interval) if the target is an interrupt endpoint.
  321. *
  322. * Return:
  323. * If successful, 0. Otherwise a negative error number. The number of actual
  324. * bytes transferred will be stored in the @actual_length parameter.
  325. *
  326. */
  327. int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
  328. void *data, int len, int *actual_length, int timeout)
  329. {
  330. struct urb *urb;
  331. struct usb_host_endpoint *ep;
  332. ep = usb_pipe_endpoint(usb_dev, pipe);
  333. if (!ep || len < 0)
  334. return -EINVAL;
  335. urb = usb_alloc_urb(0, GFP_KERNEL);
  336. if (!urb)
  337. return -ENOMEM;
  338. if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
  339. USB_ENDPOINT_XFER_INT) {
  340. pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
  341. usb_fill_int_urb(urb, usb_dev, pipe, data, len,
  342. usb_api_blocking_completion, NULL,
  343. ep->desc.bInterval);
  344. } else
  345. usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
  346. usb_api_blocking_completion, NULL);
  347. return usb_start_wait_urb(urb, timeout, actual_length);
  348. }
  349. EXPORT_SYMBOL_GPL(usb_bulk_msg);
  350. /*-------------------------------------------------------------------*/
  351. static void sg_clean(struct usb_sg_request *io)
  352. {
  353. if (io->urbs) {
  354. while (io->entries--)
  355. usb_free_urb(io->urbs[io->entries]);
  356. kfree(io->urbs);
  357. io->urbs = NULL;
  358. }
  359. io->dev = NULL;
  360. }
  361. static void sg_complete(struct urb *urb)
  362. {
  363. unsigned long flags;
  364. struct usb_sg_request *io = urb->context;
  365. int status = urb->status;
  366. spin_lock_irqsave(&io->lock, flags);
  367. /* In 2.5 we require hcds' endpoint queues not to progress after fault
  368. * reports, until the completion callback (this!) returns. That lets
  369. * device driver code (like this routine) unlink queued urbs first,
  370. * if it needs to, since the HC won't work on them at all. So it's
  371. * not possible for page N+1 to overwrite page N, and so on.
  372. *
  373. * That's only for "hard" faults; "soft" faults (unlinks) sometimes
  374. * complete before the HCD can get requests away from hardware,
  375. * though never during cleanup after a hard fault.
  376. */
  377. if (io->status
  378. && (io->status != -ECONNRESET
  379. || status != -ECONNRESET)
  380. && urb->actual_length) {
  381. dev_err(io->dev->bus->controller,
  382. "dev %s ep%d%s scatterlist error %d/%d\n",
  383. io->dev->devpath,
  384. usb_endpoint_num(&urb->ep->desc),
  385. usb_urb_dir_in(urb) ? "in" : "out",
  386. status, io->status);
  387. /* BUG (); */
  388. }
  389. if (io->status == 0 && status && status != -ECONNRESET) {
  390. int i, found, retval;
  391. io->status = status;
  392. /* the previous urbs, and this one, completed already.
  393. * unlink pending urbs so they won't rx/tx bad data.
  394. * careful: unlink can sometimes be synchronous...
  395. */
  396. spin_unlock_irqrestore(&io->lock, flags);
  397. for (i = 0, found = 0; i < io->entries; i++) {
  398. if (!io->urbs[i])
  399. continue;
  400. if (found) {
  401. usb_block_urb(io->urbs[i]);
  402. retval = usb_unlink_urb(io->urbs[i]);
  403. if (retval != -EINPROGRESS &&
  404. retval != -ENODEV &&
  405. retval != -EBUSY &&
  406. retval != -EIDRM)
  407. dev_err(&io->dev->dev,
  408. "%s, unlink --> %d\n",
  409. __func__, retval);
  410. } else if (urb == io->urbs[i])
  411. found = 1;
  412. }
  413. spin_lock_irqsave(&io->lock, flags);
  414. }
  415. /* on the last completion, signal usb_sg_wait() */
  416. io->bytes += urb->actual_length;
  417. io->count--;
  418. if (!io->count)
  419. complete(&io->complete);
  420. spin_unlock_irqrestore(&io->lock, flags);
  421. }
  422. /**
  423. * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
  424. * @io: request block being initialized. until usb_sg_wait() returns,
  425. * treat this as a pointer to an opaque block of memory,
  426. * @dev: the usb device that will send or receive the data
  427. * @pipe: endpoint "pipe" used to transfer the data
  428. * @period: polling rate for interrupt endpoints, in frames or
  429. * (for high speed endpoints) microframes; ignored for bulk
  430. * @sg: scatterlist entries
  431. * @nents: how many entries in the scatterlist
  432. * @length: how many bytes to send from the scatterlist, or zero to
  433. * send every byte identified in the list.
  434. * @mem_flags: SLAB_* flags affecting memory allocations in this call
  435. *
  436. * This initializes a scatter/gather request, allocating resources such as
  437. * I/O mappings and urb memory (except maybe memory used by USB controller
  438. * drivers).
  439. *
  440. * The request must be issued using usb_sg_wait(), which waits for the I/O to
  441. * complete (or to be canceled) and then cleans up all resources allocated by
  442. * usb_sg_init().
  443. *
  444. * The request may be canceled with usb_sg_cancel(), either before or after
  445. * usb_sg_wait() is called.
  446. *
  447. * Return: Zero for success, else a negative errno value.
  448. */
  449. int usb_sg_init(struct usb_sg_request *io, struct usb_device *dev,
  450. unsigned pipe, unsigned period, struct scatterlist *sg,
  451. int nents, size_t length, gfp_t mem_flags)
  452. {
  453. int i;
  454. int urb_flags;
  455. int use_sg;
  456. if (!io || !dev || !sg
  457. || usb_pipecontrol(pipe)
  458. || usb_pipeisoc(pipe)
  459. || nents <= 0)
  460. return -EINVAL;
  461. spin_lock_init(&io->lock);
  462. io->dev = dev;
  463. io->pipe = pipe;
  464. if (dev->bus->sg_tablesize > 0) {
  465. use_sg = true;
  466. io->entries = 1;
  467. } else {
  468. use_sg = false;
  469. io->entries = nents;
  470. }
  471. /* initialize all the urbs we'll use */
  472. io->urbs = kmalloc_array(io->entries, sizeof(*io->urbs), mem_flags);
  473. if (!io->urbs)
  474. goto nomem;
  475. urb_flags = URB_NO_INTERRUPT;
  476. if (usb_pipein(pipe))
  477. urb_flags |= URB_SHORT_NOT_OK;
  478. for_each_sg(sg, sg, io->entries, i) {
  479. struct urb *urb;
  480. unsigned len;
  481. urb = usb_alloc_urb(0, mem_flags);
  482. if (!urb) {
  483. io->entries = i;
  484. goto nomem;
  485. }
  486. io->urbs[i] = urb;
  487. urb->dev = NULL;
  488. urb->pipe = pipe;
  489. urb->interval = period;
  490. urb->transfer_flags = urb_flags;
  491. urb->complete = sg_complete;
  492. urb->context = io;
  493. urb->sg = sg;
  494. if (use_sg) {
  495. /* There is no single transfer buffer */
  496. urb->transfer_buffer = NULL;
  497. urb->num_sgs = nents;
  498. /* A length of zero means transfer the whole sg list */
  499. len = length;
  500. if (len == 0) {
  501. struct scatterlist *sg2;
  502. int j;
  503. for_each_sg(sg, sg2, nents, j)
  504. len += sg2->length;
  505. }
  506. } else {
  507. /*
  508. * Some systems can't use DMA; they use PIO instead.
  509. * For their sakes, transfer_buffer is set whenever
  510. * possible.
  511. */
  512. if (!PageHighMem(sg_page(sg)))
  513. urb->transfer_buffer = sg_virt(sg);
  514. else
  515. urb->transfer_buffer = NULL;
  516. len = sg->length;
  517. if (length) {
  518. len = min_t(size_t, len, length);
  519. length -= len;
  520. if (length == 0)
  521. io->entries = i + 1;
  522. }
  523. }
  524. urb->transfer_buffer_length = len;
  525. }
  526. io->urbs[--i]->transfer_flags &= ~URB_NO_INTERRUPT;
  527. /* transaction state */
  528. io->count = io->entries;
  529. io->status = 0;
  530. io->bytes = 0;
  531. init_completion(&io->complete);
  532. return 0;
  533. nomem:
  534. sg_clean(io);
  535. return -ENOMEM;
  536. }
  537. EXPORT_SYMBOL_GPL(usb_sg_init);
  538. /**
  539. * usb_sg_wait - synchronously execute scatter/gather request
  540. * @io: request block handle, as initialized with usb_sg_init().
  541. * some fields become accessible when this call returns.
  542. *
  543. * Context: task context, might sleep.
  544. *
  545. * This function blocks until the specified I/O operation completes. It
  546. * leverages the grouping of the related I/O requests to get good transfer
  547. * rates, by queueing the requests. At higher speeds, such queuing can
  548. * significantly improve USB throughput.
  549. *
  550. * There are three kinds of completion for this function.
  551. *
  552. * (1) success, where io->status is zero. The number of io->bytes
  553. * transferred is as requested.
  554. * (2) error, where io->status is a negative errno value. The number
  555. * of io->bytes transferred before the error is usually less
  556. * than requested, and can be nonzero.
  557. * (3) cancellation, a type of error with status -ECONNRESET that
  558. * is initiated by usb_sg_cancel().
  559. *
  560. * When this function returns, all memory allocated through usb_sg_init() or
  561. * this call will have been freed. The request block parameter may still be
  562. * passed to usb_sg_cancel(), or it may be freed. It could also be
  563. * reinitialized and then reused.
  564. *
  565. * Data Transfer Rates:
  566. *
  567. * Bulk transfers are valid for full or high speed endpoints.
  568. * The best full speed data rate is 19 packets of 64 bytes each
  569. * per frame, or 1216 bytes per millisecond.
  570. * The best high speed data rate is 13 packets of 512 bytes each
  571. * per microframe, or 52 KBytes per millisecond.
  572. *
  573. * The reason to use interrupt transfers through this API would most likely
  574. * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
  575. * could be transferred. That capability is less useful for low or full
  576. * speed interrupt endpoints, which allow at most one packet per millisecond,
  577. * of at most 8 or 64 bytes (respectively).
  578. *
  579. * It is not necessary to call this function to reserve bandwidth for devices
  580. * under an xHCI host controller, as the bandwidth is reserved when the
  581. * configuration or interface alt setting is selected.
  582. */
  583. void usb_sg_wait(struct usb_sg_request *io)
  584. {
  585. int i;
  586. int entries = io->entries;
  587. /* queue the urbs. */
  588. spin_lock_irq(&io->lock);
  589. i = 0;
  590. while (i < entries && !io->status) {
  591. int retval;
  592. io->urbs[i]->dev = io->dev;
  593. spin_unlock_irq(&io->lock);
  594. retval = usb_submit_urb(io->urbs[i], GFP_NOIO);
  595. switch (retval) {
  596. /* maybe we retrying will recover */
  597. case -ENXIO: /* hc didn't queue this one */
  598. case -EAGAIN:
  599. case -ENOMEM:
  600. retval = 0;
  601. yield();
  602. break;
  603. /* no error? continue immediately.
  604. *
  605. * NOTE: to work better with UHCI (4K I/O buffer may
  606. * need 3K of TDs) it may be good to limit how many
  607. * URBs are queued at once; N milliseconds?
  608. */
  609. case 0:
  610. ++i;
  611. cpu_relax();
  612. break;
  613. /* fail any uncompleted urbs */
  614. default:
  615. io->urbs[i]->status = retval;
  616. dev_dbg(&io->dev->dev, "%s, submit --> %d\n",
  617. __func__, retval);
  618. usb_sg_cancel(io);
  619. }
  620. spin_lock_irq(&io->lock);
  621. if (retval && (io->status == 0 || io->status == -ECONNRESET))
  622. io->status = retval;
  623. }
  624. io->count -= entries - i;
  625. if (io->count == 0)
  626. complete(&io->complete);
  627. spin_unlock_irq(&io->lock);
  628. /* OK, yes, this could be packaged as non-blocking.
  629. * So could the submit loop above ... but it's easier to
  630. * solve neither problem than to solve both!
  631. */
  632. wait_for_completion(&io->complete);
  633. sg_clean(io);
  634. }
  635. EXPORT_SYMBOL_GPL(usb_sg_wait);
  636. /**
  637. * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
  638. * @io: request block, initialized with usb_sg_init()
  639. *
  640. * This stops a request after it has been started by usb_sg_wait().
  641. * It can also prevents one initialized by usb_sg_init() from starting,
  642. * so that call just frees resources allocated to the request.
  643. */
  644. void usb_sg_cancel(struct usb_sg_request *io)
  645. {
  646. unsigned long flags;
  647. int i, retval;
  648. spin_lock_irqsave(&io->lock, flags);
  649. if (io->status || io->count == 0) {
  650. spin_unlock_irqrestore(&io->lock, flags);
  651. return;
  652. }
  653. /* shut everything down */
  654. io->status = -ECONNRESET;
  655. io->count++; /* Keep the request alive until we're done */
  656. spin_unlock_irqrestore(&io->lock, flags);
  657. for (i = io->entries - 1; i >= 0; --i) {
  658. usb_block_urb(io->urbs[i]);
  659. retval = usb_unlink_urb(io->urbs[i]);
  660. if (retval != -EINPROGRESS
  661. && retval != -ENODEV
  662. && retval != -EBUSY
  663. && retval != -EIDRM)
  664. dev_warn(&io->dev->dev, "%s, unlink --> %d\n",
  665. __func__, retval);
  666. }
  667. spin_lock_irqsave(&io->lock, flags);
  668. io->count--;
  669. if (!io->count)
  670. complete(&io->complete);
  671. spin_unlock_irqrestore(&io->lock, flags);
  672. }
  673. EXPORT_SYMBOL_GPL(usb_sg_cancel);
  674. /*-------------------------------------------------------------------*/
  675. /**
  676. * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
  677. * @dev: the device whose descriptor is being retrieved
  678. * @type: the descriptor type (USB_DT_*)
  679. * @index: the number of the descriptor
  680. * @buf: where to put the descriptor
  681. * @size: how big is "buf"?
  682. *
  683. * Context: task context, might sleep.
  684. *
  685. * Gets a USB descriptor. Convenience functions exist to simplify
  686. * getting some types of descriptors. Use
  687. * usb_get_string() or usb_string() for USB_DT_STRING.
  688. * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
  689. * are part of the device structure.
  690. * In addition to a number of USB-standard descriptors, some
  691. * devices also use class-specific or vendor-specific descriptors.
  692. *
  693. * This call is synchronous, and may not be used in an interrupt context.
  694. *
  695. * Return: The number of bytes received on success, or else the status code
  696. * returned by the underlying usb_control_msg() call.
  697. */
  698. int usb_get_descriptor(struct usb_device *dev, unsigned char type,
  699. unsigned char index, void *buf, int size)
  700. {
  701. int i;
  702. int result;
  703. if (size <= 0) /* No point in asking for no data */
  704. return -EINVAL;
  705. memset(buf, 0, size); /* Make sure we parse really received data */
  706. for (i = 0; i < 3; ++i) {
  707. /* retry on length 0 or error; some devices are flakey */
  708. result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  709. USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
  710. (type << 8) + index, 0, buf, size,
  711. USB_CTRL_GET_TIMEOUT);
  712. if (result <= 0 && result != -ETIMEDOUT)
  713. continue;
  714. if (result > 1 && ((u8 *)buf)[1] != type) {
  715. result = -ENODATA;
  716. continue;
  717. }
  718. break;
  719. }
  720. return result;
  721. }
  722. EXPORT_SYMBOL_GPL(usb_get_descriptor);
  723. /**
  724. * usb_get_string - gets a string descriptor
  725. * @dev: the device whose string descriptor is being retrieved
  726. * @langid: code for language chosen (from string descriptor zero)
  727. * @index: the number of the descriptor
  728. * @buf: where to put the string
  729. * @size: how big is "buf"?
  730. *
  731. * Context: task context, might sleep.
  732. *
  733. * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
  734. * in little-endian byte order).
  735. * The usb_string() function will often be a convenient way to turn
  736. * these strings into kernel-printable form.
  737. *
  738. * Strings may be referenced in device, configuration, interface, or other
  739. * descriptors, and could also be used in vendor-specific ways.
  740. *
  741. * This call is synchronous, and may not be used in an interrupt context.
  742. *
  743. * Return: The number of bytes received on success, or else the status code
  744. * returned by the underlying usb_control_msg() call.
  745. */
  746. static int usb_get_string(struct usb_device *dev, unsigned short langid,
  747. unsigned char index, void *buf, int size)
  748. {
  749. int i;
  750. int result;
  751. if (size <= 0) /* No point in asking for no data */
  752. return -EINVAL;
  753. for (i = 0; i < 3; ++i) {
  754. /* retry on length 0 or stall; some devices are flakey */
  755. result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  756. USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
  757. (USB_DT_STRING << 8) + index, langid, buf, size,
  758. USB_CTRL_GET_TIMEOUT);
  759. if (result == 0 || result == -EPIPE)
  760. continue;
  761. if (result > 1 && ((u8 *) buf)[1] != USB_DT_STRING) {
  762. result = -ENODATA;
  763. continue;
  764. }
  765. break;
  766. }
  767. return result;
  768. }
  769. static void usb_try_string_workarounds(unsigned char *buf, int *length)
  770. {
  771. int newlength, oldlength = *length;
  772. for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
  773. if (!isprint(buf[newlength]) || buf[newlength + 1])
  774. break;
  775. if (newlength > 2) {
  776. buf[0] = newlength;
  777. *length = newlength;
  778. }
  779. }
  780. static int usb_string_sub(struct usb_device *dev, unsigned int langid,
  781. unsigned int index, unsigned char *buf)
  782. {
  783. int rc;
  784. /* Try to read the string descriptor by asking for the maximum
  785. * possible number of bytes */
  786. if (dev->quirks & USB_QUIRK_STRING_FETCH_255)
  787. rc = -EIO;
  788. else
  789. rc = usb_get_string(dev, langid, index, buf, 255);
  790. /* If that failed try to read the descriptor length, then
  791. * ask for just that many bytes */
  792. if (rc < 2) {
  793. rc = usb_get_string(dev, langid, index, buf, 2);
  794. if (rc == 2)
  795. rc = usb_get_string(dev, langid, index, buf, buf[0]);
  796. }
  797. if (rc >= 2) {
  798. if (!buf[0] && !buf[1])
  799. usb_try_string_workarounds(buf, &rc);
  800. /* There might be extra junk at the end of the descriptor */
  801. if (buf[0] < rc)
  802. rc = buf[0];
  803. rc = rc - (rc & 1); /* force a multiple of two */
  804. }
  805. if (rc < 2)
  806. rc = (rc < 0 ? rc : -EINVAL);
  807. return rc;
  808. }
  809. static int usb_get_langid(struct usb_device *dev, unsigned char *tbuf)
  810. {
  811. int err;
  812. if (dev->have_langid)
  813. return 0;
  814. if (dev->string_langid < 0)
  815. return -EPIPE;
  816. err = usb_string_sub(dev, 0, 0, tbuf);
  817. /* If the string was reported but is malformed, default to english
  818. * (0x0409) */
  819. if (err == -ENODATA || (err > 0 && err < 4)) {
  820. dev->string_langid = 0x0409;
  821. dev->have_langid = 1;
  822. dev_err(&dev->dev,
  823. "language id specifier not provided by device, defaulting to English\n");
  824. return 0;
  825. }
  826. /* In case of all other errors, we assume the device is not able to
  827. * deal with strings at all. Set string_langid to -1 in order to
  828. * prevent any string to be retrieved from the device */
  829. if (err < 0) {
  830. dev_info(&dev->dev, "string descriptor 0 read error: %d\n",
  831. err);
  832. dev->string_langid = -1;
  833. return -EPIPE;
  834. }
  835. /* always use the first langid listed */
  836. dev->string_langid = tbuf[2] | (tbuf[3] << 8);
  837. dev->have_langid = 1;
  838. dev_dbg(&dev->dev, "default language 0x%04x\n",
  839. dev->string_langid);
  840. return 0;
  841. }
  842. /**
  843. * usb_string - returns UTF-8 version of a string descriptor
  844. * @dev: the device whose string descriptor is being retrieved
  845. * @index: the number of the descriptor
  846. * @buf: where to put the string
  847. * @size: how big is "buf"?
  848. *
  849. * Context: task context, might sleep.
  850. *
  851. * This converts the UTF-16LE encoded strings returned by devices, from
  852. * usb_get_string_descriptor(), to null-terminated UTF-8 encoded ones
  853. * that are more usable in most kernel contexts. Note that this function
  854. * chooses strings in the first language supported by the device.
  855. *
  856. * This call is synchronous, and may not be used in an interrupt context.
  857. *
  858. * Return: length of the string (>= 0) or usb_control_msg status (< 0).
  859. */
  860. int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
  861. {
  862. unsigned char *tbuf;
  863. int err;
  864. if (dev->state == USB_STATE_SUSPENDED)
  865. return -EHOSTUNREACH;
  866. if (size <= 0 || !buf)
  867. return -EINVAL;
  868. buf[0] = 0;
  869. if (index <= 0 || index >= 256)
  870. return -EINVAL;
  871. tbuf = kmalloc(256, GFP_NOIO);
  872. if (!tbuf)
  873. return -ENOMEM;
  874. err = usb_get_langid(dev, tbuf);
  875. if (err < 0)
  876. goto errout;
  877. err = usb_string_sub(dev, dev->string_langid, index, tbuf);
  878. if (err < 0)
  879. goto errout;
  880. size--; /* leave room for trailing NULL char in output buffer */
  881. err = utf16s_to_utf8s((wchar_t *) &tbuf[2], (err - 2) / 2,
  882. UTF16_LITTLE_ENDIAN, buf, size);
  883. buf[err] = 0;
  884. if (tbuf[1] != USB_DT_STRING)
  885. dev_dbg(&dev->dev,
  886. "wrong descriptor type %02x for string %d (\"%s\")\n",
  887. tbuf[1], index, buf);
  888. errout:
  889. kfree(tbuf);
  890. return err;
  891. }
  892. EXPORT_SYMBOL_GPL(usb_string);
  893. /* one UTF-8-encoded 16-bit character has at most three bytes */
  894. #define MAX_USB_STRING_SIZE (127 * 3 + 1)
  895. /**
  896. * usb_cache_string - read a string descriptor and cache it for later use
  897. * @udev: the device whose string descriptor is being read
  898. * @index: the descriptor index
  899. *
  900. * Return: A pointer to a kmalloc'ed buffer containing the descriptor string,
  901. * or %NULL if the index is 0 or the string could not be read.
  902. */
  903. char *usb_cache_string(struct usb_device *udev, int index)
  904. {
  905. char *buf;
  906. char *smallbuf = NULL;
  907. int len;
  908. if (index <= 0)
  909. return NULL;
  910. buf = kmalloc(MAX_USB_STRING_SIZE, GFP_NOIO);
  911. if (buf) {
  912. len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE);
  913. if (len > 0) {
  914. smallbuf = kmalloc(++len, GFP_NOIO);
  915. if (!smallbuf)
  916. return buf;
  917. memcpy(smallbuf, buf, len);
  918. }
  919. kfree(buf);
  920. }
  921. return smallbuf;
  922. }
  923. EXPORT_SYMBOL_GPL(usb_cache_string);
  924. /*
  925. * usb_get_device_descriptor - read the device descriptor
  926. * @udev: the device whose device descriptor should be read
  927. *
  928. * Context: task context, might sleep.
  929. *
  930. * Not exported, only for use by the core. If drivers really want to read
  931. * the device descriptor directly, they can call usb_get_descriptor() with
  932. * type = USB_DT_DEVICE and index = 0.
  933. *
  934. * Returns: a pointer to a dynamically allocated usb_device_descriptor
  935. * structure (which the caller must deallocate), or an ERR_PTR value.
  936. */
  937. struct usb_device_descriptor *usb_get_device_descriptor(struct usb_device *udev)
  938. {
  939. struct usb_device_descriptor *desc;
  940. int ret;
  941. desc = kmalloc(sizeof(*desc), GFP_NOIO);
  942. if (!desc)
  943. return ERR_PTR(-ENOMEM);
  944. ret = usb_get_descriptor(udev, USB_DT_DEVICE, 0, desc, sizeof(*desc));
  945. if (ret == sizeof(*desc))
  946. return desc;
  947. if (ret >= 0)
  948. ret = -EMSGSIZE;
  949. kfree(desc);
  950. return ERR_PTR(ret);
  951. }
  952. /*
  953. * usb_set_isoch_delay - informs the device of the packet transmit delay
  954. * @dev: the device whose delay is to be informed
  955. * Context: task context, might sleep
  956. *
  957. * Since this is an optional request, we don't bother if it fails.
  958. */
  959. int usb_set_isoch_delay(struct usb_device *dev)
  960. {
  961. /* skip hub devices */
  962. if (dev->descriptor.bDeviceClass == USB_CLASS_HUB)
  963. return 0;
  964. /* skip non-SS/non-SSP devices */
  965. if (dev->speed < USB_SPEED_SUPER)
  966. return 0;
  967. return usb_control_msg_send(dev, 0,
  968. USB_REQ_SET_ISOCH_DELAY,
  969. USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_DEVICE,
  970. dev->hub_delay, 0, NULL, 0,
  971. USB_CTRL_SET_TIMEOUT,
  972. GFP_NOIO);
  973. }
  974. /**
  975. * usb_get_status - issues a GET_STATUS call
  976. * @dev: the device whose status is being checked
  977. * @recip: USB_RECIP_*; for device, interface, or endpoint
  978. * @type: USB_STATUS_TYPE_*; for standard or PTM status types
  979. * @target: zero (for device), else interface or endpoint number
  980. * @data: pointer to two bytes of bitmap data
  981. *
  982. * Context: task context, might sleep.
  983. *
  984. * Returns device, interface, or endpoint status. Normally only of
  985. * interest to see if the device is self powered, or has enabled the
  986. * remote wakeup facility; or whether a bulk or interrupt endpoint
  987. * is halted ("stalled").
  988. *
  989. * Bits in these status bitmaps are set using the SET_FEATURE request,
  990. * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
  991. * function should be used to clear halt ("stall") status.
  992. *
  993. * This call is synchronous, and may not be used in an interrupt context.
  994. *
  995. * Returns 0 and the status value in *@data (in host byte order) on success,
  996. * or else the status code from the underlying usb_control_msg() call.
  997. */
  998. int usb_get_status(struct usb_device *dev, int recip, int type, int target,
  999. void *data)
  1000. {
  1001. int ret;
  1002. void *status;
  1003. int length;
  1004. switch (type) {
  1005. case USB_STATUS_TYPE_STANDARD:
  1006. length = 2;
  1007. break;
  1008. case USB_STATUS_TYPE_PTM:
  1009. if (recip != USB_RECIP_DEVICE)
  1010. return -EINVAL;
  1011. length = 4;
  1012. break;
  1013. default:
  1014. return -EINVAL;
  1015. }
  1016. status = kmalloc(length, GFP_KERNEL);
  1017. if (!status)
  1018. return -ENOMEM;
  1019. ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  1020. USB_REQ_GET_STATUS, USB_DIR_IN | recip, USB_STATUS_TYPE_STANDARD,
  1021. target, status, length, USB_CTRL_GET_TIMEOUT);
  1022. switch (ret) {
  1023. case 4:
  1024. if (type != USB_STATUS_TYPE_PTM) {
  1025. ret = -EIO;
  1026. break;
  1027. }
  1028. *(u32 *) data = le32_to_cpu(*(__le32 *) status);
  1029. ret = 0;
  1030. break;
  1031. case 2:
  1032. if (type != USB_STATUS_TYPE_STANDARD) {
  1033. ret = -EIO;
  1034. break;
  1035. }
  1036. *(u16 *) data = le16_to_cpu(*(__le16 *) status);
  1037. ret = 0;
  1038. break;
  1039. default:
  1040. ret = -EIO;
  1041. }
  1042. kfree(status);
  1043. return ret;
  1044. }
  1045. EXPORT_SYMBOL_GPL(usb_get_status);
  1046. /**
  1047. * usb_clear_halt - tells device to clear endpoint halt/stall condition
  1048. * @dev: device whose endpoint is halted
  1049. * @pipe: endpoint "pipe" being cleared
  1050. *
  1051. * Context: task context, might sleep.
  1052. *
  1053. * This is used to clear halt conditions for bulk and interrupt endpoints,
  1054. * as reported by URB completion status. Endpoints that are halted are
  1055. * sometimes referred to as being "stalled". Such endpoints are unable
  1056. * to transmit or receive data until the halt status is cleared. Any URBs
  1057. * queued for such an endpoint should normally be unlinked by the driver
  1058. * before clearing the halt condition, as described in sections 5.7.5
  1059. * and 5.8.5 of the USB 2.0 spec.
  1060. *
  1061. * Note that control and isochronous endpoints don't halt, although control
  1062. * endpoints report "protocol stall" (for unsupported requests) using the
  1063. * same status code used to report a true stall.
  1064. *
  1065. * This call is synchronous, and may not be used in an interrupt context.
  1066. * If a thread in your driver uses this call, make sure your disconnect()
  1067. * method can wait for it to complete.
  1068. *
  1069. * Return: Zero on success, or else the status code returned by the
  1070. * underlying usb_control_msg() call.
  1071. */
  1072. int usb_clear_halt(struct usb_device *dev, int pipe)
  1073. {
  1074. int result;
  1075. int endp = usb_pipeendpoint(pipe);
  1076. if (usb_pipein(pipe))
  1077. endp |= USB_DIR_IN;
  1078. /* we don't care if it wasn't halted first. in fact some devices
  1079. * (like some ibmcam model 1 units) seem to expect hosts to make
  1080. * this request for iso endpoints, which can't halt!
  1081. */
  1082. result = usb_control_msg_send(dev, 0,
  1083. USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
  1084. USB_ENDPOINT_HALT, endp, NULL, 0,
  1085. USB_CTRL_SET_TIMEOUT, GFP_NOIO);
  1086. /* don't un-halt or force to DATA0 except on success */
  1087. if (result)
  1088. return result;
  1089. /* NOTE: seems like Microsoft and Apple don't bother verifying
  1090. * the clear "took", so some devices could lock up if you check...
  1091. * such as the Hagiwara FlashGate DUAL. So we won't bother.
  1092. *
  1093. * NOTE: make sure the logic here doesn't diverge much from
  1094. * the copy in usb-storage, for as long as we need two copies.
  1095. */
  1096. usb_reset_endpoint(dev, endp);
  1097. return 0;
  1098. }
  1099. EXPORT_SYMBOL_GPL(usb_clear_halt);
  1100. static int create_intf_ep_devs(struct usb_interface *intf)
  1101. {
  1102. struct usb_device *udev = interface_to_usbdev(intf);
  1103. struct usb_host_interface *alt = intf->cur_altsetting;
  1104. int i;
  1105. if (intf->ep_devs_created || intf->unregistering)
  1106. return 0;
  1107. for (i = 0; i < alt->desc.bNumEndpoints; ++i)
  1108. (void) usb_create_ep_devs(&intf->dev, &alt->endpoint[i], udev);
  1109. intf->ep_devs_created = 1;
  1110. return 0;
  1111. }
  1112. static void remove_intf_ep_devs(struct usb_interface *intf)
  1113. {
  1114. struct usb_host_interface *alt = intf->cur_altsetting;
  1115. int i;
  1116. if (!intf->ep_devs_created)
  1117. return;
  1118. for (i = 0; i < alt->desc.bNumEndpoints; ++i)
  1119. usb_remove_ep_devs(&alt->endpoint[i]);
  1120. intf->ep_devs_created = 0;
  1121. }
  1122. /**
  1123. * usb_disable_endpoint -- Disable an endpoint by address
  1124. * @dev: the device whose endpoint is being disabled
  1125. * @epaddr: the endpoint's address. Endpoint number for output,
  1126. * endpoint number + USB_DIR_IN for input
  1127. * @reset_hardware: flag to erase any endpoint state stored in the
  1128. * controller hardware
  1129. *
  1130. * Disables the endpoint for URB submission and nukes all pending URBs.
  1131. * If @reset_hardware is set then also deallocates hcd/hardware state
  1132. * for the endpoint.
  1133. */
  1134. void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr,
  1135. bool reset_hardware)
  1136. {
  1137. unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
  1138. struct usb_host_endpoint *ep;
  1139. if (!dev)
  1140. return;
  1141. if (usb_endpoint_out(epaddr)) {
  1142. ep = dev->ep_out[epnum];
  1143. if (reset_hardware && epnum != 0)
  1144. dev->ep_out[epnum] = NULL;
  1145. } else {
  1146. ep = dev->ep_in[epnum];
  1147. if (reset_hardware && epnum != 0)
  1148. dev->ep_in[epnum] = NULL;
  1149. }
  1150. if (ep) {
  1151. ep->enabled = 0;
  1152. usb_hcd_flush_endpoint(dev, ep);
  1153. if (reset_hardware)
  1154. usb_hcd_disable_endpoint(dev, ep);
  1155. }
  1156. }
  1157. /**
  1158. * usb_reset_endpoint - Reset an endpoint's state.
  1159. * @dev: the device whose endpoint is to be reset
  1160. * @epaddr: the endpoint's address. Endpoint number for output,
  1161. * endpoint number + USB_DIR_IN for input
  1162. *
  1163. * Resets any host-side endpoint state such as the toggle bit,
  1164. * sequence number or current window.
  1165. */
  1166. void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr)
  1167. {
  1168. unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
  1169. struct usb_host_endpoint *ep;
  1170. if (usb_endpoint_out(epaddr))
  1171. ep = dev->ep_out[epnum];
  1172. else
  1173. ep = dev->ep_in[epnum];
  1174. if (ep)
  1175. usb_hcd_reset_endpoint(dev, ep);
  1176. }
  1177. EXPORT_SYMBOL_GPL(usb_reset_endpoint);
  1178. /**
  1179. * usb_disable_interface -- Disable all endpoints for an interface
  1180. * @dev: the device whose interface is being disabled
  1181. * @intf: pointer to the interface descriptor
  1182. * @reset_hardware: flag to erase any endpoint state stored in the
  1183. * controller hardware
  1184. *
  1185. * Disables all the endpoints for the interface's current altsetting.
  1186. */
  1187. void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf,
  1188. bool reset_hardware)
  1189. {
  1190. struct usb_host_interface *alt = intf->cur_altsetting;
  1191. int i;
  1192. for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
  1193. usb_disable_endpoint(dev,
  1194. alt->endpoint[i].desc.bEndpointAddress,
  1195. reset_hardware);
  1196. }
  1197. }
  1198. /*
  1199. * usb_disable_device_endpoints -- Disable all endpoints for a device
  1200. * @dev: the device whose endpoints are being disabled
  1201. * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
  1202. */
  1203. static void usb_disable_device_endpoints(struct usb_device *dev, int skip_ep0)
  1204. {
  1205. struct usb_hcd *hcd = bus_to_hcd(dev->bus);
  1206. int i;
  1207. if (hcd->driver->check_bandwidth) {
  1208. /* First pass: Cancel URBs, leave endpoint pointers intact. */
  1209. for (i = skip_ep0; i < 16; ++i) {
  1210. usb_disable_endpoint(dev, i, false);
  1211. usb_disable_endpoint(dev, i + USB_DIR_IN, false);
  1212. }
  1213. /* Remove endpoints from the host controller internal state */
  1214. mutex_lock(hcd->bandwidth_mutex);
  1215. usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
  1216. mutex_unlock(hcd->bandwidth_mutex);
  1217. }
  1218. /* Second pass: remove endpoint pointers */
  1219. for (i = skip_ep0; i < 16; ++i) {
  1220. usb_disable_endpoint(dev, i, true);
  1221. usb_disable_endpoint(dev, i + USB_DIR_IN, true);
  1222. }
  1223. }
  1224. /**
  1225. * usb_disable_device - Disable all the endpoints for a USB device
  1226. * @dev: the device whose endpoints are being disabled
  1227. * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
  1228. *
  1229. * Disables all the device's endpoints, potentially including endpoint 0.
  1230. * Deallocates hcd/hardware state for the endpoints (nuking all or most
  1231. * pending urbs) and usbcore state for the interfaces, so that usbcore
  1232. * must usb_set_configuration() before any interfaces could be used.
  1233. */
  1234. void usb_disable_device(struct usb_device *dev, int skip_ep0)
  1235. {
  1236. int i;
  1237. /* getting rid of interfaces will disconnect
  1238. * any drivers bound to them (a key side effect)
  1239. */
  1240. if (dev->actconfig) {
  1241. /*
  1242. * FIXME: In order to avoid self-deadlock involving the
  1243. * bandwidth_mutex, we have to mark all the interfaces
  1244. * before unregistering any of them.
  1245. */
  1246. for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++)
  1247. dev->actconfig->interface[i]->unregistering = 1;
  1248. for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
  1249. struct usb_interface *interface;
  1250. /* remove this interface if it has been registered */
  1251. interface = dev->actconfig->interface[i];
  1252. if (!device_is_registered(&interface->dev))
  1253. continue;
  1254. dev_dbg(&dev->dev, "unregistering interface %s\n",
  1255. dev_name(&interface->dev));
  1256. remove_intf_ep_devs(interface);
  1257. device_del(&interface->dev);
  1258. }
  1259. /* Now that the interfaces are unbound, nobody should
  1260. * try to access them.
  1261. */
  1262. for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
  1263. put_device(&dev->actconfig->interface[i]->dev);
  1264. dev->actconfig->interface[i] = NULL;
  1265. }
  1266. usb_disable_usb2_hardware_lpm(dev);
  1267. usb_unlocked_disable_lpm(dev);
  1268. usb_disable_ltm(dev);
  1269. dev->actconfig = NULL;
  1270. if (dev->state == USB_STATE_CONFIGURED)
  1271. usb_set_device_state(dev, USB_STATE_ADDRESS);
  1272. }
  1273. dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__,
  1274. skip_ep0 ? "non-ep0" : "all");
  1275. usb_disable_device_endpoints(dev, skip_ep0);
  1276. }
  1277. /**
  1278. * usb_enable_endpoint - Enable an endpoint for USB communications
  1279. * @dev: the device whose interface is being enabled
  1280. * @ep: the endpoint
  1281. * @reset_ep: flag to reset the endpoint state
  1282. *
  1283. * Resets the endpoint state if asked, and sets dev->ep_{in,out} pointers.
  1284. * For control endpoints, both the input and output sides are handled.
  1285. */
  1286. void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep,
  1287. bool reset_ep)
  1288. {
  1289. int epnum = usb_endpoint_num(&ep->desc);
  1290. int is_out = usb_endpoint_dir_out(&ep->desc);
  1291. int is_control = usb_endpoint_xfer_control(&ep->desc);
  1292. if (reset_ep)
  1293. usb_hcd_reset_endpoint(dev, ep);
  1294. if (is_out || is_control)
  1295. dev->ep_out[epnum] = ep;
  1296. if (!is_out || is_control)
  1297. dev->ep_in[epnum] = ep;
  1298. ep->enabled = 1;
  1299. }
  1300. /**
  1301. * usb_enable_interface - Enable all the endpoints for an interface
  1302. * @dev: the device whose interface is being enabled
  1303. * @intf: pointer to the interface descriptor
  1304. * @reset_eps: flag to reset the endpoints' state
  1305. *
  1306. * Enables all the endpoints for the interface's current altsetting.
  1307. */
  1308. void usb_enable_interface(struct usb_device *dev,
  1309. struct usb_interface *intf, bool reset_eps)
  1310. {
  1311. struct usb_host_interface *alt = intf->cur_altsetting;
  1312. int i;
  1313. for (i = 0; i < alt->desc.bNumEndpoints; ++i)
  1314. usb_enable_endpoint(dev, &alt->endpoint[i], reset_eps);
  1315. }
  1316. /**
  1317. * usb_set_interface - Makes a particular alternate setting be current
  1318. * @dev: the device whose interface is being updated
  1319. * @interface: the interface being updated
  1320. * @alternate: the setting being chosen.
  1321. *
  1322. * Context: task context, might sleep.
  1323. *
  1324. * This is used to enable data transfers on interfaces that may not
  1325. * be enabled by default. Not all devices support such configurability.
  1326. * Only the driver bound to an interface may change its setting.
  1327. *
  1328. * Within any given configuration, each interface may have several
  1329. * alternative settings. These are often used to control levels of
  1330. * bandwidth consumption. For example, the default setting for a high
  1331. * speed interrupt endpoint may not send more than 64 bytes per microframe,
  1332. * while interrupt transfers of up to 3KBytes per microframe are legal.
  1333. * Also, isochronous endpoints may never be part of an
  1334. * interface's default setting. To access such bandwidth, alternate
  1335. * interface settings must be made current.
  1336. *
  1337. * Note that in the Linux USB subsystem, bandwidth associated with
  1338. * an endpoint in a given alternate setting is not reserved until an URB
  1339. * is submitted that needs that bandwidth. Some other operating systems
  1340. * allocate bandwidth early, when a configuration is chosen.
  1341. *
  1342. * xHCI reserves bandwidth and configures the alternate setting in
  1343. * usb_hcd_alloc_bandwidth(). If it fails the original interface altsetting
  1344. * may be disabled. Drivers cannot rely on any particular alternate
  1345. * setting being in effect after a failure.
  1346. *
  1347. * This call is synchronous, and may not be used in an interrupt context.
  1348. * Also, drivers must not change altsettings while urbs are scheduled for
  1349. * endpoints in that interface; all such urbs must first be completed
  1350. * (perhaps forced by unlinking). If a thread in your driver uses this call,
  1351. * make sure your disconnect() method can wait for it to complete.
  1352. *
  1353. * Return: Zero on success, or else the status code returned by the
  1354. * underlying usb_control_msg() call.
  1355. */
  1356. int usb_set_interface(struct usb_device *dev, int interface, int alternate)
  1357. {
  1358. struct usb_interface *iface;
  1359. struct usb_host_interface *alt;
  1360. struct usb_hcd *hcd = bus_to_hcd(dev->bus);
  1361. int i, ret, manual = 0;
  1362. unsigned int epaddr;
  1363. unsigned int pipe;
  1364. if (dev->state == USB_STATE_SUSPENDED)
  1365. return -EHOSTUNREACH;
  1366. iface = usb_ifnum_to_if(dev, interface);
  1367. if (!iface) {
  1368. dev_dbg(&dev->dev, "selecting invalid interface %d\n",
  1369. interface);
  1370. return -EINVAL;
  1371. }
  1372. if (iface->unregistering)
  1373. return -ENODEV;
  1374. alt = usb_altnum_to_altsetting(iface, alternate);
  1375. if (!alt) {
  1376. dev_warn(&dev->dev, "selecting invalid altsetting %d\n",
  1377. alternate);
  1378. return -EINVAL;
  1379. }
  1380. /*
  1381. * usb3 hosts configure the interface in usb_hcd_alloc_bandwidth,
  1382. * including freeing dropped endpoint ring buffers.
  1383. * Make sure the interface endpoints are flushed before that
  1384. */
  1385. usb_disable_interface(dev, iface, false);
  1386. /* Make sure we have enough bandwidth for this alternate interface.
  1387. * Remove the current alt setting and add the new alt setting.
  1388. */
  1389. mutex_lock(hcd->bandwidth_mutex);
  1390. /* Disable LPM, and re-enable it once the new alt setting is installed,
  1391. * so that the xHCI driver can recalculate the U1/U2 timeouts.
  1392. */
  1393. if (usb_disable_lpm(dev)) {
  1394. dev_err(&iface->dev, "%s Failed to disable LPM\n", __func__);
  1395. mutex_unlock(hcd->bandwidth_mutex);
  1396. return -ENOMEM;
  1397. }
  1398. /* Changing alt-setting also frees any allocated streams */
  1399. for (i = 0; i < iface->cur_altsetting->desc.bNumEndpoints; i++)
  1400. iface->cur_altsetting->endpoint[i].streams = 0;
  1401. ret = usb_hcd_alloc_bandwidth(dev, NULL, iface->cur_altsetting, alt);
  1402. if (ret < 0) {
  1403. dev_info(&dev->dev, "Not enough bandwidth for altsetting %d\n",
  1404. alternate);
  1405. usb_enable_lpm(dev);
  1406. mutex_unlock(hcd->bandwidth_mutex);
  1407. return ret;
  1408. }
  1409. if (dev->quirks & USB_QUIRK_NO_SET_INTF)
  1410. ret = -EPIPE;
  1411. else
  1412. ret = usb_control_msg_send(dev, 0,
  1413. USB_REQ_SET_INTERFACE,
  1414. USB_RECIP_INTERFACE, alternate,
  1415. interface, NULL, 0, 5000,
  1416. GFP_NOIO);
  1417. /* 9.4.10 says devices don't need this and are free to STALL the
  1418. * request if the interface only has one alternate setting.
  1419. */
  1420. if (ret == -EPIPE && iface->num_altsetting == 1) {
  1421. dev_dbg(&dev->dev,
  1422. "manual set_interface for iface %d, alt %d\n",
  1423. interface, alternate);
  1424. manual = 1;
  1425. } else if (ret) {
  1426. /* Re-instate the old alt setting */
  1427. usb_hcd_alloc_bandwidth(dev, NULL, alt, iface->cur_altsetting);
  1428. usb_enable_lpm(dev);
  1429. mutex_unlock(hcd->bandwidth_mutex);
  1430. return ret;
  1431. }
  1432. mutex_unlock(hcd->bandwidth_mutex);
  1433. /* FIXME drivers shouldn't need to replicate/bugfix the logic here
  1434. * when they implement async or easily-killable versions of this or
  1435. * other "should-be-internal" functions (like clear_halt).
  1436. * should hcd+usbcore postprocess control requests?
  1437. */
  1438. /* prevent submissions using previous endpoint settings */
  1439. if (iface->cur_altsetting != alt) {
  1440. remove_intf_ep_devs(iface);
  1441. usb_remove_sysfs_intf_files(iface);
  1442. }
  1443. usb_disable_interface(dev, iface, true);
  1444. iface->cur_altsetting = alt;
  1445. /* Now that the interface is installed, re-enable LPM. */
  1446. usb_unlocked_enable_lpm(dev);
  1447. /* If the interface only has one altsetting and the device didn't
  1448. * accept the request, we attempt to carry out the equivalent action
  1449. * by manually clearing the HALT feature for each endpoint in the
  1450. * new altsetting.
  1451. */
  1452. if (manual) {
  1453. for (i = 0; i < alt->desc.bNumEndpoints; i++) {
  1454. epaddr = alt->endpoint[i].desc.bEndpointAddress;
  1455. pipe = __create_pipe(dev,
  1456. USB_ENDPOINT_NUMBER_MASK & epaddr) |
  1457. (usb_endpoint_out(epaddr) ?
  1458. USB_DIR_OUT : USB_DIR_IN);
  1459. usb_clear_halt(dev, pipe);
  1460. }
  1461. }
  1462. /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
  1463. *
  1464. * Note:
  1465. * Despite EP0 is always present in all interfaces/AS, the list of
  1466. * endpoints from the descriptor does not contain EP0. Due to its
  1467. * omnipresence one might expect EP0 being considered "affected" by
  1468. * any SetInterface request and hence assume toggles need to be reset.
  1469. * However, EP0 toggles are re-synced for every individual transfer
  1470. * during the SETUP stage - hence EP0 toggles are "don't care" here.
  1471. * (Likewise, EP0 never "halts" on well designed devices.)
  1472. */
  1473. usb_enable_interface(dev, iface, true);
  1474. if (device_is_registered(&iface->dev)) {
  1475. usb_create_sysfs_intf_files(iface);
  1476. create_intf_ep_devs(iface);
  1477. }
  1478. return 0;
  1479. }
  1480. EXPORT_SYMBOL_GPL(usb_set_interface);
  1481. /**
  1482. * usb_reset_configuration - lightweight device reset
  1483. * @dev: the device whose configuration is being reset
  1484. *
  1485. * This issues a standard SET_CONFIGURATION request to the device using
  1486. * the current configuration. The effect is to reset most USB-related
  1487. * state in the device, including interface altsettings (reset to zero),
  1488. * endpoint halts (cleared), and endpoint state (only for bulk and interrupt
  1489. * endpoints). Other usbcore state is unchanged, including bindings of
  1490. * usb device drivers to interfaces.
  1491. *
  1492. * Because this affects multiple interfaces, avoid using this with composite
  1493. * (multi-interface) devices. Instead, the driver for each interface may
  1494. * use usb_set_interface() on the interfaces it claims. Be careful though;
  1495. * some devices don't support the SET_INTERFACE request, and others won't
  1496. * reset all the interface state (notably endpoint state). Resetting the whole
  1497. * configuration would affect other drivers' interfaces.
  1498. *
  1499. * The caller must own the device lock.
  1500. *
  1501. * Return: Zero on success, else a negative error code.
  1502. *
  1503. * If this routine fails the device will probably be in an unusable state
  1504. * with endpoints disabled, and interfaces only partially enabled.
  1505. */
  1506. int usb_reset_configuration(struct usb_device *dev)
  1507. {
  1508. int i, retval;
  1509. struct usb_host_config *config;
  1510. struct usb_hcd *hcd = bus_to_hcd(dev->bus);
  1511. if (dev->state == USB_STATE_SUSPENDED)
  1512. return -EHOSTUNREACH;
  1513. /* caller must have locked the device and must own
  1514. * the usb bus readlock (so driver bindings are stable);
  1515. * calls during probe() are fine
  1516. */
  1517. usb_disable_device_endpoints(dev, 1); /* skip ep0*/
  1518. config = dev->actconfig;
  1519. retval = 0;
  1520. mutex_lock(hcd->bandwidth_mutex);
  1521. /* Disable LPM, and re-enable it once the configuration is reset, so
  1522. * that the xHCI driver can recalculate the U1/U2 timeouts.
  1523. */
  1524. if (usb_disable_lpm(dev)) {
  1525. dev_err(&dev->dev, "%s Failed to disable LPM\n", __func__);
  1526. mutex_unlock(hcd->bandwidth_mutex);
  1527. return -ENOMEM;
  1528. }
  1529. /* xHCI adds all endpoints in usb_hcd_alloc_bandwidth */
  1530. retval = usb_hcd_alloc_bandwidth(dev, config, NULL, NULL);
  1531. if (retval < 0) {
  1532. usb_enable_lpm(dev);
  1533. mutex_unlock(hcd->bandwidth_mutex);
  1534. return retval;
  1535. }
  1536. retval = usb_control_msg_send(dev, 0, USB_REQ_SET_CONFIGURATION, 0,
  1537. config->desc.bConfigurationValue, 0,
  1538. NULL, 0, USB_CTRL_SET_TIMEOUT,
  1539. GFP_NOIO);
  1540. if (retval) {
  1541. usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
  1542. usb_enable_lpm(dev);
  1543. mutex_unlock(hcd->bandwidth_mutex);
  1544. return retval;
  1545. }
  1546. mutex_unlock(hcd->bandwidth_mutex);
  1547. /* re-init hc/hcd interface/endpoint state */
  1548. for (i = 0; i < config->desc.bNumInterfaces; i++) {
  1549. struct usb_interface *intf = config->interface[i];
  1550. struct usb_host_interface *alt;
  1551. alt = usb_altnum_to_altsetting(intf, 0);
  1552. /* No altsetting 0? We'll assume the first altsetting.
  1553. * We could use a GetInterface call, but if a device is
  1554. * so non-compliant that it doesn't have altsetting 0
  1555. * then I wouldn't trust its reply anyway.
  1556. */
  1557. if (!alt)
  1558. alt = &intf->altsetting[0];
  1559. if (alt != intf->cur_altsetting) {
  1560. remove_intf_ep_devs(intf);
  1561. usb_remove_sysfs_intf_files(intf);
  1562. }
  1563. intf->cur_altsetting = alt;
  1564. usb_enable_interface(dev, intf, true);
  1565. if (device_is_registered(&intf->dev)) {
  1566. usb_create_sysfs_intf_files(intf);
  1567. create_intf_ep_devs(intf);
  1568. }
  1569. }
  1570. /* Now that the interfaces are installed, re-enable LPM. */
  1571. usb_unlocked_enable_lpm(dev);
  1572. return 0;
  1573. }
  1574. EXPORT_SYMBOL_GPL(usb_reset_configuration);
  1575. static void usb_release_interface(struct device *dev)
  1576. {
  1577. struct usb_interface *intf = to_usb_interface(dev);
  1578. struct usb_interface_cache *intfc =
  1579. altsetting_to_usb_interface_cache(intf->altsetting);
  1580. kref_put(&intfc->ref, usb_release_interface_cache);
  1581. usb_put_dev(interface_to_usbdev(intf));
  1582. of_node_put(dev->of_node);
  1583. kfree(intf);
  1584. }
  1585. /*
  1586. * usb_deauthorize_interface - deauthorize an USB interface
  1587. *
  1588. * @intf: USB interface structure
  1589. */
  1590. void usb_deauthorize_interface(struct usb_interface *intf)
  1591. {
  1592. struct device *dev = &intf->dev;
  1593. device_lock(dev->parent);
  1594. if (intf->authorized) {
  1595. device_lock(dev);
  1596. intf->authorized = 0;
  1597. device_unlock(dev);
  1598. usb_forced_unbind_intf(intf);
  1599. }
  1600. device_unlock(dev->parent);
  1601. }
  1602. /*
  1603. * usb_authorize_interface - authorize an USB interface
  1604. *
  1605. * @intf: USB interface structure
  1606. */
  1607. void usb_authorize_interface(struct usb_interface *intf)
  1608. {
  1609. struct device *dev = &intf->dev;
  1610. if (!intf->authorized) {
  1611. device_lock(dev);
  1612. intf->authorized = 1; /* authorize interface */
  1613. device_unlock(dev);
  1614. }
  1615. }
  1616. static int usb_if_uevent(const struct device *dev, struct kobj_uevent_env *env)
  1617. {
  1618. const struct usb_device *usb_dev;
  1619. const struct usb_interface *intf;
  1620. const struct usb_host_interface *alt;
  1621. intf = to_usb_interface(dev);
  1622. usb_dev = interface_to_usbdev(intf);
  1623. alt = intf->cur_altsetting;
  1624. if (add_uevent_var(env, "INTERFACE=%d/%d/%d",
  1625. alt->desc.bInterfaceClass,
  1626. alt->desc.bInterfaceSubClass,
  1627. alt->desc.bInterfaceProtocol))
  1628. return -ENOMEM;
  1629. if (add_uevent_var(env,
  1630. "MODALIAS=usb:"
  1631. "v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02Xin%02X",
  1632. le16_to_cpu(usb_dev->descriptor.idVendor),
  1633. le16_to_cpu(usb_dev->descriptor.idProduct),
  1634. le16_to_cpu(usb_dev->descriptor.bcdDevice),
  1635. usb_dev->descriptor.bDeviceClass,
  1636. usb_dev->descriptor.bDeviceSubClass,
  1637. usb_dev->descriptor.bDeviceProtocol,
  1638. alt->desc.bInterfaceClass,
  1639. alt->desc.bInterfaceSubClass,
  1640. alt->desc.bInterfaceProtocol,
  1641. alt->desc.bInterfaceNumber))
  1642. return -ENOMEM;
  1643. return 0;
  1644. }
  1645. const struct device_type usb_if_device_type = {
  1646. .name = "usb_interface",
  1647. .release = usb_release_interface,
  1648. .uevent = usb_if_uevent,
  1649. };
  1650. static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev,
  1651. struct usb_host_config *config,
  1652. u8 inum)
  1653. {
  1654. struct usb_interface_assoc_descriptor *retval = NULL;
  1655. struct usb_interface_assoc_descriptor *intf_assoc;
  1656. int first_intf;
  1657. int last_intf;
  1658. int i;
  1659. for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) {
  1660. intf_assoc = config->intf_assoc[i];
  1661. if (intf_assoc->bInterfaceCount == 0)
  1662. continue;
  1663. first_intf = intf_assoc->bFirstInterface;
  1664. last_intf = first_intf + (intf_assoc->bInterfaceCount - 1);
  1665. if (inum >= first_intf && inum <= last_intf) {
  1666. if (!retval)
  1667. retval = intf_assoc;
  1668. else
  1669. dev_err(&dev->dev, "Interface #%d referenced"
  1670. " by multiple IADs\n", inum);
  1671. }
  1672. }
  1673. return retval;
  1674. }
  1675. /*
  1676. * Internal function to queue a device reset
  1677. * See usb_queue_reset_device() for more details
  1678. */
  1679. static void __usb_queue_reset_device(struct work_struct *ws)
  1680. {
  1681. int rc;
  1682. struct usb_interface *iface =
  1683. container_of(ws, struct usb_interface, reset_ws);
  1684. struct usb_device *udev = interface_to_usbdev(iface);
  1685. rc = usb_lock_device_for_reset(udev, iface);
  1686. if (rc >= 0) {
  1687. usb_reset_device(udev);
  1688. usb_unlock_device(udev);
  1689. }
  1690. usb_put_intf(iface); /* Undo _get_ in usb_queue_reset_device() */
  1691. }
  1692. /*
  1693. * Internal function to set the wireless_status sysfs attribute
  1694. * See usb_set_wireless_status() for more details
  1695. */
  1696. static void __usb_wireless_status_intf(struct work_struct *ws)
  1697. {
  1698. struct usb_interface *iface =
  1699. container_of(ws, struct usb_interface, wireless_status_work);
  1700. device_lock(iface->dev.parent);
  1701. if (iface->sysfs_files_created)
  1702. usb_update_wireless_status_attr(iface);
  1703. device_unlock(iface->dev.parent);
  1704. usb_put_intf(iface); /* Undo _get_ in usb_set_wireless_status() */
  1705. }
  1706. /**
  1707. * usb_set_wireless_status - sets the wireless_status struct member
  1708. * @iface: the interface to modify
  1709. * @status: the new wireless status
  1710. *
  1711. * Set the wireless_status struct member to the new value, and emit
  1712. * sysfs changes as necessary.
  1713. *
  1714. * Returns: 0 on success, -EALREADY if already set.
  1715. */
  1716. int usb_set_wireless_status(struct usb_interface *iface,
  1717. enum usb_wireless_status status)
  1718. {
  1719. if (iface->wireless_status == status)
  1720. return -EALREADY;
  1721. usb_get_intf(iface);
  1722. iface->wireless_status = status;
  1723. schedule_work(&iface->wireless_status_work);
  1724. return 0;
  1725. }
  1726. EXPORT_SYMBOL_GPL(usb_set_wireless_status);
  1727. /*
  1728. * usb_set_configuration - Makes a particular device setting be current
  1729. * @dev: the device whose configuration is being updated
  1730. * @configuration: the configuration being chosen.
  1731. *
  1732. * Context: task context, might sleep. Caller holds device lock.
  1733. *
  1734. * This is used to enable non-default device modes. Not all devices
  1735. * use this kind of configurability; many devices only have one
  1736. * configuration.
  1737. *
  1738. * @configuration is the value of the configuration to be installed.
  1739. * According to the USB spec (e.g. section 9.1.1.5), configuration values
  1740. * must be non-zero; a value of zero indicates that the device in
  1741. * unconfigured. However some devices erroneously use 0 as one of their
  1742. * configuration values. To help manage such devices, this routine will
  1743. * accept @configuration = -1 as indicating the device should be put in
  1744. * an unconfigured state.
  1745. *
  1746. * USB device configurations may affect Linux interoperability,
  1747. * power consumption and the functionality available. For example,
  1748. * the default configuration is limited to using 100mA of bus power,
  1749. * so that when certain device functionality requires more power,
  1750. * and the device is bus powered, that functionality should be in some
  1751. * non-default device configuration. Other device modes may also be
  1752. * reflected as configuration options, such as whether two ISDN
  1753. * channels are available independently; and choosing between open
  1754. * standard device protocols (like CDC) or proprietary ones.
  1755. *
  1756. * Note that a non-authorized device (dev->authorized == 0) will only
  1757. * be put in unconfigured mode.
  1758. *
  1759. * Note that USB has an additional level of device configurability,
  1760. * associated with interfaces. That configurability is accessed using
  1761. * usb_set_interface().
  1762. *
  1763. * This call is synchronous. The calling context must be able to sleep,
  1764. * must own the device lock, and must not hold the driver model's USB
  1765. * bus mutex; usb interface driver probe() methods cannot use this routine.
  1766. *
  1767. * Returns zero on success, or else the status code returned by the
  1768. * underlying call that failed. On successful completion, each interface
  1769. * in the original device configuration has been destroyed, and each one
  1770. * in the new configuration has been probed by all relevant usb device
  1771. * drivers currently known to the kernel.
  1772. */
  1773. int usb_set_configuration(struct usb_device *dev, int configuration)
  1774. {
  1775. int i, ret;
  1776. struct usb_host_config *cp = NULL;
  1777. struct usb_interface **new_interfaces = NULL;
  1778. struct usb_hcd *hcd = bus_to_hcd(dev->bus);
  1779. int n, nintf;
  1780. if (dev->authorized == 0 || configuration == -1)
  1781. configuration = 0;
  1782. else {
  1783. for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
  1784. if (dev->config[i].desc.bConfigurationValue ==
  1785. configuration) {
  1786. cp = &dev->config[i];
  1787. break;
  1788. }
  1789. }
  1790. }
  1791. if ((!cp && configuration != 0))
  1792. return -EINVAL;
  1793. /* The USB spec says configuration 0 means unconfigured.
  1794. * But if a device includes a configuration numbered 0,
  1795. * we will accept it as a correctly configured state.
  1796. * Use -1 if you really want to unconfigure the device.
  1797. */
  1798. if (cp && configuration == 0)
  1799. dev_warn(&dev->dev, "config 0 descriptor??\n");
  1800. /* Allocate memory for new interfaces before doing anything else,
  1801. * so that if we run out then nothing will have changed. */
  1802. n = nintf = 0;
  1803. if (cp) {
  1804. nintf = cp->desc.bNumInterfaces;
  1805. new_interfaces = kmalloc_array(nintf, sizeof(*new_interfaces),
  1806. GFP_NOIO);
  1807. if (!new_interfaces)
  1808. return -ENOMEM;
  1809. for (; n < nintf; ++n) {
  1810. new_interfaces[n] = kzalloc(
  1811. sizeof(struct usb_interface),
  1812. GFP_NOIO);
  1813. if (!new_interfaces[n]) {
  1814. ret = -ENOMEM;
  1815. free_interfaces:
  1816. while (--n >= 0)
  1817. kfree(new_interfaces[n]);
  1818. kfree(new_interfaces);
  1819. return ret;
  1820. }
  1821. }
  1822. i = dev->bus_mA - usb_get_max_power(dev, cp);
  1823. if (i < 0)
  1824. dev_warn(&dev->dev, "new config #%d exceeds power "
  1825. "limit by %dmA\n",
  1826. configuration, -i);
  1827. }
  1828. /* Wake up the device so we can send it the Set-Config request */
  1829. ret = usb_autoresume_device(dev);
  1830. if (ret)
  1831. goto free_interfaces;
  1832. /* if it's already configured, clear out old state first.
  1833. * getting rid of old interfaces means unbinding their drivers.
  1834. */
  1835. if (dev->state != USB_STATE_ADDRESS)
  1836. usb_disable_device(dev, 1); /* Skip ep0 */
  1837. /* Get rid of pending async Set-Config requests for this device */
  1838. cancel_async_set_config(dev);
  1839. /* Make sure we have bandwidth (and available HCD resources) for this
  1840. * configuration. Remove endpoints from the schedule if we're dropping
  1841. * this configuration to set configuration 0. After this point, the
  1842. * host controller will not allow submissions to dropped endpoints. If
  1843. * this call fails, the device state is unchanged.
  1844. */
  1845. mutex_lock(hcd->bandwidth_mutex);
  1846. /* Disable LPM, and re-enable it once the new configuration is
  1847. * installed, so that the xHCI driver can recalculate the U1/U2
  1848. * timeouts.
  1849. */
  1850. if (dev->actconfig && usb_disable_lpm(dev)) {
  1851. dev_err(&dev->dev, "%s Failed to disable LPM\n", __func__);
  1852. mutex_unlock(hcd->bandwidth_mutex);
  1853. ret = -ENOMEM;
  1854. goto free_interfaces;
  1855. }
  1856. ret = usb_hcd_alloc_bandwidth(dev, cp, NULL, NULL);
  1857. if (ret < 0) {
  1858. if (dev->actconfig)
  1859. usb_enable_lpm(dev);
  1860. mutex_unlock(hcd->bandwidth_mutex);
  1861. usb_autosuspend_device(dev);
  1862. goto free_interfaces;
  1863. }
  1864. /*
  1865. * Initialize the new interface structures and the
  1866. * hc/hcd/usbcore interface/endpoint state.
  1867. */
  1868. for (i = 0; i < nintf; ++i) {
  1869. struct usb_interface_cache *intfc;
  1870. struct usb_interface *intf;
  1871. struct usb_host_interface *alt;
  1872. u8 ifnum;
  1873. cp->interface[i] = intf = new_interfaces[i];
  1874. intfc = cp->intf_cache[i];
  1875. intf->altsetting = intfc->altsetting;
  1876. intf->num_altsetting = intfc->num_altsetting;
  1877. intf->authorized = !!HCD_INTF_AUTHORIZED(hcd);
  1878. kref_get(&intfc->ref);
  1879. alt = usb_altnum_to_altsetting(intf, 0);
  1880. /* No altsetting 0? We'll assume the first altsetting.
  1881. * We could use a GetInterface call, but if a device is
  1882. * so non-compliant that it doesn't have altsetting 0
  1883. * then I wouldn't trust its reply anyway.
  1884. */
  1885. if (!alt)
  1886. alt = &intf->altsetting[0];
  1887. ifnum = alt->desc.bInterfaceNumber;
  1888. intf->intf_assoc = find_iad(dev, cp, ifnum);
  1889. intf->cur_altsetting = alt;
  1890. usb_enable_interface(dev, intf, true);
  1891. intf->dev.parent = &dev->dev;
  1892. if (usb_of_has_combined_node(dev)) {
  1893. device_set_of_node_from_dev(&intf->dev, &dev->dev);
  1894. } else {
  1895. intf->dev.of_node = usb_of_get_interface_node(dev,
  1896. configuration, ifnum);
  1897. }
  1898. ACPI_COMPANION_SET(&intf->dev, ACPI_COMPANION(&dev->dev));
  1899. intf->dev.driver = NULL;
  1900. intf->dev.bus = &usb_bus_type;
  1901. intf->dev.type = &usb_if_device_type;
  1902. intf->dev.groups = usb_interface_groups;
  1903. INIT_WORK(&intf->reset_ws, __usb_queue_reset_device);
  1904. INIT_WORK(&intf->wireless_status_work, __usb_wireless_status_intf);
  1905. intf->minor = -1;
  1906. device_initialize(&intf->dev);
  1907. pm_runtime_no_callbacks(&intf->dev);
  1908. dev_set_name(&intf->dev, "%d-%s:%d.%d", dev->bus->busnum,
  1909. dev->devpath, configuration, ifnum);
  1910. usb_get_dev(dev);
  1911. }
  1912. kfree(new_interfaces);
  1913. ret = usb_control_msg_send(dev, 0, USB_REQ_SET_CONFIGURATION, 0,
  1914. configuration, 0, NULL, 0,
  1915. USB_CTRL_SET_TIMEOUT, GFP_NOIO);
  1916. if (ret && cp) {
  1917. /*
  1918. * All the old state is gone, so what else can we do?
  1919. * The device is probably useless now anyway.
  1920. */
  1921. usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
  1922. for (i = 0; i < nintf; ++i) {
  1923. usb_disable_interface(dev, cp->interface[i], true);
  1924. put_device(&cp->interface[i]->dev);
  1925. cp->interface[i] = NULL;
  1926. }
  1927. cp = NULL;
  1928. }
  1929. dev->actconfig = cp;
  1930. mutex_unlock(hcd->bandwidth_mutex);
  1931. if (!cp) {
  1932. usb_set_device_state(dev, USB_STATE_ADDRESS);
  1933. /* Leave LPM disabled while the device is unconfigured. */
  1934. usb_autosuspend_device(dev);
  1935. return ret;
  1936. }
  1937. usb_set_device_state(dev, USB_STATE_CONFIGURED);
  1938. if (cp->string == NULL &&
  1939. !(dev->quirks & USB_QUIRK_CONFIG_INTF_STRINGS))
  1940. cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
  1941. /* Now that the interfaces are installed, re-enable LPM. */
  1942. usb_unlocked_enable_lpm(dev);
  1943. /* Enable LTM if it was turned off by usb_disable_device. */
  1944. usb_enable_ltm(dev);
  1945. /* Now that all the interfaces are set up, register them
  1946. * to trigger binding of drivers to interfaces. probe()
  1947. * routines may install different altsettings and may
  1948. * claim() any interfaces not yet bound. Many class drivers
  1949. * need that: CDC, audio, video, etc.
  1950. */
  1951. for (i = 0; i < nintf; ++i) {
  1952. struct usb_interface *intf = cp->interface[i];
  1953. if (intf->dev.of_node &&
  1954. !of_device_is_available(intf->dev.of_node)) {
  1955. dev_info(&dev->dev, "skipping disabled interface %d\n",
  1956. intf->cur_altsetting->desc.bInterfaceNumber);
  1957. continue;
  1958. }
  1959. dev_dbg(&dev->dev,
  1960. "adding %s (config #%d, interface %d)\n",
  1961. dev_name(&intf->dev), configuration,
  1962. intf->cur_altsetting->desc.bInterfaceNumber);
  1963. device_enable_async_suspend(&intf->dev);
  1964. ret = device_add(&intf->dev);
  1965. if (ret != 0) {
  1966. dev_err(&dev->dev, "device_add(%s) --> %d\n",
  1967. dev_name(&intf->dev), ret);
  1968. continue;
  1969. }
  1970. create_intf_ep_devs(intf);
  1971. }
  1972. usb_autosuspend_device(dev);
  1973. return 0;
  1974. }
  1975. EXPORT_SYMBOL_GPL(usb_set_configuration);
  1976. static LIST_HEAD(set_config_list);
  1977. static DEFINE_SPINLOCK(set_config_lock);
  1978. struct set_config_request {
  1979. struct usb_device *udev;
  1980. int config;
  1981. struct work_struct work;
  1982. struct list_head node;
  1983. };
  1984. /* Worker routine for usb_driver_set_configuration() */
  1985. static void driver_set_config_work(struct work_struct *work)
  1986. {
  1987. struct set_config_request *req =
  1988. container_of(work, struct set_config_request, work);
  1989. struct usb_device *udev = req->udev;
  1990. usb_lock_device(udev);
  1991. spin_lock(&set_config_lock);
  1992. list_del(&req->node);
  1993. spin_unlock(&set_config_lock);
  1994. if (req->config >= -1) /* Is req still valid? */
  1995. usb_set_configuration(udev, req->config);
  1996. usb_unlock_device(udev);
  1997. usb_put_dev(udev);
  1998. kfree(req);
  1999. }
  2000. /* Cancel pending Set-Config requests for a device whose configuration
  2001. * was just changed
  2002. */
  2003. static void cancel_async_set_config(struct usb_device *udev)
  2004. {
  2005. struct set_config_request *req;
  2006. spin_lock(&set_config_lock);
  2007. list_for_each_entry(req, &set_config_list, node) {
  2008. if (req->udev == udev)
  2009. req->config = -999; /* Mark as cancelled */
  2010. }
  2011. spin_unlock(&set_config_lock);
  2012. }
  2013. /**
  2014. * usb_driver_set_configuration - Provide a way for drivers to change device configurations
  2015. * @udev: the device whose configuration is being updated
  2016. * @config: the configuration being chosen.
  2017. * Context: In process context, must be able to sleep
  2018. *
  2019. * Device interface drivers are not allowed to change device configurations.
  2020. * This is because changing configurations will destroy the interface the
  2021. * driver is bound to and create new ones; it would be like a floppy-disk
  2022. * driver telling the computer to replace the floppy-disk drive with a
  2023. * tape drive!
  2024. *
  2025. * Still, in certain specialized circumstances the need may arise. This
  2026. * routine gets around the normal restrictions by using a work thread to
  2027. * submit the change-config request.
  2028. *
  2029. * Return: 0 if the request was successfully queued, error code otherwise.
  2030. * The caller has no way to know whether the queued request will eventually
  2031. * succeed.
  2032. */
  2033. int usb_driver_set_configuration(struct usb_device *udev, int config)
  2034. {
  2035. struct set_config_request *req;
  2036. req = kmalloc(sizeof(*req), GFP_KERNEL);
  2037. if (!req)
  2038. return -ENOMEM;
  2039. req->udev = udev;
  2040. req->config = config;
  2041. INIT_WORK(&req->work, driver_set_config_work);
  2042. spin_lock(&set_config_lock);
  2043. list_add(&req->node, &set_config_list);
  2044. spin_unlock(&set_config_lock);
  2045. usb_get_dev(udev);
  2046. schedule_work(&req->work);
  2047. return 0;
  2048. }
  2049. EXPORT_SYMBOL_GPL(usb_driver_set_configuration);
  2050. /**
  2051. * cdc_parse_cdc_header - parse the extra headers present in CDC devices
  2052. * @hdr: the place to put the results of the parsing
  2053. * @intf: the interface for which parsing is requested
  2054. * @buffer: pointer to the extra headers to be parsed
  2055. * @buflen: length of the extra headers
  2056. *
  2057. * This evaluates the extra headers present in CDC devices which
  2058. * bind the interfaces for data and control and provide details
  2059. * about the capabilities of the device.
  2060. *
  2061. * Return: number of descriptors parsed or -EINVAL
  2062. * if the header is contradictory beyond salvage
  2063. */
  2064. int cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr,
  2065. struct usb_interface *intf,
  2066. u8 *buffer,
  2067. int buflen)
  2068. {
  2069. /* duplicates are ignored */
  2070. struct usb_cdc_union_desc *union_header = NULL;
  2071. /* duplicates are not tolerated */
  2072. struct usb_cdc_header_desc *header = NULL;
  2073. struct usb_cdc_ether_desc *ether = NULL;
  2074. struct usb_cdc_mdlm_detail_desc *detail = NULL;
  2075. struct usb_cdc_mdlm_desc *desc = NULL;
  2076. unsigned int elength;
  2077. int cnt = 0;
  2078. memset(hdr, 0x00, sizeof(struct usb_cdc_parsed_header));
  2079. hdr->phonet_magic_present = false;
  2080. while (buflen > 0) {
  2081. elength = buffer[0];
  2082. if (!elength) {
  2083. dev_err(&intf->dev, "skipping garbage byte\n");
  2084. elength = 1;
  2085. goto next_desc;
  2086. }
  2087. if ((buflen < elength) || (elength < 3)) {
  2088. dev_err(&intf->dev, "invalid descriptor buffer length\n");
  2089. break;
  2090. }
  2091. if (buffer[1] != USB_DT_CS_INTERFACE) {
  2092. dev_err(&intf->dev, "skipping garbage\n");
  2093. goto next_desc;
  2094. }
  2095. switch (buffer[2]) {
  2096. case USB_CDC_UNION_TYPE: /* we've found it */
  2097. if (elength < sizeof(struct usb_cdc_union_desc))
  2098. goto next_desc;
  2099. if (union_header) {
  2100. dev_err(&intf->dev, "More than one union descriptor, skipping ...\n");
  2101. goto next_desc;
  2102. }
  2103. union_header = (struct usb_cdc_union_desc *)buffer;
  2104. break;
  2105. case USB_CDC_COUNTRY_TYPE:
  2106. if (elength < sizeof(struct usb_cdc_country_functional_desc))
  2107. goto next_desc;
  2108. hdr->usb_cdc_country_functional_desc =
  2109. (struct usb_cdc_country_functional_desc *)buffer;
  2110. break;
  2111. case USB_CDC_HEADER_TYPE:
  2112. if (elength != sizeof(struct usb_cdc_header_desc))
  2113. goto next_desc;
  2114. if (header)
  2115. return -EINVAL;
  2116. header = (struct usb_cdc_header_desc *)buffer;
  2117. break;
  2118. case USB_CDC_ACM_TYPE:
  2119. if (elength < sizeof(struct usb_cdc_acm_descriptor))
  2120. goto next_desc;
  2121. hdr->usb_cdc_acm_descriptor =
  2122. (struct usb_cdc_acm_descriptor *)buffer;
  2123. break;
  2124. case USB_CDC_ETHERNET_TYPE:
  2125. if (elength != sizeof(struct usb_cdc_ether_desc))
  2126. goto next_desc;
  2127. if (ether)
  2128. return -EINVAL;
  2129. ether = (struct usb_cdc_ether_desc *)buffer;
  2130. break;
  2131. case USB_CDC_CALL_MANAGEMENT_TYPE:
  2132. if (elength < sizeof(struct usb_cdc_call_mgmt_descriptor))
  2133. goto next_desc;
  2134. hdr->usb_cdc_call_mgmt_descriptor =
  2135. (struct usb_cdc_call_mgmt_descriptor *)buffer;
  2136. break;
  2137. case USB_CDC_DMM_TYPE:
  2138. if (elength < sizeof(struct usb_cdc_dmm_desc))
  2139. goto next_desc;
  2140. hdr->usb_cdc_dmm_desc =
  2141. (struct usb_cdc_dmm_desc *)buffer;
  2142. break;
  2143. case USB_CDC_MDLM_TYPE:
  2144. if (elength < sizeof(struct usb_cdc_mdlm_desc))
  2145. goto next_desc;
  2146. if (desc)
  2147. return -EINVAL;
  2148. desc = (struct usb_cdc_mdlm_desc *)buffer;
  2149. break;
  2150. case USB_CDC_MDLM_DETAIL_TYPE:
  2151. if (elength < sizeof(struct usb_cdc_mdlm_detail_desc))
  2152. goto next_desc;
  2153. if (detail)
  2154. return -EINVAL;
  2155. detail = (struct usb_cdc_mdlm_detail_desc *)buffer;
  2156. break;
  2157. case USB_CDC_NCM_TYPE:
  2158. if (elength < sizeof(struct usb_cdc_ncm_desc))
  2159. goto next_desc;
  2160. hdr->usb_cdc_ncm_desc = (struct usb_cdc_ncm_desc *)buffer;
  2161. break;
  2162. case USB_CDC_MBIM_TYPE:
  2163. if (elength < sizeof(struct usb_cdc_mbim_desc))
  2164. goto next_desc;
  2165. hdr->usb_cdc_mbim_desc = (struct usb_cdc_mbim_desc *)buffer;
  2166. break;
  2167. case USB_CDC_MBIM_EXTENDED_TYPE:
  2168. if (elength < sizeof(struct usb_cdc_mbim_extended_desc))
  2169. break;
  2170. hdr->usb_cdc_mbim_extended_desc =
  2171. (struct usb_cdc_mbim_extended_desc *)buffer;
  2172. break;
  2173. case CDC_PHONET_MAGIC_NUMBER:
  2174. hdr->phonet_magic_present = true;
  2175. break;
  2176. default:
  2177. /*
  2178. * there are LOTS more CDC descriptors that
  2179. * could legitimately be found here.
  2180. */
  2181. dev_dbg(&intf->dev, "Ignoring descriptor: type %02x, length %ud\n",
  2182. buffer[2], elength);
  2183. goto next_desc;
  2184. }
  2185. cnt++;
  2186. next_desc:
  2187. buflen -= elength;
  2188. buffer += elength;
  2189. }
  2190. hdr->usb_cdc_union_desc = union_header;
  2191. hdr->usb_cdc_header_desc = header;
  2192. hdr->usb_cdc_mdlm_detail_desc = detail;
  2193. hdr->usb_cdc_mdlm_desc = desc;
  2194. hdr->usb_cdc_ether_desc = ether;
  2195. return cnt;
  2196. }
  2197. EXPORT_SYMBOL(cdc_parse_cdc_header);