usb_device.c 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922
  1. /*
  2. * LPCUSB, an USB device driver for LPC microcontrollers
  3. * Copyright (C) 2006 Bertrik Sikken (bertrik@sikken.nl)
  4. * Copyright (c) 2016 Intel Corporation
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. The name of the author may not be used to endorse or promote products
  15. * derived from this software without specific prior written permission.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  18. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  19. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  20. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  21. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  22. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  23. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  24. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  26. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. */
  28. /**
  29. * @file
  30. * @brief USB device core layer
  31. *
  32. * This module handles control transfer handler, standard request handler and
  33. * USB Interface for customer application.
  34. *
  35. * Control transfers handler is normally installed on the
  36. * endpoint 0 callback.
  37. *
  38. * Control transfers can be of the following type:
  39. * 0 Standard;
  40. * 1 Class;
  41. * 2 Vendor;
  42. * 3 Reserved.
  43. *
  44. * A callback can be installed for each of these control transfers using
  45. * usb_register_request_handler.
  46. * When an OUT request arrives, data is collected in the data store provided
  47. * with the usb_register_request_handler call. When the transfer is done, the
  48. * callback is called.
  49. * When an IN request arrives, the callback is called immediately to either
  50. * put the control transfer data in the data store, or to get a pointer to
  51. * control transfer data. The data is then packetized and sent to the host.
  52. *
  53. * Standard request handler handles the 'chapter 9' processing, specifically
  54. * the standard device requests in table 9-3 from the universal serial bus
  55. * specification revision 2.0
  56. */
  57. #include <errno.h>
  58. #include <stddef.h>
  59. #include <sys/util.h>
  60. #include <sys/byteorder.h>
  61. #include <init.h>
  62. #if defined(USB_VUSB_EN_GPIO)
  63. #include <gpio.h>
  64. #endif
  65. #include <usb/usb_device.h>
  66. #include <drivers/usb/usb_dc.h>
  67. #include <drivers/usb/usb.h>
  68. #include <usb/usbstruct.h>
  69. #include <usb/usb_common.h>
  70. #include <usb/bos.h>
  71. #include <string.h>
  72. #include <logging/log.h>
  73. #define LOG_LEVEL CONFIG_SYS_LOG_USB_DEVICE_LEVEL
  74. LOG_MODULE_REGISTER(usb_device);
  75. #define MAX_DESC_HANDLERS 4 /** Device, interface, endpoint, other */
  76. /* general descriptor field offsets */
  77. #define DESC_bLength 0 /** Length offset */
  78. #define DESC_bDescriptorType 1 /** Descriptor type offset */
  79. /* config descriptor field offsets */
  80. #define CONF_DESC_wTotalLength 2 /** Total length offset */
  81. #define CONF_DESC_bConfigurationValue 5 /** Configuration value offset */
  82. #define CONF_DESC_bmAttributes 7 /** configuration characteristics */
  83. /* interface descriptor field offsets */
  84. #define INTF_DESC_bInterfaceNumber 2 /** Interface number offset */
  85. #define INTF_DESC_bAlternateSetting 3 /** Alternate setting offset */
  86. /* endpoint descriptor field offsets */
  87. #define ENDP_DESC_bEndpointAddress 2 /** Endpoint address offset */
  88. #define ENDP_DESC_bmAttributes 3 /** Bulk or interrupt? */
  89. #define ENDP_DESC_wMaxPacketSize 4 /** Maximum packet size offset */
  90. #define MAX_NUM_REQ_HANDLERS 4
  91. #define MAX_STD_REQ_MSG_SIZE 8
  92. #define MAX_NUM_TRANSFERS 4 /** Max number of parallel transfers */
  93. /* Default USB control EP, always 0 and 0x80 */
  94. #define USB_CONTROL_OUT_EP0 0
  95. #define USB_CONTROL_IN_EP0 0x80
  96. /* bound the USB descriptor structs */
  97. static const struct usb_cfg_data *usb_cfg_data_buf[CONFIG_USB_COMPOSITE_DEVICE_CLASS_NUM];
  98. struct usb_transfer_data {
  99. /** endpoint associated to the transfer */
  100. u8_t ep;
  101. /** Transfer status */
  102. int status;
  103. /** Transfer read/write buffer */
  104. u8_t *buffer;
  105. /** Transfer buffer size */
  106. size_t bsize;
  107. /** Transferred size */
  108. size_t tsize;
  109. /** Transfer callback */
  110. usb_transfer_callback cb;
  111. /** Transfer caller private data */
  112. void *priv;
  113. /** Transfer synchronization semaphore */
  114. struct k_sem sem;
  115. /** Transfer read/write work */
  116. struct k_work work;
  117. /** Transfer flags */
  118. unsigned int flags;
  119. };
  120. #ifdef CONFIG_USB_DEVICE_TRANSFER
  121. static void usb_transfer_work(struct k_work *item);
  122. #endif
  123. static struct usb_dev_priv {
  124. /** Setup packet */
  125. struct usb_setup_packet setup;
  126. /** Pointer to data buffer */
  127. u8_t *data_buf;
  128. /** Eemaining bytes in buffer */
  129. s32_t data_buf_residue;
  130. /** Total length of control transfer */
  131. s32_t data_buf_len;
  132. /** Installed custom request handler */
  133. usb_request_handler custom_req_handler;
  134. /** USB stack status clalback */
  135. usb_status_callback status_callback;
  136. /** Pointer to registered descriptors */
  137. const u8_t *descriptors;
  138. /** Pointer to registered full-speed descriptors */
  139. const u8_t *fs_descriptors;
  140. /** Pointer to registered high-speed descriptors */
  141. const u8_t *hs_descriptors;
  142. /** Array of installed request handler callbacks */
  143. usb_request_handler req_handlers[MAX_NUM_REQ_HANDLERS];
  144. /* Buffer used for storing standard, class and vendor request data */
  145. u8_t req_data[CONFIG_USB_REQUEST_BUFFER_SIZE];
  146. /** Variable to check whether the usb has been enabled */
  147. bool enabled;
  148. /** Currently selected configuration */
  149. u8_t configuration;
  150. /** Remote wakeup feature status */
  151. bool remote_wakeup;
  152. /** Zero-length packet for control-transfer */
  153. bool zero;
  154. /*
  155. * HACK: Add to let the upper layer take care of control transfer
  156. * to support extend function.
  157. *
  158. * Restriction:
  159. * 1. data length = setup->wLength
  160. * 2. data length <= MAX_PACKET_SIZE0.
  161. */
  162. bool upper_ctrl;
  163. #ifdef CONFIG_USB_DEVICE_TRANSFER
  164. /** Transfer list */
  165. struct usb_transfer_data transfer[MAX_NUM_TRANSFERS];
  166. #endif
  167. u8_t unconfigured; /* 1: if set configuration 0 */
  168. } usb_dev;
  169. /*
  170. * @brief print the contents of a setup packet
  171. *
  172. * @param [in] setup The setup packet
  173. *
  174. */
  175. static void usb_print_setup(struct usb_setup_packet *setup)
  176. {
  177. /* avoid compiler warning if LOG_DBG is not defined */
  178. ARG_UNUSED(setup);
  179. LOG_DBG("SETUP\n");
  180. LOG_DBG("%x %x %x %x %x\n",
  181. setup->bmRequestType,
  182. setup->bRequest,
  183. sys_le16_to_cpu(setup->wValue),
  184. sys_le16_to_cpu(setup->wIndex),
  185. sys_le16_to_cpu(setup->wLength));
  186. }
  187. /*
  188. * @brief handle a request by calling one of the installed request handlers
  189. *
  190. * Local function to handle a request by calling one of the installed request
  191. * handlers. In case of data going from host to device, the data is at *ppbData.
  192. * In case of data going from device to host, the handler can either choose to
  193. * write its data at *ppbData or update the data pointer.
  194. *
  195. * @param [in] setup The setup packet
  196. * @param [in,out] len Pointer to data length
  197. * @param [in,out] data Data buffer
  198. *
  199. * @return true if the request was handles successfully
  200. */
  201. static bool usb_handle_request(struct usb_setup_packet *setup,
  202. s32_t *len, u8_t **data)
  203. {
  204. u32_t type = REQTYPE_GET_TYPE(setup->bmRequestType);
  205. usb_request_handler handler = usb_dev.req_handlers[type];
  206. LOG_DBG("** %d **\n", type);
  207. if (type >= MAX_NUM_REQ_HANDLERS) {
  208. LOG_DBG("Error Incorrect iType %d\n", type);
  209. return false;
  210. }
  211. if (handler == NULL) {
  212. LOG_DBG("No handler for reqtype %d\n", type);
  213. return false;
  214. }
  215. if ((*handler)(setup, len, data) < 0) {
  216. LOG_DBG("Handler Error %d\n", type);
  217. usb_print_setup(setup);
  218. return false;
  219. }
  220. return true;
  221. }
  222. /*
  223. * @brief send next chunk of data (possibly 0 bytes) to host
  224. *
  225. * @return N/A
  226. */
  227. static void usb_data_to_host(void)
  228. {
  229. u32_t chunk = MIN(MAX_PACKET_SIZE0, usb_dev.data_buf_residue);
  230. /*Always EP0 for control*/
  231. usb_dc_ep_write(0x80, usb_dev.data_buf, chunk, &chunk);
  232. usb_dev.data_buf += chunk;
  233. usb_dev.data_buf_residue -= chunk;
  234. }
  235. /*
  236. * @brief handle IN/OUT transfers on EP0
  237. *
  238. * @param [in] ep Endpoint address
  239. * @param [in] ep_status Endpoint status
  240. *
  241. * @return N/A
  242. */
  243. static void usb_handle_control_transfer(u8_t ep,
  244. enum usb_dc_ep_cb_status_code ep_status)
  245. {
  246. u32_t chunk = 0;
  247. struct usb_setup_packet *setup = &usb_dev.setup;
  248. LOG_DBG("ep %x, status %x\n", ep, ep_status);
  249. if (ep == USB_CONTROL_OUT_EP0 && ep_status == USB_DC_EP_SETUP) {
  250. u16_t length;
  251. /*
  252. * OUT transfer, Setup packet,
  253. * reset request message state machine
  254. */
  255. if (usb_dc_ep_read(ep,
  256. (u8_t *)setup, sizeof(*setup), NULL) < 0) {
  257. LOG_DBG("Read Setup Packet failed\n");
  258. usb_dc_ep_set_stall(USB_CONTROL_IN_EP0);
  259. return;
  260. }
  261. length = sys_le16_to_cpu(setup->wLength);
  262. if (length > CONFIG_USB_REQUEST_BUFFER_SIZE) {
  263. if (REQTYPE_GET_DIR(setup->bmRequestType)
  264. == REQTYPE_DIR_TO_HOST) {
  265. LOG_DBG("length 0x%x(0x%x) too small\n",
  266. length,
  267. CONFIG_USB_REQUEST_BUFFER_SIZE);
  268. } else {
  269. LOG_ERR("Request buffer too small\n");
  270. usb_dc_ep_set_stall(USB_CONTROL_IN_EP0);
  271. usb_dc_ep_set_stall(USB_CONTROL_OUT_EP0);
  272. return;
  273. }
  274. }
  275. usb_dev.data_buf = usb_dev.req_data;
  276. usb_dev.data_buf_residue = length;
  277. usb_dev.data_buf_len = length;
  278. if (length &&
  279. REQTYPE_GET_DIR(setup->bmRequestType)
  280. == REQTYPE_DIR_TO_DEVICE) {
  281. return;
  282. }
  283. /* Ask installed handler to process request */
  284. if (!usb_handle_request(setup,
  285. &usb_dev.data_buf_len, &usb_dev.data_buf)) {
  286. LOG_DBG("usb_handle_request failed\n");
  287. usb_dc_ep_set_stall(USB_CONTROL_IN_EP0);
  288. return;
  289. }
  290. if ((usb_dev.data_buf_len == 0) &&
  291. (length != 0) &&
  292. (REQTYPE_GET_DIR(setup->bmRequestType)
  293. == REQTYPE_DIR_TO_HOST)) {
  294. usb_dev.upper_ctrl = true;
  295. return;
  296. }
  297. /* Send smallest of requested and offered length */
  298. usb_dev.data_buf_residue = MIN(usb_dev.data_buf_len, length);
  299. /* Check for zero-length packet */
  300. if ((usb_dev.data_buf_residue < length) &&
  301. (usb_dev.data_buf_residue % MAX_PACKET_SIZE0 == 0)) {
  302. usb_dev.zero = true;
  303. } else {
  304. usb_dev.zero = false;
  305. }
  306. /* Send first part (possibly a zero-length status message) */
  307. usb_data_to_host();
  308. } else if (ep == USB_CONTROL_OUT_EP0) {
  309. /* OUT transfer, data or status packets */
  310. if (usb_dev.data_buf_residue <= 0) {
  311. /* absorb zero-length status message */
  312. if (usb_dc_ep_read(USB_CONTROL_OUT_EP0,
  313. usb_dev.data_buf, 0, &chunk) < 0) {
  314. LOG_DBG("Read DATA Packet failed\n");
  315. usb_dc_ep_set_stall(USB_CONTROL_IN_EP0);
  316. }
  317. return;
  318. }
  319. if (usb_dc_ep_read(USB_CONTROL_OUT_EP0,
  320. usb_dev.data_buf,
  321. usb_dev.data_buf_residue, &chunk) < 0) {
  322. LOG_DBG("Read DATA Packet failed\n");
  323. usb_dc_ep_set_stall(USB_CONTROL_IN_EP0);
  324. usb_dc_ep_set_stall(USB_CONTROL_OUT_EP0);
  325. return;
  326. }
  327. usb_dev.data_buf += chunk;
  328. usb_dev.data_buf_residue -= chunk;
  329. if (usb_dev.data_buf_residue == 0) {
  330. /* Received all, send data to handler */
  331. usb_dev.data_buf = usb_dev.req_data;
  332. if (!usb_handle_request(setup,
  333. &usb_dev.data_buf_len, &usb_dev.data_buf)) {
  334. LOG_DBG("usb_handle_request1 failed\n");
  335. usb_dc_ep_set_stall(USB_CONTROL_IN_EP0);
  336. return;
  337. }
  338. /*Send status to host*/
  339. LOG_DBG(">> usb_data_to_host(2)\n");
  340. usb_data_to_host();
  341. }
  342. } else if (ep == USB_CONTROL_IN_EP0) {
  343. /* Avoid redundant data transfer */
  344. if (usb_dev.upper_ctrl) {
  345. usb_dev.upper_ctrl = false;
  346. usb_dev.data_buf_residue = 0;
  347. return;
  348. }
  349. if (usb_dev.zero && usb_dev.data_buf_residue == 0) {
  350. LOG_DBG("send zero-length packet\n");
  351. usb_data_to_host();
  352. usb_dev.zero = false;
  353. }
  354. /* Send more data if available */
  355. if (usb_dev.data_buf_residue != 0) {
  356. usb_data_to_host();
  357. }
  358. } else {
  359. __ASSERT_NO_MSG(false);
  360. }
  361. }
  362. /*
  363. * @brief register a callback for handling requests
  364. *
  365. * @param [in] type Type of request, e.g. REQTYPE_TYPE_STANDARD
  366. * @param [in] handler Callback function pointer
  367. *
  368. * @return N/A
  369. */
  370. static void usb_register_request_handler(s32_t type,
  371. usb_request_handler handler)
  372. {
  373. usb_dev.req_handlers[type] = handler;
  374. }
  375. /*
  376. * @brief register full-speed/high-speed USB descriptors
  377. *
  378. * @return N/A
  379. */
  380. void usb_device_register_descriptors(const u8_t *usb_fs_descriptors,
  381. const u8_t *usb_hs_descriptors)
  382. {
  383. usb_dev.fs_descriptors = usb_fs_descriptors;
  384. usb_dev.hs_descriptors = usb_hs_descriptors;
  385. }
  386. #define STRING_LENGTH(s) (strlen(s) * 2)
  387. static u8_t str_desc_buf[CONFIG_USB_DEVICE_STRING_DESC_MAX_LEN*2 + 2];
  388. static u8_t manufacturer_str_ptr[CONFIG_USB_DEVICE_STRING_DESC_MAX_LEN];
  389. static u8_t product_str_ptr[CONFIG_USB_DEVICE_STRING_DESC_MAX_LEN];
  390. static u8_t dev_sn_str_ptr[CONFIG_USB_DEVICE_STRING_DESC_MAX_LEN];
  391. int usb_device_register_string_descriptor(enum usb_device_str_desc type,
  392. u8_t *str_dat, u8_t str_len)
  393. {
  394. u8_t *str_array[3] = {"manufacture_str", "product_str", "dev_sn_str"};
  395. if (str_len > CONFIG_USB_DEVICE_STRING_DESC_MAX_LEN) {
  396. int index = type - 1;
  397. if(index < 0){
  398. index = 0;
  399. }
  400. LOG_ERR("%s : %s is more than %d bytes!\n", str_array[index],
  401. str_dat, CONFIG_USB_DEVICE_STRING_DESC_MAX_LEN);
  402. return -EINVAL;
  403. }
  404. switch (type) {
  405. case MANUFACTURE_STR_DESC:
  406. memcpy(manufacturer_str_ptr, str_dat, strlen(str_dat));
  407. break;
  408. case PRODUCT_STR_DESC:
  409. memcpy(product_str_ptr, str_dat, strlen(str_dat));
  410. break;
  411. case DEV_SN_DESC:
  412. memcpy(dev_sn_str_ptr, str_dat, strlen(str_dat));
  413. break;
  414. default:
  415. LOG_ERR("Unknown_Type\n");
  416. return -EINVAL;
  417. }
  418. return 0;
  419. }
  420. static void change_strdesc_to_unicode(u8_t *str_desc, u8_t *unicode_buf)
  421. {
  422. for (u8_t i = 2, j = 0; i < unicode_buf[0]; i++) {
  423. if (i%2 == 0) {
  424. unicode_buf[i] = str_desc[j++];
  425. } else {
  426. unicode_buf[i] = 0;
  427. }
  428. }
  429. }
  430. static void usb_process_str_des(u8_t *des_ptr)
  431. {
  432. memset(str_desc_buf, 0, sizeof(str_desc_buf));
  433. str_desc_buf[0] = STRING_LENGTH(des_ptr) + 2;
  434. str_desc_buf[1] = USB_STRING_DESC;
  435. if(str_desc_buf[0] > sizeof(str_desc_buf)) {
  436. str_desc_buf[0] = sizeof(str_desc_buf);
  437. }
  438. change_strdesc_to_unicode(des_ptr, str_desc_buf);
  439. }
  440. static inline bool device_qual(u8_t **data)
  441. {
  442. struct usb_qualifier_descriptor *qual =
  443. (struct usb_qualifier_descriptor *)*data;
  444. struct usb_device_descriptor *desc =
  445. (struct usb_device_descriptor *)(usb_dev.descriptors);
  446. if ((usb_dc_maxspeed() < USB_SPEED_HIGH) ||
  447. (usb_dc_speed() >= USB_SPEED_SUPER)) {
  448. return false;
  449. }
  450. qual->bLength = sizeof(*qual);
  451. qual->bDescriptorType = DESC_DEVICE_QUALIFIER;
  452. /* POLICY: same bcdUSB and device type info at both speeds */
  453. qual->bcdUSB = sys_cpu_to_le16(USB_2_0),
  454. qual->bDeviceClass = desc->bDeviceClass;
  455. qual->bDeviceSubClass = desc->bDeviceSubClass;
  456. qual->bDeviceProtocol = desc->bDeviceProtocol;
  457. /* ASSUME same EP0 fifo size at both speeds */
  458. qual->bMaxPacketSize0 = MAX_PACKET_SIZE0;
  459. qual->bNumConfigurations = 1;
  460. qual->bRESERVED = 0;
  461. return true;
  462. }
  463. static inline bool other_speed(u8_t **data, s32_t *len, u8_t index)
  464. {
  465. u8_t *p = NULL;
  466. enum usb_device_speed speed = usb_dc_speed();
  467. if (usb_dc_maxspeed() < USB_SPEED_HIGH) {
  468. return false;
  469. }
  470. switch (speed) {
  471. case USB_SPEED_HIGH:
  472. p = (u8_t *)usb_dev.hs_descriptors;
  473. break;
  474. case USB_SPEED_FULL:
  475. p = (u8_t *)usb_dev.fs_descriptors;
  476. break;
  477. default:
  478. return false;
  479. }
  480. /* FIXME: not implemented yet */
  481. return false;
  482. }
  483. /*
  484. * @brief get specified USB descriptor
  485. *
  486. * This function parses the list of installed USB descriptors and attempts
  487. * to find the specified USB descriptor.
  488. *
  489. * @param [in] type_index Type and index of the descriptor
  490. * @param [in] lang_id Language ID of the descriptor (currently unused)
  491. * @param [out] len Descriptor length
  492. * @param [out] data Descriptor data
  493. *
  494. * @return true if the descriptor was found, false otherwise
  495. */
  496. static bool usb_get_descriptor(u16_t type_index, u16_t lang_id,
  497. s32_t *len, u8_t **data)
  498. {
  499. u8_t type = 0;
  500. u8_t index = 0;
  501. u8_t *p = NULL;
  502. s32_t cur_index = 0;
  503. bool found = false;
  504. /*Avoid compiler warning until this is used for something*/
  505. ARG_UNUSED(lang_id);
  506. type = GET_DESC_TYPE(type_index);
  507. index = GET_DESC_INDEX(type_index);
  508. if (type == DESC_STRING) {
  509. switch (index) {
  510. case LANGUAGE_ID_STR:
  511. memset(str_desc_buf, 0, sizeof(str_desc_buf));
  512. str_desc_buf[0] = 0x04;
  513. str_desc_buf[1] = 0x03;
  514. str_desc_buf[2] = 0x09;
  515. str_desc_buf[3] = 0x04;
  516. *data = str_desc_buf;
  517. *len = 4;
  518. break;
  519. case MANUFACTURE_STR_DESC:
  520. usb_process_str_des(manufacturer_str_ptr);
  521. *data = str_desc_buf;
  522. *len = str_desc_buf[0];
  523. break;
  524. case PRODUCT_STR_DESC:
  525. usb_process_str_des(product_str_ptr);
  526. *data = str_desc_buf;
  527. *len = str_desc_buf[0];
  528. break;
  529. case DEV_SN_DESC:
  530. usb_process_str_des(dev_sn_str_ptr);
  531. *data = str_desc_buf;
  532. *len = str_desc_buf[0];
  533. break;
  534. default:
  535. break;
  536. }
  537. return true;
  538. }
  539. /*
  540. * Invalid types of descriptors,
  541. * see USB Spec. Revision 2.0, 9.4.3 Get Descriptor
  542. */
  543. if ((type == DESC_INTERFACE) || (type == DESC_ENDPOINT) ||
  544. (type > DESC_OTHER_SPEED)) {
  545. return false;
  546. }
  547. switch (type) {
  548. case DESC_DEVICE_QUALIFIER:
  549. *len = sizeof(struct usb_qualifier_descriptor);
  550. return device_qual(data);
  551. case DESC_OTHER_SPEED:
  552. return other_speed(data, len, index);
  553. default:
  554. break;
  555. }
  556. p = (u8_t *)usb_dev.descriptors;
  557. cur_index = 0;
  558. while (p[DESC_bLength] != 0) {
  559. if (p[DESC_bDescriptorType] == type) {
  560. if (cur_index == index) {
  561. found = true;
  562. break;
  563. }
  564. cur_index++;
  565. }
  566. /* skip to next descriptor */
  567. p += p[DESC_bLength];
  568. }
  569. if (found) {
  570. /* set data pointer */
  571. *data = p;
  572. /* get length from structure */
  573. if (type == DESC_CONFIGURATION) {
  574. /* configuration descriptor is an
  575. * exception, length is at offset
  576. * 2 and 3
  577. */
  578. *len = (p[CONF_DESC_wTotalLength]) |
  579. (p[CONF_DESC_wTotalLength + 1] << 8);
  580. } else {
  581. /* normally length is at offset 0 */
  582. *len = p[DESC_bLength];
  583. }
  584. } else {
  585. /* nothing found */
  586. LOG_DBG("Desc %x not found!\n", type_index);
  587. }
  588. return found;
  589. }
  590. /*
  591. * @brief set USB configuration
  592. *
  593. * This function configures the device according to the specified configuration
  594. * index and alternate setting by parsing the installed USB descriptor list.
  595. * A configuration index of 0 unconfigures the device.
  596. *
  597. * @param [in] config_index Configuration index
  598. * @param [in] alt_setting Alternate setting number
  599. *
  600. * @return true if successfully configured false if error or unconfigured
  601. */
  602. static bool usb_set_configuration(u8_t config_index, u8_t alt_setting)
  603. {
  604. u8_t *p = NULL;
  605. u8_t cur_config = 0;
  606. u8_t cur_alt_setting = 0;
  607. if (config_index == 0) {
  608. /* unconfigure device */
  609. if (usb_dev.configuration) {
  610. usb_dev.unconfigured = 1;
  611. }
  612. LOG_DBG("Device not configured - invalid configuration "
  613. "offset\n");
  614. return true;
  615. }
  616. /* configure endpoints for this configuration/altsetting */
  617. p = (u8_t *)usb_dev.descriptors;
  618. cur_config = 0xFF;
  619. cur_alt_setting = 0xFF;
  620. while (p[DESC_bLength] != 0) {
  621. switch (p[DESC_bDescriptorType]) {
  622. case DESC_CONFIGURATION:
  623. /* remember current configuration index */
  624. cur_config = p[CONF_DESC_bConfigurationValue];
  625. break;
  626. case DESC_INTERFACE:
  627. /* remember current alternate setting */
  628. cur_alt_setting =
  629. p[INTF_DESC_bAlternateSetting];
  630. break;
  631. case DESC_ENDPOINT:
  632. if ((cur_config == config_index) &&
  633. (cur_alt_setting == alt_setting)) {
  634. struct usb_dc_ep_cfg_data ep_cfg;
  635. /* endpoint found for desired config
  636. * and alternate setting
  637. */
  638. ep_cfg.ep_type =
  639. p[ENDP_DESC_bmAttributes];
  640. ep_cfg.ep_mps =
  641. (p[ENDP_DESC_wMaxPacketSize]) |
  642. (p[ENDP_DESC_wMaxPacketSize + 1]
  643. << 8);
  644. ep_cfg.ep_addr =
  645. p[ENDP_DESC_bEndpointAddress];
  646. usb_dc_ep_configure(&ep_cfg);
  647. usb_dc_ep_enable(ep_cfg.ep_addr);
  648. }
  649. break;
  650. default:
  651. break;
  652. }
  653. /* skip to next descriptor */
  654. p += p[DESC_bLength];
  655. }
  656. usb_dev.unconfigured = 0;
  657. if (usb_dev.status_callback) {
  658. usb_dev.status_callback(USB_DC_CONFIGURED, &config_index);
  659. }
  660. return true;
  661. }
  662. /*
  663. * @brief get USB interface altsetting
  664. *
  665. * @param [in] iface Interface index
  666. *
  667. * @return current altsetting
  668. */
  669. static inline u8_t usb_get_interface(u8_t iface)
  670. {
  671. u16_t intf_info;
  672. /*
  673. * In order to let upper layer know what the interface number
  674. * and retrun the current alternate setting.
  675. *
  676. * iface: the higher byte, alt_setting: the lower byte
  677. */
  678. intf_info = (iface << 8) + 0;
  679. LOG_DBG("iface %u\n", iface);
  680. if (usb_dev.status_callback) {
  681. usb_dev.status_callback(USB_DC_ALTSETTING, (u8_t *)&intf_info);
  682. }
  683. return intf_info & 0xFF;
  684. }
  685. /*
  686. * @brief set USB interface
  687. *
  688. * @param [in] iface Interface index
  689. * @param [in] alt_setting Alternate setting number
  690. *
  691. * @return true if successfully configured false if error or unconfigured
  692. */
  693. static bool usb_set_interface(u8_t iface, u8_t alt_setting)
  694. {
  695. const u8_t *p = usb_dev.descriptors;
  696. u8_t cur_iface = 0xFF;
  697. u8_t cur_alt_setting = 0xFF;
  698. struct usb_dc_ep_cfg_data ep_cfg;
  699. u16_t intf_info;
  700. /*
  701. * In order to let upper layer know what the interface number
  702. * and the alternate setting of "Set Interface" transfer is.
  703. *
  704. * iface: the higher byte, alt_setting: the lower byte
  705. */
  706. intf_info = (iface << 8) + alt_setting;
  707. LOG_DBG("iface %u alt_setting %u\n", iface, alt_setting);
  708. while (p[DESC_bLength] != 0) {
  709. switch (p[DESC_bDescriptorType]) {
  710. case DESC_INTERFACE:
  711. /* remember current alternate setting */
  712. cur_alt_setting = p[INTF_DESC_bAlternateSetting];
  713. cur_iface = p[INTF_DESC_bInterfaceNumber];
  714. break;
  715. case DESC_ENDPOINT:
  716. if ((cur_iface != iface) ||
  717. (cur_alt_setting != alt_setting)) {
  718. break;
  719. }
  720. /* Endpoint is found for desired interface and
  721. * alternate setting
  722. */
  723. ep_cfg.ep_type = p[ENDP_DESC_bmAttributes] &
  724. USB_DC_EP_TYPE_MASK;
  725. ep_cfg.ep_mps = (p[ENDP_DESC_wMaxPacketSize]) |
  726. (p[ENDP_DESC_wMaxPacketSize + 1] << 8);
  727. ep_cfg.ep_addr = p[ENDP_DESC_bEndpointAddress];
  728. usb_dc_ep_configure(&ep_cfg);
  729. usb_dc_ep_enable(ep_cfg.ep_addr);
  730. LOG_DBG("Found: ep_addr 0x%x\n", ep_cfg.ep_addr);
  731. break;
  732. default:
  733. break;
  734. }
  735. /* skip to next descriptor */
  736. p += p[DESC_bLength];
  737. LOG_DBG("p %p\n", p);
  738. }
  739. if (usb_dev.status_callback) {
  740. usb_dev.status_callback(USB_DC_INTERFACE, (u8_t *)&intf_info);
  741. }
  742. return true;
  743. }
  744. /*
  745. * @brief handle a standard device request
  746. *
  747. * @param [in] setup The setup packet
  748. * @param [in,out] len Pointer to data length
  749. * @param [in,out] data_buf Data buffer
  750. *
  751. * @return true if the request was handled successfully
  752. */
  753. static bool usb_handle_std_device_req(struct usb_setup_packet *setup,
  754. s32_t *len, u8_t **data_buf)
  755. {
  756. u16_t value = sys_le16_to_cpu(setup->wValue);
  757. u16_t index = sys_le16_to_cpu(setup->wIndex);
  758. bool ret = true;
  759. u8_t *data = *data_buf;
  760. switch (setup->bRequest) {
  761. case REQ_GET_STATUS:
  762. LOG_DBG("REQ_GET_STATUS\n");
  763. /* bit 0: self-powered */
  764. /* bit 1: remote wakeup = not supported */
  765. data[0] = 0;
  766. data[1] = 0;
  767. #ifdef CONFIG_USB_DEVICE_SELF_POWERED
  768. data[0] |= BIT(USB_DEVICE_SELF_POWERED);
  769. #endif
  770. #ifdef CONFIG_USB_DEVICE_REMOTE_WAKEUP
  771. data[0] |= (usb_dev.remote_wakeup ? BIT(USB_DEVICE_REMOTE_WAKEUP) : 0);
  772. #endif
  773. *len = 2;
  774. break;
  775. case REQ_SET_ADDRESS:
  776. LOG_DBG("REQ_SET_ADDRESS, addr 0x%x\n", value);
  777. usb_dc_set_address(value);
  778. break;
  779. case REQ_GET_DESCRIPTOR:
  780. LOG_DBG("REQ_GET_DESCRIPTOR\n");
  781. ret = usb_get_descriptor(value, index, len, data_buf);
  782. break;
  783. case REQ_GET_CONFIGURATION:
  784. LOG_DBG("REQ_GET_CONFIGURATION\n");
  785. /* indicate if we are configured */
  786. data[0] = usb_dev.configuration;
  787. *len = 1;
  788. break;
  789. case REQ_SET_CONFIGURATION:
  790. value &= 0xFF;
  791. LOG_DBG("REQ_SET_CONFIGURATION, conf 0x%x\n", value);
  792. if (!usb_set_configuration(value, 0)) {
  793. LOG_DBG("USBSetConfiguration failed!\n");
  794. ret = false;
  795. } else {
  796. /* configuration successful,
  797. * update current configuration
  798. */
  799. usb_dev.configuration = value;
  800. }
  801. break;
  802. case REQ_CLEAR_FEATURE:
  803. LOG_DBG("REQ_CLEAR_FEATURE\n");
  804. ret = false;
  805. #ifdef CONFIG_USB_DEVICE_REMOTE_WAKEUP
  806. if (value == FEA_REMOTE_WAKEUP) {
  807. usb_dev.remote_wakeup = false;
  808. ret = true;
  809. }
  810. #endif
  811. break;
  812. case REQ_SET_FEATURE:
  813. LOG_DBG("REQ_SET_FEATURE\n");
  814. ret = false;
  815. #ifdef CONFIG_USB_DEVICE_REMOTE_WAKEUP
  816. if (value == FEA_REMOTE_WAKEUP) {
  817. usb_dev.remote_wakeup = true;
  818. ret = true;
  819. }
  820. #endif
  821. if (value == FEA_TEST_MODE) {
  822. /* put TEST_MODE code here */
  823. }
  824. break;
  825. case REQ_SET_DESCRIPTOR:
  826. LOG_DBG("Device req %x not implemented\n", setup->bRequest);
  827. ret = false;
  828. break;
  829. default:
  830. LOG_DBG("Illegal device req %x\n", setup->bRequest);
  831. ret = false;
  832. break;
  833. }
  834. return ret;
  835. }
  836. /*
  837. * @brief handle a standard interface request
  838. *
  839. * @param [in] setup The setup packet
  840. * @param [in,out] len Pointer to data length
  841. * @param [in] data_buf Data buffer
  842. *
  843. * @return true if the request was handled successfully
  844. */
  845. static bool usb_handle_std_interface_req(struct usb_setup_packet *setup,
  846. s32_t *len, u8_t **data_buf)
  847. {
  848. u16_t value = sys_le16_to_cpu(setup->wValue);
  849. u16_t index = sys_le16_to_cpu(setup->wIndex);
  850. u8_t *data = *data_buf;
  851. switch (setup->bRequest) {
  852. case REQ_GET_STATUS:
  853. /* no bits specified */
  854. data[0] = 0;
  855. data[1] = 0;
  856. *len = 2;
  857. break;
  858. case REQ_CLEAR_FEATURE:
  859. case REQ_SET_FEATURE:
  860. /* not defined for interface */
  861. return false;
  862. case REQ_GET_INTERFACE:
  863. data[0] = usb_get_interface(index);
  864. *len = 1;
  865. break;
  866. case REQ_SET_INTERFACE:
  867. LOG_DBG("REQ_SET_INTERFACE\n");
  868. usb_set_interface(index, value);
  869. *len = 0;
  870. break;
  871. default:
  872. LOG_DBG("Illegal interface req %d\n", setup->bRequest);
  873. return false;
  874. }
  875. return true;
  876. }
  877. /*
  878. * @brief handle a standard endpoint request
  879. *
  880. * @param [in] setup The setup packet
  881. * @param [in,out] len Pointer to data length
  882. * @param [in] data_buf Data buffer
  883. *
  884. * @return true if the request was handled successfully
  885. */
  886. static bool usb_handle_std_endpoint_req(struct usb_setup_packet *setup,
  887. s32_t *len, u8_t **data_buf)
  888. {
  889. u16_t value = sys_le16_to_cpu(setup->wValue);
  890. u8_t ep = sys_le16_to_cpu(setup->wIndex);
  891. u8_t *data = *data_buf;
  892. switch (setup->bRequest) {
  893. case REQ_GET_STATUS:
  894. /* bit 0 = endpointed halted or not */
  895. usb_dc_ep_is_stalled(ep, &data[0]);
  896. data[1] = 0;
  897. *len = 2;
  898. break;
  899. case REQ_CLEAR_FEATURE:
  900. if (value == FEA_ENDPOINT_HALT) {
  901. /* clear HALT by unstalling */
  902. LOG_DBG("... EP clear halt %x\n", ep);
  903. usb_dc_ep_clear_stall(ep);
  904. break;
  905. }
  906. /* only ENDPOINT_HALT defined for endpoints */
  907. return false;
  908. case REQ_SET_FEATURE:
  909. if (value == FEA_ENDPOINT_HALT) {
  910. /* set HALT by stalling */
  911. LOG_DBG("--- EP SET halt %x\n", ep);
  912. usb_dc_ep_set_stall(ep);
  913. break;
  914. }
  915. /* only ENDPOINT_HALT defined for endpoints */
  916. return false;
  917. case REQ_SYNCH_FRAME:
  918. LOG_DBG("EP req %d not implemented\n", setup->bRequest);
  919. return false;
  920. default:
  921. LOG_DBG("Illegal EP req %d\n", setup->bRequest);
  922. return false;
  923. }
  924. return true;
  925. }
  926. /*
  927. * @brief default handler for standard ('chapter 9') requests
  928. *
  929. * If a custom request handler was installed, this handler is called first.
  930. *
  931. * @param [in] setup The setup packet
  932. * @param [in,out] len Pointer to data length
  933. * @param [in] data_buf Data buffer
  934. *
  935. * @return true if the request was handled successfully
  936. */
  937. static int usb_handle_standard_request(struct usb_setup_packet *setup,
  938. s32_t *len, u8_t **data_buf)
  939. {
  940. int rc = 0;
  941. if (!usb_handle_bos(setup, len, data_buf)) {
  942. return 0;
  943. }
  944. /* try the custom request handler first */
  945. if (usb_dev.custom_req_handler &&
  946. !usb_dev.custom_req_handler(setup, len, data_buf)) {
  947. return 0;
  948. }
  949. switch (REQTYPE_GET_RECIP(setup->bmRequestType)) {
  950. case REQTYPE_RECIP_DEVICE:
  951. if (usb_handle_std_device_req(setup, len, data_buf) == false)
  952. rc = -EINVAL;
  953. break;
  954. case REQTYPE_RECIP_INTERFACE:
  955. if (usb_handle_std_interface_req(setup, len, data_buf) == false)
  956. rc = -EINVAL;
  957. break;
  958. case REQTYPE_RECIP_ENDPOINT:
  959. if (usb_handle_std_endpoint_req(setup, len, data_buf) == false)
  960. rc = -EINVAL;
  961. break;
  962. default:
  963. rc = -EINVAL;
  964. }
  965. return rc;
  966. }
  967. /*
  968. * @brief Registers a callback for custom device requests
  969. *
  970. * In usb_register_custom_req_handler, the custom request handler gets a first
  971. * chance at handling the request before it is handed over to the 'chapter 9'
  972. * request handler.
  973. *
  974. * This can be used for example in HID devices, where a REQ_GET_DESCRIPTOR
  975. * request is sent to an interface, which is not covered by the 'chapter 9'
  976. * specification.
  977. *
  978. * @param [in] handler Callback function pointer
  979. */
  980. static void usb_register_custom_req_handler(usb_request_handler handler)
  981. {
  982. usb_dev.custom_req_handler = handler;
  983. }
  984. /*
  985. * @brief register a callback for device status
  986. *
  987. * This function registers a callback for device status. The registered callback
  988. * is used to report changes in the status of the device controller.
  989. *
  990. * @param [in] cb Callback function pointer
  991. */
  992. static void usb_register_status_callback(usb_status_callback cb)
  993. {
  994. usb_dev.status_callback = cb;
  995. }
  996. /**
  997. * @brief turn on/off USB VBUS voltage
  998. *
  999. * @param on Set to false to turn off and to true to turn on VBUS
  1000. *
  1001. * @return 0 on success, negative errno code on fail
  1002. */
  1003. static int usb_vbus_set(bool on)
  1004. {
  1005. #if defined(USB_VUSB_EN_GPIO)
  1006. int ret = 0;
  1007. struct device *gpio_dev = device_get_binding(USB_GPIO_DRV_NAME);
  1008. if (!gpio_dev) {
  1009. LOG_DBG("USB requires GPIO. Cannot find %s!\n",
  1010. USB_GPIO_DRV_NAME);
  1011. return -ENODEV;
  1012. }
  1013. /* Enable USB IO */
  1014. ret = gpio_pin_configure(gpio_dev, USB_VUSB_EN_GPIO, GPIO_DIR_OUT);
  1015. if (ret)
  1016. return ret;
  1017. ret = gpio_pin_write(gpio_dev, USB_VUSB_EN_GPIO, on == true ? 1 : 0);
  1018. if (ret)
  1019. return ret;
  1020. #endif
  1021. return 0;
  1022. }
  1023. static void status_cb(enum usb_dc_status_code status, u8_t *param)
  1024. {
  1025. if (status == USB_DC_HIGHSPEED) {
  1026. LOG_DBG("High-speed status cb\n");
  1027. usb_dev.descriptors = usb_dev.hs_descriptors;
  1028. }
  1029. if (usb_dev.status_callback != NULL) {
  1030. usb_dev.status_callback(status, param);
  1031. }
  1032. }
  1033. bool usb_remote_wakeup_enabled(void)
  1034. {
  1035. return usb_dev.remote_wakeup;
  1036. }
  1037. int usb_remote_wakeup(void)
  1038. {
  1039. #ifdef CONFIG_USB_DEVICE_REMOTE_WAKEUP
  1040. if (usb_dev.remote_wakeup) {
  1041. return usb_dc_do_remote_wakeup();
  1042. }
  1043. return -EACCES;
  1044. #else
  1045. return -ENOTSUP;
  1046. #endif
  1047. }
  1048. int usb_set_config(const struct usb_cfg_data *config)
  1049. {
  1050. if (!config) {
  1051. return -EINVAL;
  1052. }
  1053. /* register descriptors */
  1054. usb_dev.descriptors = usb_dev.fs_descriptors;
  1055. /* register standard request handler */
  1056. usb_register_request_handler(REQTYPE_TYPE_STANDARD,
  1057. usb_handle_standard_request);
  1058. /* register class request handlers for each interface*/
  1059. if (config->interface.class_handler != NULL) {
  1060. usb_register_request_handler(REQTYPE_TYPE_CLASS,
  1061. config->interface.class_handler);
  1062. }
  1063. /* register vendor request handlers */
  1064. if (config->interface.vendor_handler) {
  1065. usb_register_request_handler(REQTYPE_TYPE_VENDOR,
  1066. config->interface.vendor_handler);
  1067. }
  1068. /* register class request handlers for each interface*/
  1069. if (config->interface.custom_handler != NULL) {
  1070. usb_register_custom_req_handler(
  1071. config->interface.custom_handler);
  1072. }
  1073. return 0;
  1074. }
  1075. static u8_t class_num;
  1076. int usb_decice_composite_set_config(const struct usb_cfg_data *config)
  1077. {
  1078. if (class_num >= CONFIG_USB_COMPOSITE_DEVICE_CLASS_NUM) {
  1079. LOG_ERR("%d\n", class_num);
  1080. class_num = 0;
  1081. return -EINVAL;
  1082. }
  1083. usb_cfg_data_buf[class_num] = config;
  1084. class_num++;
  1085. return 0;
  1086. }
  1087. int usb_deconfig(void)
  1088. {
  1089. class_num = 0;
  1090. /* unegister standard request handler */
  1091. usb_register_request_handler(REQTYPE_TYPE_STANDARD, NULL);
  1092. /* unregister class request handlers for each interface*/
  1093. usb_register_request_handler(REQTYPE_TYPE_CLASS, NULL);
  1094. /* unregister class request handlers for each interface*/
  1095. usb_register_custom_req_handler(NULL);
  1096. /* unregister status callback */
  1097. usb_register_status_callback(NULL);
  1098. /* Reset USB controller */
  1099. usb_dc_reset();
  1100. return 0;
  1101. }
  1102. int usb_enable(const struct usb_cfg_data *config)
  1103. {
  1104. int ret;
  1105. u32_t i;
  1106. struct usb_dc_ep_cfg_data ep0_cfg;
  1107. if (true == usb_dev.enabled) {
  1108. return 0;
  1109. }
  1110. /* Enable VBUS if needed */
  1111. ret = usb_vbus_set(true);
  1112. if (ret < 0)
  1113. return ret;
  1114. /* register status callback */
  1115. if (config->cb_usb_status != NULL) {
  1116. usb_register_status_callback(config->cb_usb_status);
  1117. }
  1118. ret = usb_dc_set_status_callback(status_cb);
  1119. if (ret < 0)
  1120. return ret;
  1121. ret = usb_dc_attach();
  1122. if (ret < 0)
  1123. return ret;
  1124. /* Configure control EP */
  1125. ep0_cfg.ep_mps = MAX_PACKET_SIZE0;
  1126. ep0_cfg.ep_type = USB_DC_EP_CONTROL;
  1127. ep0_cfg.ep_addr = USB_CONTROL_OUT_EP0;
  1128. ret = usb_dc_ep_configure(&ep0_cfg);
  1129. if (ret < 0)
  1130. return ret;
  1131. ep0_cfg.ep_addr = USB_CONTROL_IN_EP0;
  1132. ret = usb_dc_ep_configure(&ep0_cfg);
  1133. if (ret < 0)
  1134. return ret;
  1135. /*register endpoint 0 handlers*/
  1136. ret = usb_dc_ep_set_callback(USB_CONTROL_OUT_EP0,
  1137. usb_handle_control_transfer);
  1138. if (ret < 0)
  1139. return ret;
  1140. ret = usb_dc_ep_set_callback(USB_CONTROL_IN_EP0,
  1141. usb_handle_control_transfer);
  1142. if (ret < 0)
  1143. return ret;
  1144. /*register endpoint handlers*/
  1145. for (i = 0; i < config->num_endpoints; i++) {
  1146. ret = usb_dc_ep_set_callback(config->endpoint[i].ep_addr,
  1147. config->endpoint[i].ep_cb);
  1148. if (ret < 0)
  1149. return ret;
  1150. }
  1151. #ifdef CONFIG_USB_DEVICE_TRANSFER
  1152. /* init transfer slots */
  1153. for (i = 0; i < MAX_NUM_TRANSFERS; i++) {
  1154. k_work_init(&usb_dev.transfer[i].work, usb_transfer_work);
  1155. k_sem_init(&usb_dev.transfer[i].sem, 1, 1);
  1156. }
  1157. #endif
  1158. /* enable control EP */
  1159. ret = usb_dc_ep_enable(USB_CONTROL_OUT_EP0);
  1160. if (ret < 0)
  1161. return ret;
  1162. ret = usb_dc_ep_enable(USB_CONTROL_IN_EP0);
  1163. if (ret < 0)
  1164. return ret;
  1165. usb_dev.unconfigured = 0;
  1166. usb_dev.enabled = true;
  1167. return 0;
  1168. }
  1169. int usb_disable(void)
  1170. {
  1171. int ret;
  1172. if (true != usb_dev.enabled) {
  1173. /* Already disabled: go ahead! */
  1174. LOG_DBG("already\n");
  1175. }
  1176. ret = usb_dc_detach();
  1177. if (ret < 0) {
  1178. return ret;
  1179. }
  1180. /* Disable VBUS if needed */
  1181. usb_vbus_set(false);
  1182. usb_dev.enabled = false;
  1183. return 0;
  1184. }
  1185. int usb_write(u8_t ep, const u8_t *data, u32_t data_len,
  1186. u32_t *bytes_ret)
  1187. {
  1188. return usb_dc_ep_write(ep, data, data_len, bytes_ret);
  1189. }
  1190. int usb_read(u8_t ep, u8_t *data, u32_t max_data_len,
  1191. u32_t *ret_bytes)
  1192. {
  1193. return usb_dc_ep_read(ep, data, max_data_len, ret_bytes);
  1194. }
  1195. int usb_read_async(u8_t ep, u8_t *data, u32_t max_data_len,
  1196. u32_t *ret_bytes)
  1197. {
  1198. return usb_dc_ep_read_async(ep, data, max_data_len, ret_bytes);
  1199. }
  1200. int usb_read_actual(u8_t ep, u32_t *ret_bytes)
  1201. {
  1202. return usb_dc_ep_read_actual(ep, ret_bytes);
  1203. }
  1204. int usb_ep_set_stall(u8_t ep)
  1205. {
  1206. return usb_dc_ep_set_stall(ep);
  1207. }
  1208. int usb_ep_clear_stall(u8_t ep)
  1209. {
  1210. return usb_dc_ep_clear_stall(ep);
  1211. }
  1212. int usb_ep_read_wait(u8_t ep, u8_t *data, u32_t max_data_len,
  1213. u32_t *ret_bytes)
  1214. {
  1215. return usb_dc_ep_read_wait(ep, data, max_data_len, ret_bytes);
  1216. }
  1217. int usb_ep_read_continue(u8_t ep)
  1218. {
  1219. return usb_dc_ep_read_continue(ep);
  1220. }
  1221. #ifdef CONFIG_USB_DEVICE_TRANSFER
  1222. /* Transfer management */
  1223. static struct usb_transfer_data *usb_ep_get_transfer(u8_t ep)
  1224. {
  1225. int i;
  1226. for (i = 0; i < ARRAY_SIZE(usb_dev.transfer); i++) {
  1227. if (usb_dev.transfer[i].ep == ep) {
  1228. return &usb_dev.transfer[i];
  1229. }
  1230. }
  1231. return NULL;
  1232. }
  1233. static void usb_transfer_work(struct k_work *item)
  1234. {
  1235. struct usb_transfer_data *trans;
  1236. int ret = 0, bytes;
  1237. u8_t ep;
  1238. trans = CONTAINER_OF(item, struct usb_transfer_data, work);
  1239. ep = trans->ep;
  1240. if (trans->status != -EBUSY) {
  1241. /* transfer cancelled or already completed */
  1242. goto done;
  1243. }
  1244. if (trans->flags & USB_TRANS_WRITE) {
  1245. if (!trans->bsize) {
  1246. if (!(trans->flags & USB_TRANS_NO_ZLP)) {
  1247. usb_dc_ep_write(ep, NULL, 0, NULL);
  1248. }
  1249. trans->status = 0;
  1250. goto done;
  1251. }
  1252. ret = usb_dc_ep_write(ep, trans->buffer, trans->bsize, &bytes);
  1253. if (ret) {
  1254. /* transfer error */
  1255. trans->status = -EINVAL;
  1256. goto done;
  1257. }
  1258. trans->buffer += bytes;
  1259. trans->bsize -= bytes;
  1260. trans->tsize += bytes;
  1261. } else {
  1262. ret = usb_dc_ep_read_wait(ep, trans->buffer, trans->bsize,
  1263. &bytes);
  1264. if (ret) {
  1265. /* transfer error */
  1266. trans->status = -EINVAL;
  1267. goto done;
  1268. }
  1269. trans->buffer += bytes;
  1270. trans->bsize -= bytes;
  1271. trans->tsize += bytes;
  1272. /* ZLP, short-pkt or buffer full */
  1273. if (!bytes || (bytes % usb_dc_ep_mps(ep)) || !trans->bsize) {
  1274. /* transfer complete */
  1275. trans->status = 0;
  1276. goto done;
  1277. }
  1278. /* we expect mote data, clear NAK */
  1279. usb_dc_ep_read_continue(ep);
  1280. }
  1281. done:
  1282. if (trans->status != -EBUSY && trans->cb) { /* Transfer complete */
  1283. usb_transfer_callback cb = trans->cb;
  1284. int tsize = trans->tsize;
  1285. void *priv = trans->priv;
  1286. if (k_is_in_isr()) {
  1287. /* reschedule completion in thread context */
  1288. k_work_submit(&trans->work);
  1289. return;
  1290. }
  1291. LOG_DBG("transfer done, ep=%02x, status=%d, size=%zu\n",
  1292. trans->ep, trans->status, trans->tsize);
  1293. trans->cb = NULL;
  1294. k_sem_give(&trans->sem);
  1295. /* Transfer completion callback */
  1296. cb(ep, tsize, priv);
  1297. }
  1298. }
  1299. void usb_transfer_ep_callback(u8_t ep, enum usb_dc_ep_cb_status_code status)
  1300. {
  1301. struct usb_transfer_data *trans = usb_ep_get_transfer(ep);
  1302. if (status != USB_DC_EP_DATA_IN && status != USB_DC_EP_DATA_OUT) {
  1303. return;
  1304. }
  1305. if (!trans) {
  1306. if (status == USB_DC_EP_DATA_IN) {
  1307. u32_t bytes;
  1308. /* In the unlikely case we receive data while no
  1309. * transfer is ongoing, we have to consume the data
  1310. * anyway. This is to prevent stucking reception on
  1311. * other endpoints (e.g dw driver has only one rx-fifo,
  1312. * so drain it).
  1313. */
  1314. do {
  1315. u8_t data;
  1316. usb_dc_ep_read_wait(ep, &data, 1, &bytes);
  1317. } while (bytes);
  1318. LOG_ERR("RX data lost, no transfer\n");
  1319. }
  1320. return;
  1321. }
  1322. if (!k_is_in_isr() || (status == USB_DC_EP_DATA_OUT)) {
  1323. /* If we are not in IRQ context, no need to defer work */
  1324. /* Read (out) needs to be done from ep_callback */
  1325. usb_transfer_work(&trans->work);
  1326. } else {
  1327. k_work_submit(&trans->work);
  1328. }
  1329. }
  1330. int usb_transfer(u8_t ep, u8_t *data, size_t dlen, unsigned int flags,
  1331. usb_transfer_callback cb, void *cb_data)
  1332. {
  1333. struct usb_transfer_data *trans = NULL;
  1334. int i, key, ret = 0;
  1335. LOG_DBG("transfer start, ep=%02x, data=%p, dlen=%zd\n",
  1336. ep, data, dlen);
  1337. key = irq_lock();
  1338. for (i = 0; i < MAX_NUM_TRANSFERS; i++) {
  1339. if (!k_sem_take(&usb_dev.transfer[i].sem, K_NO_WAIT)) {
  1340. trans = &usb_dev.transfer[i];
  1341. break;
  1342. }
  1343. }
  1344. if (!trans) {
  1345. LOG_ERR("no transfer slot available\n");
  1346. ret = -ENOMEM;
  1347. goto done;
  1348. }
  1349. if (trans->status == -EBUSY) {
  1350. /* A transfer is already ongoing and not completed */
  1351. k_sem_give(&trans->sem);
  1352. ret = -EBUSY;
  1353. goto done;
  1354. }
  1355. /* Configure new transfer */
  1356. trans->ep = ep;
  1357. trans->buffer = data;
  1358. trans->bsize = dlen;
  1359. trans->tsize = 0;
  1360. trans->cb = cb;
  1361. trans->flags = flags;
  1362. trans->priv = cb_data;
  1363. trans->status = -EBUSY;
  1364. if (usb_dc_ep_mps(ep) && (dlen % usb_dc_ep_mps(ep))) {
  1365. /* no need to send ZLP since last packet will be a short one */
  1366. trans->flags |= USB_TRANS_NO_ZLP;
  1367. }
  1368. if (flags & USB_TRANS_WRITE) {
  1369. /* start writing first chunk */
  1370. k_work_submit(&trans->work);
  1371. } else {
  1372. /* ready to read, clear NAK */
  1373. ret = usb_dc_ep_read_continue(ep);
  1374. }
  1375. done:
  1376. irq_unlock(key);
  1377. return ret;
  1378. }
  1379. void usb_cancel_transfer(u8_t ep)
  1380. {
  1381. struct usb_transfer_data *trans;
  1382. int key;
  1383. key = irq_lock();
  1384. trans = usb_ep_get_transfer(ep);
  1385. if (!trans) {
  1386. goto done;
  1387. }
  1388. if (trans->status != -EBUSY) {
  1389. goto done;
  1390. }
  1391. trans->status = -ECANCELED;
  1392. k_work_submit(&trans->work);
  1393. done:
  1394. irq_unlock(key);
  1395. }
  1396. struct usb_transfer_sync_priv {
  1397. int tsize;
  1398. struct k_sem sem;
  1399. };
  1400. static void usb_transfer_sync_cb(u8_t ep, int size, void *priv)
  1401. {
  1402. struct usb_transfer_sync_priv *pdata = priv;
  1403. pdata->tsize = size;
  1404. k_sem_give(&pdata->sem);
  1405. }
  1406. int usb_transfer_sync(u8_t ep, u8_t *data, size_t dlen, unsigned int flags)
  1407. {
  1408. struct usb_transfer_sync_priv pdata;
  1409. int ret;
  1410. k_sem_init(&pdata.sem, 0, 1);
  1411. ret = usb_transfer(ep, data, dlen, flags, usb_transfer_sync_cb, &pdata);
  1412. if (ret) {
  1413. return ret;
  1414. }
  1415. /* Semaphore will be released by the transfer completion callback */
  1416. k_sem_take(&pdata.sem, K_FOREVER);
  1417. return pdata.tsize;
  1418. }
  1419. #endif
  1420. static void forward_status_cb(enum usb_dc_status_code status, u8_t *param)
  1421. {
  1422. size_t size = CONFIG_USB_COMPOSITE_DEVICE_CLASS_NUM;
  1423. if (status == USB_DC_HIGHSPEED) {
  1424. usb_dev.descriptors = usb_dev.hs_descriptors;
  1425. }
  1426. for (size_t i = 0; i < size; i++) {
  1427. if (usb_cfg_data_buf[i]->cb_usb_status) {
  1428. usb_cfg_data_buf[i]->cb_usb_status(status, param);
  1429. }
  1430. }
  1431. }
  1432. /*
  1433. * The functions class_handler(), custom_handler() and vendor_handler()
  1434. * go through the interfaces one after the other and compare the
  1435. * bInterfaceNumber with the wIndex and and then call the appropriate
  1436. * callback of the USB function.
  1437. * Note, a USB function can have more than one interface and the
  1438. * request does not have to be directed to the first interface (unlikely).
  1439. * These functions can be simplified and moved to usb_handle_request()
  1440. * when legacy initialization throgh the usb_set_config() and
  1441. * usb_enable() is no longer needed.
  1442. */
  1443. static int class_handler(struct usb_setup_packet *pSetup,
  1444. s32_t *len, u8_t **data)
  1445. {
  1446. size_t size = CONFIG_USB_COMPOSITE_DEVICE_CLASS_NUM;
  1447. u16_t index = sys_le16_to_cpu(pSetup->wIndex);
  1448. const struct usb_if_descriptor *if_descr;
  1449. const struct usb_interface_cfg_data *iface;
  1450. const struct usb_ep_cfg_data *ep_data;
  1451. LOG_DBG("bRequest 0x%x, wIndex 0x%x\n", pSetup->bRequest, index);
  1452. for (size_t i = 0; i < size; i++) {
  1453. iface = &(usb_cfg_data_buf[i]->interface);
  1454. if_descr = usb_cfg_data_buf[i]->interface_descriptor;
  1455. if (!iface->class_handler) {
  1456. continue;
  1457. }
  1458. /* interface */
  1459. if (if_descr->bInterfaceNumber == (index & 0xFF)) {
  1460. return iface->class_handler(pSetup, len, data);
  1461. }
  1462. /* endpoint */
  1463. for (size_t j = 0; j < usb_cfg_data_buf[i]->num_endpoints; j++) {
  1464. ep_data = usb_cfg_data_buf[i]->endpoint;
  1465. if (ep_data[j].ep_addr == index) {
  1466. return iface->class_handler(pSetup, len, data);
  1467. }
  1468. }
  1469. }
  1470. return -ENOTSUP;
  1471. }
  1472. static int custom_handler(struct usb_setup_packet *pSetup,
  1473. s32_t *len, u8_t **data)
  1474. {
  1475. size_t size = CONFIG_USB_COMPOSITE_DEVICE_CLASS_NUM;
  1476. u16_t index = sys_le16_to_cpu(pSetup->wIndex);
  1477. const struct usb_if_descriptor *if_descr;
  1478. const struct usb_interface_cfg_data *iface;
  1479. LOG_DBG("bRequest 0x%x, wIndex 0x%x\n", pSetup->bRequest, index);
  1480. for (size_t i = 0; i < size; i++) {
  1481. iface = &(usb_cfg_data_buf[i]->interface);
  1482. if_descr = usb_cfg_data_buf[i]->interface_descriptor;
  1483. if ((iface->custom_handler) &&
  1484. (if_descr->bInterfaceNumber == (index & 0xFF))) {
  1485. return iface->custom_handler(pSetup, len, data);
  1486. }
  1487. }
  1488. return -ENOTSUP;
  1489. }
  1490. static int vendor_handler(struct usb_setup_packet *pSetup,
  1491. s32_t *len, u8_t **data)
  1492. {
  1493. size_t size = CONFIG_USB_COMPOSITE_DEVICE_CLASS_NUM;
  1494. u16_t index = sys_le16_to_cpu(pSetup->wIndex);
  1495. const struct usb_if_descriptor *if_descr;
  1496. const struct usb_interface_cfg_data *iface;
  1497. LOG_DBG("bRequest 0x%x, wIndex 0x%x\n", pSetup->bRequest, index);
  1498. for (size_t i = 0; i < size; i++) {
  1499. iface = &(usb_cfg_data_buf[i]->interface);
  1500. if_descr = usb_cfg_data_buf[i]->interface_descriptor;
  1501. if ((iface->vendor_handler) &&
  1502. (if_descr->bInterfaceNumber == (index & 0xFF))) {
  1503. return iface->vendor_handler(pSetup, len, data);
  1504. }
  1505. }
  1506. return -ENOTSUP;
  1507. }
  1508. static int composite_setup_ep_cb(void)
  1509. {
  1510. size_t size = CONFIG_USB_COMPOSITE_DEVICE_CLASS_NUM;
  1511. const struct usb_ep_cfg_data *ep_data;
  1512. for (size_t i = 0; i < size; i++) {
  1513. ep_data = usb_cfg_data_buf[i]->endpoint;
  1514. for (u8_t n = 0; n < usb_cfg_data_buf[i]->num_endpoints; n++) {
  1515. LOG_INF("set cb, ep: 0x%x\n", ep_data[n].ep_addr);
  1516. if (usb_dc_ep_set_callback(ep_data[n].ep_addr,
  1517. ep_data[n].ep_cb)) {
  1518. return -1;
  1519. }
  1520. }
  1521. }
  1522. return 0;
  1523. }
  1524. /*
  1525. * API: initialize USB composite device
  1526. */
  1527. int usb_device_composite_init(struct device *dev)
  1528. {
  1529. int ret;
  1530. struct usb_dc_ep_cfg_data ep0_cfg;
  1531. if (true == usb_dev.enabled) {
  1532. return 0;
  1533. }
  1534. /* register composite device descriptors */
  1535. usb_dev.descriptors = usb_dev.fs_descriptors;
  1536. /* register standard request handler */
  1537. usb_register_request_handler(REQTYPE_TYPE_STANDARD,
  1538. usb_handle_standard_request);
  1539. /* register class request handlers for each interface*/
  1540. usb_register_request_handler(REQTYPE_TYPE_CLASS, class_handler);
  1541. /* register vendor request handlers */
  1542. usb_register_request_handler(REQTYPE_TYPE_VENDOR, vendor_handler);
  1543. /* register class request handlers for each interface*/
  1544. usb_register_custom_req_handler(custom_handler);
  1545. usb_register_status_callback(forward_status_cb);
  1546. ret = usb_dc_set_status_callback(forward_status_cb);
  1547. if (ret < 0) {
  1548. return ret;
  1549. }
  1550. /* Enable VBUS if needed */
  1551. ret = usb_vbus_set(true);
  1552. if (ret < 0) {
  1553. return ret;
  1554. }
  1555. ret = usb_dc_attach();
  1556. if (ret < 0) {
  1557. return ret;
  1558. }
  1559. /* Configure control EP */
  1560. ep0_cfg.ep_mps = MAX_PACKET_SIZE0;
  1561. ep0_cfg.ep_type = USB_DC_EP_CONTROL;
  1562. ep0_cfg.ep_addr = USB_CONTROL_OUT_EP0;
  1563. ret = usb_dc_ep_configure(&ep0_cfg);
  1564. if (ret < 0) {
  1565. return ret;
  1566. }
  1567. ep0_cfg.ep_addr = USB_CONTROL_IN_EP0;
  1568. ret = usb_dc_ep_configure(&ep0_cfg);
  1569. if (ret < 0) {
  1570. return ret;
  1571. }
  1572. /*register endpoint 0 handlers*/
  1573. ret = usb_dc_ep_set_callback(USB_CONTROL_OUT_EP0,
  1574. usb_handle_control_transfer);
  1575. if (ret < 0)
  1576. return ret;
  1577. ret = usb_dc_ep_set_callback(USB_CONTROL_IN_EP0,
  1578. usb_handle_control_transfer);
  1579. if (ret < 0)
  1580. return ret;
  1581. if (composite_setup_ep_cb()) {
  1582. return -1;
  1583. }
  1584. #ifdef CONFIG_USB_DEVICE_TRANSFER
  1585. /* init transfer slots */
  1586. for (int i = 0; i < MAX_NUM_TRANSFERS; i++) {
  1587. k_work_init(&usb_dev.transfer[i].work, usb_transfer_work);
  1588. k_sem_init(&usb_dev.transfer[i].sem, 1, 1);
  1589. }
  1590. #endif
  1591. /* enable control EP */
  1592. ret = usb_dc_ep_enable(USB_CONTROL_OUT_EP0);
  1593. if (ret < 0) {
  1594. return ret;
  1595. }
  1596. ret = usb_dc_ep_enable(USB_CONTROL_IN_EP0);
  1597. if (ret < 0) {
  1598. return ret;
  1599. }
  1600. usb_dev.unconfigured = 0;
  1601. usb_dev.enabled = true;
  1602. return 0;
  1603. }
  1604. /*
  1605. * API: deinitialize USB composite device
  1606. */
  1607. int usb_device_composite_exit(void)
  1608. {
  1609. int ret;
  1610. ret = usb_disable();
  1611. if (ret) {
  1612. LOG_ERR("Failed to disable USB: %d\n", ret);
  1613. return ret;
  1614. }
  1615. usb_deconfig();
  1616. LOG_INF("done\n");
  1617. return ret;
  1618. }
  1619. enum usb_device_speed usb_device_speed(void)
  1620. {
  1621. return usb_dc_speed();
  1622. }
  1623. bool usb_device_unconfigured(void)
  1624. {
  1625. return usb_dev.unconfigured == 1;
  1626. }