1 /*
2  * Copyright (c) 2022, sakumisu
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 #include "usbd_core.h"
7 #ifdef CONFIG_USBDEV_EP0_THREAD
8 #include "usb_osal.h"
9 
10 #define USB_EP0_STATE_SETUP 0
11 #define USB_EP0_STATE_IN    1
12 #define USB_EP0_STATE_OUT   2
13 #endif
14 
15 #undef USB_DBG_TAG
16 #define USB_DBG_TAG "usbd_core"
17 #include "usb_log.h"
18 
19 /* general descriptor field offsets */
20 #define DESC_bLength         0 /** Length offset */
21 #define DESC_bDescriptorType 1 /** Descriptor type offset */
22 
23 /* config descriptor field offsets */
24 #define CONF_DESC_wTotalLength        2 /** Total length offset */
25 #define CONF_DESC_bConfigurationValue 5 /** Configuration value offset */
26 #define CONF_DESC_bmAttributes        7 /** configuration characteristics */
27 
28 /* interface descriptor field offsets */
29 #define INTF_DESC_bInterfaceNumber  2 /** Interface number offset */
30 #define INTF_DESC_bAlternateSetting 3 /** Alternate setting offset */
31 
32 struct usbd_tx_rx_msg {
33     uint8_t ep;
34     uint8_t ep_mult;
35     uint16_t ep_mps;
36     uint32_t nbytes;
37     usbd_endpoint_callback cb;
38 };
39 
40 USB_NOCACHE_RAM_SECTION struct usbd_core_priv {
41     /** Setup packet */
42     USB_MEM_ALIGNX struct usb_setup_packet setup;
43     /** Pointer to data buffer */
44     USB_MEM_ALIGNX uint8_t *ep0_data_buf;
45     /** Remaining bytes in buffer */
46     uint32_t ep0_data_buf_residue;
47     /** Total length of control transfer */
48     uint32_t ep0_data_buf_len;
49     /** Zero length packet flag of control transfer */
50     bool zlp_flag;
51     /** Pointer to registered descriptors */
52 #ifdef CONFIG_USBDEV_ADVANCE_DESC
53     const struct usb_descriptor *descriptors;
54 #else
55     const uint8_t *descriptors;
56     struct usb_msosv1_descriptor *msosv1_desc;
57     struct usb_msosv2_descriptor *msosv2_desc;
58     struct usb_bos_descriptor *bos_desc;
59     struct usb_webusb_descriptor *webusb_url_desc;
60 #endif
61     /* Buffer used for storing standard, class and vendor request data */
62     USB_MEM_ALIGNX uint8_t req_data[USB_ALIGN_UP(CONFIG_USBDEV_REQUEST_BUFFER_LEN, CONFIG_USB_ALIGN_SIZE)];
63 
64     /** Currently selected configuration */
65     uint8_t configuration;
66     uint8_t device_address;
67     uint8_t ep0_next_state;
68     bool self_powered;
69     bool remote_wakeup_support;
70     bool remote_wakeup_enabled;
71     bool is_suspend;
72 #ifdef CONFIG_USBDEV_ADVANCE_DESC
73     uint8_t speed;
74 #endif
75 #ifdef CONFIG_USBDEV_TEST_MODE
76     bool test_req;
77 #endif
78 #ifdef CONFIG_USBDEV_EP0_THREAD
79     usb_osal_mq_t usbd_ep0_mq;
80     usb_osal_thread_t usbd_ep0_thread;
81 #endif
82     struct usbd_interface *intf[16];
83     uint8_t intf_altsetting[16];
84     uint8_t intf_offset;
85 
86     struct usbd_tx_rx_msg tx_msg[16];
87     struct usbd_tx_rx_msg rx_msg[16];
88 
89     void (*event_handler)(uint8_t busid, uint8_t event);
90 } g_usbd_core[CONFIG_USBDEV_MAX_BUS];
91 
92 struct usbd_bus g_usbdev_bus[CONFIG_USBDEV_MAX_BUS];
93 
94 static void usbd_class_event_notify_handler(uint8_t busid, uint8_t event, void *arg);
95 
usbd_print_setup(struct usb_setup_packet * setup)96 static void usbd_print_setup(struct usb_setup_packet *setup)
97 {
98     USB_LOG_ERR("Setup: "
99                 "bmRequestType 0x%02x, bRequest 0x%02x, wValue 0x%04x, wIndex 0x%04x, wLength 0x%04x\r\n",
100                 setup->bmRequestType,
101                 setup->bRequest,
102                 setup->wValue,
103                 setup->wIndex,
104                 setup->wLength);
105 }
106 
107 #if (CONFIG_USB_DBG_LEVEL >= USB_DBG_LOG)
108 static const char *usb_ep0_state_string[] = {
109     "setup",
110     "indata",
111     "outdata",
112     "instatus",
113     "outstatus"
114 };
115 #endif
116 
is_device_configured(uint8_t busid)117 static bool is_device_configured(uint8_t busid)
118 {
119     return (g_usbd_core[busid].configuration != 0);
120 }
121 
122 /**
123  * @brief configure and enable endpoint
124  *
125  * This function sets endpoint configuration according to one specified in USB
126  * endpoint descriptor and then enables it for data transfers.
127  *
128  * @param [in]  busid busid
129  * @param [in]  ep Endpoint descriptor byte array
130  *
131  * @return true if successfully configured and enabled
132  */
usbd_set_endpoint(uint8_t busid,const struct usb_endpoint_descriptor * ep)133 static bool usbd_set_endpoint(uint8_t busid, const struct usb_endpoint_descriptor *ep)
134 {
135     USB_LOG_DBG("Open ep:0x%02x type:%u mps:%u\r\n",
136                 ep->bEndpointAddress,
137                 USB_GET_ENDPOINT_TYPE(ep->bmAttributes),
138                 USB_GET_MAXPACKETSIZE(ep->wMaxPacketSize));
139 
140     if (ep->bEndpointAddress & 0x80) {
141         g_usbd_core[busid].tx_msg[ep->bEndpointAddress & 0x7f].ep_mps = USB_GET_MAXPACKETSIZE(ep->wMaxPacketSize);
142         g_usbd_core[busid].tx_msg[ep->bEndpointAddress & 0x7f].ep_mult = USB_GET_MULT(ep->wMaxPacketSize);
143     } else {
144         g_usbd_core[busid].rx_msg[ep->bEndpointAddress & 0x7f].ep_mps = USB_GET_MAXPACKETSIZE(ep->wMaxPacketSize);
145         g_usbd_core[busid].rx_msg[ep->bEndpointAddress & 0x7f].ep_mult = USB_GET_MULT(ep->wMaxPacketSize);
146     }
147 
148     return usbd_ep_open(busid, ep) == 0 ? true : false;
149 }
150 /**
151  * @brief Disable endpoint for transferring data
152  *
153  * This function cancels transfers that are associated with endpoint and
154  * disabled endpoint itself.
155  *
156  * @param [in]  busid busid
157  * @param [in]  ep Endpoint descriptor byte array
158  *
159  * @return true if successfully deconfigured and disabled
160  */
usbd_reset_endpoint(uint8_t busid,const struct usb_endpoint_descriptor * ep)161 static bool usbd_reset_endpoint(uint8_t busid, const struct usb_endpoint_descriptor *ep)
162 {
163     USB_LOG_DBG("Close ep:0x%02x type:%u\r\n",
164                 ep->bEndpointAddress,
165                 USB_GET_ENDPOINT_TYPE(ep->bmAttributes));
166 
167     return usbd_ep_close(busid, ep->bEndpointAddress) == 0 ? true : false;
168 }
169 
170 /**
171  * @brief get specified USB descriptor
172  *
173  * This function parses the list of installed USB descriptors and attempts
174  * to find the specified USB descriptor.
175  *
176  * @param [in]  busid busid
177  * @param [in]  type_index Type and index of the descriptor
178  * @param [out] data       Descriptor data
179  * @param [out] len        Descriptor length
180  *
181  * @return true if the descriptor was found, false otherwise
182  */
183 #ifdef CONFIG_USBDEV_ADVANCE_DESC
usbd_get_descriptor(uint8_t busid,uint16_t type_index,uint8_t ** data,uint32_t * len)184 static bool usbd_get_descriptor(uint8_t busid, uint16_t type_index, uint8_t **data, uint32_t *len)
185 {
186     uint8_t type = 0U;
187     uint8_t index = 0U;
188     bool found = true;
189     uint32_t desc_len = 0;
190     const char *string = NULL;
191     const uint8_t *desc = NULL;
192 
193     type = HI_BYTE(type_index);
194     index = LO_BYTE(type_index);
195 
196     switch (type) {
197         case USB_DESCRIPTOR_TYPE_DEVICE:
198             g_usbd_core[busid].speed = usbd_get_port_speed(busid); /* before we get device descriptor, we have known steady port speed */
199 
200             if (g_usbd_core[busid].descriptors->device_descriptor_callback == NULL) {
201                 found = false;
202                 break;
203             }
204             desc = g_usbd_core[busid].descriptors->device_descriptor_callback(g_usbd_core[busid].speed);
205             if (desc == NULL) {
206                 found = false;
207                 break;
208             }
209             desc_len = desc[0];
210             break;
211         case USB_DESCRIPTOR_TYPE_CONFIGURATION:
212             if (g_usbd_core[busid].descriptors->config_descriptor_callback == NULL) {
213                 found = false;
214                 break;
215             }
216             desc = g_usbd_core[busid].descriptors->config_descriptor_callback(g_usbd_core[busid].speed);
217             if (desc == NULL) {
218                 found = false;
219                 break;
220             }
221             desc_len = ((desc[CONF_DESC_wTotalLength]) | (desc[CONF_DESC_wTotalLength + 1] << 8));
222 
223             g_usbd_core[busid].self_powered = (desc[7] & USB_CONFIG_POWERED_MASK) ? true : false;
224             g_usbd_core[busid].remote_wakeup_support = (desc[7] & USB_CONFIG_REMOTE_WAKEUP) ? true : false;
225             break;
226         case USB_DESCRIPTOR_TYPE_STRING:
227             if (index == USB_OSDESC_STRING_DESC_INDEX) {
228                 if (!g_usbd_core[busid].descriptors->msosv1_descriptor) {
229                     found = false;
230                     break;
231                 }
232 
233                 desc = (uint8_t *)g_usbd_core[busid].descriptors->msosv1_descriptor->string;
234                 desc_len = g_usbd_core[busid].descriptors->msosv1_descriptor->string[0];
235             } else {
236                 if (g_usbd_core[busid].descriptors->string_descriptor_callback == NULL) {
237                     found = false;
238                     break;
239                 }
240                 string = g_usbd_core[busid].descriptors->string_descriptor_callback(g_usbd_core[busid].speed, index);
241                 if (string == NULL) {
242                     found = false;
243                     break;
244                 }
245 
246                 if (index == USB_STRING_LANGID_INDEX) {
247                     (*data)[0] = 4;
248                     (*data)[1] = USB_DESCRIPTOR_TYPE_STRING;
249                     (*data)[2] = string[0];
250                     (*data)[3] = string[1];
251 
252                     *len = 4;
253                     return true;
254                 }
255 
256                 uint16_t str_size = strlen(string);
257                 uint16_t total_size = 2 * str_size + 2;
258                 if (total_size > CONFIG_USBDEV_REQUEST_BUFFER_LEN) {
259                     USB_LOG_ERR("string size overflow\r\n");
260                     return false;
261                 }
262 
263                 (*data)[0] = total_size;
264                 (*data)[1] = USB_DESCRIPTOR_TYPE_STRING;
265 
266                 for (uint16_t i = 0; i < str_size; i++) {
267                     (*data)[2 * i + 2] = string[i];
268                     (*data)[2 * i + 3] = 0x00;
269                 }
270 
271                 *len = total_size;
272                 return true;
273             }
274             break;
275         case USB_DESCRIPTOR_TYPE_DEVICE_QUALIFIER:
276 #ifndef CONFIG_USB_HS
277             return false;
278 #else
279             if (g_usbd_core[busid].descriptors->device_quality_descriptor_callback == NULL) {
280                 found = false;
281                 break;
282             }
283             desc = g_usbd_core[busid].descriptors->device_quality_descriptor_callback(g_usbd_core[busid].speed);
284             if (desc == NULL) {
285                 found = false;
286                 break;
287             }
288             desc_len = desc[0];
289             break;
290 #endif
291         case USB_DESCRIPTOR_TYPE_OTHER_SPEED:
292             if (g_usbd_core[busid].descriptors->other_speed_descriptor_callback == NULL) {
293                 found = false;
294                 break;
295             }
296             desc = g_usbd_core[busid].descriptors->other_speed_descriptor_callback(g_usbd_core[busid].speed);
297             if (desc == NULL) {
298                 found = false;
299                 break;
300             }
301             desc_len = ((desc[CONF_DESC_wTotalLength]) | (desc[CONF_DESC_wTotalLength + 1] << 8));
302             break;
303 
304         case USB_DESCRIPTOR_TYPE_BINARY_OBJECT_STORE:
305             if (!g_usbd_core[busid].descriptors->bos_descriptor) {
306                 found = false;
307                 break;
308             }
309 
310             desc = (uint8_t *)g_usbd_core[busid].descriptors->bos_descriptor->string;
311             desc_len = g_usbd_core[busid].descriptors->bos_descriptor->string_len;
312             break;
313 
314         default:
315             found = false;
316             break;
317     }
318 
319     if (found == false) {
320         /* nothing found */
321         USB_LOG_ERR("descriptor <type:%x,index:%x> not found!\r\n", type, index);
322     } else {
323         *data = (uint8_t *)desc;
324         //memcpy(*data, desc, desc_len);
325         *len = desc_len;
326     }
327     return found;
328 }
329 #else
usbd_get_descriptor(uint8_t busid,uint16_t type_index,uint8_t ** data,uint32_t * len)330 static bool usbd_get_descriptor(uint8_t busid, uint16_t type_index, uint8_t **data, uint32_t *len)
331 {
332     uint8_t type = 0U;
333     uint8_t index = 0U;
334     uint8_t *p = NULL;
335     uint32_t cur_index = 0U;
336     bool found = false;
337 
338     type = HI_BYTE(type_index);
339     index = LO_BYTE(type_index);
340 
341     if ((type == USB_DESCRIPTOR_TYPE_STRING) && (index == USB_OSDESC_STRING_DESC_INDEX)) {
342         if (!g_usbd_core[busid].msosv1_desc) {
343             return false;
344         }
345 
346         *data = (uint8_t *)g_usbd_core[busid].msosv1_desc->string;
347         //memcpy(*data, (uint8_t *)g_usbd_core[busid].msosv1_desc->string, g_usbd_core[busid].msosv1_desc->string[0]);
348         *len = g_usbd_core[busid].msosv1_desc->string[0];
349 
350         return true;
351     } else if (type == USB_DESCRIPTOR_TYPE_BINARY_OBJECT_STORE) {
352         if (!g_usbd_core[busid].bos_desc) {
353             return false;
354         }
355 
356         *data = (uint8_t *)g_usbd_core[busid].bos_desc->string;
357         //memcpy(*data, (uint8_t *)g_usbd_core[busid].bos_desc->string, g_usbd_core[busid].bos_desc->string_len);
358         *len = g_usbd_core[busid].bos_desc->string_len;
359         return true;
360     }
361     /*
362      * Invalid types of descriptors,
363      * see USB Spec. Revision 2.0, 9.4.3 Get Descriptor
364      */
365     else if ((type == USB_DESCRIPTOR_TYPE_INTERFACE) || (type == USB_DESCRIPTOR_TYPE_ENDPOINT) ||
366 #ifndef CONFIG_USB_HS
367              (type > USB_DESCRIPTOR_TYPE_ENDPOINT)) {
368 #else
369              (type > USB_DESCRIPTOR_TYPE_OTHER_SPEED)) {
370 #endif
371         return false;
372     }
373 
374     p = (uint8_t *)g_usbd_core[busid].descriptors;
375 
376     cur_index = 0U;
377 
378     while (p[DESC_bLength] != 0U) {
379         if (p[DESC_bDescriptorType] == type) {
380             if (cur_index == index) {
381                 found = true;
382                 break;
383             }
384 
385             cur_index++;
386         }
387 
388         /* skip to next descriptor */
389         p += p[DESC_bLength];
390     }
391 
392     if (found) {
393         if ((type == USB_DESCRIPTOR_TYPE_CONFIGURATION) || ((type == USB_DESCRIPTOR_TYPE_OTHER_SPEED))) {
394             /* configuration or other speed descriptor is an
395              * exception, length is at offset 2 and 3
396              */
397             *len = (p[CONF_DESC_wTotalLength]) |
398                    (p[CONF_DESC_wTotalLength + 1] << 8);
399 
400             g_usbd_core[busid].self_powered = (p[7] & USB_CONFIG_POWERED_MASK) ? true : false;
401             g_usbd_core[busid].remote_wakeup_support = (p[7] & USB_CONFIG_REMOTE_WAKEUP) ? true : false;
402         } else {
403             /* normally length is at offset 0 */
404             *len = p[DESC_bLength];
405         }
406         *data = p;
407         //memcpy(*data, p, *len);
408     } else {
409         /* nothing found */
410         USB_LOG_ERR("descriptor <type:0x%02x,index:0x%02x> not found!\r\n", type, index);
411     }
412 
413     return found;
414 }
415 #endif
416 
417 /**
418  * @brief set USB configuration
419  *
420  * This function configures the device according to the specified configuration
421  * index and alternate setting by parsing the installed USB descriptor list.
422  * A configuration index of 0 unconfigures the device.
423  *
424  * @param [in] busid busid
425  * @param [in] config_index Configuration index
426  * @param [in] alt_setting  Alternate setting number
427  *
428  * @return true if successfully configured false if error or unconfigured
429  */
430 static bool usbd_set_configuration(uint8_t busid, uint8_t config_index, uint8_t alt_setting)
431 {
432     uint8_t cur_alt_setting = 0xFF;
433     uint8_t cur_config = 0xFF;
434     bool found = false;
435     const uint8_t *p;
436     uint32_t desc_len = 0;
437     uint32_t current_desc_len = 0;
438 
439 #ifdef CONFIG_USBDEV_ADVANCE_DESC
440     p = g_usbd_core[busid].descriptors->config_descriptor_callback(g_usbd_core[busid].speed);
441 #else
442     p = (uint8_t *)g_usbd_core[busid].descriptors;
443 #endif
444     /* configure endpoints for this configuration/altsetting */
445     while (p[DESC_bLength] != 0U) {
446         switch (p[DESC_bDescriptorType]) {
447             case USB_DESCRIPTOR_TYPE_CONFIGURATION:
448                 /* remember current configuration index */
449                 cur_config = p[CONF_DESC_bConfigurationValue];
450 
451                 if (cur_config == config_index) {
452                     found = true;
453 
454                     current_desc_len = 0;
455                     desc_len = (p[CONF_DESC_wTotalLength]) |
456                                (p[CONF_DESC_wTotalLength + 1] << 8);
457                 }
458 
459                 break;
460 
461             case USB_DESCRIPTOR_TYPE_INTERFACE:
462                 /* remember current alternate setting */
463                 cur_alt_setting =
464                     p[INTF_DESC_bAlternateSetting];
465                 break;
466 
467             case USB_DESCRIPTOR_TYPE_ENDPOINT:
468                 if ((cur_config != config_index) ||
469                     (cur_alt_setting != alt_setting)) {
470                     break;
471                 }
472 
473                 found = usbd_set_endpoint(busid, (struct usb_endpoint_descriptor *)p);
474                 break;
475 
476             default:
477                 break;
478         }
479 
480         /* skip to next descriptor */
481         current_desc_len += p[DESC_bLength];
482         p += p[DESC_bLength];
483         if (current_desc_len >= desc_len && desc_len) {
484             break;
485         }
486     }
487 
488     return found;
489 }
490 
491 /**
492  * @brief set USB interface
493  *
494  * @param [in] busid busid
495  * @param [in] iface Interface index
496  * @param [in] alt_setting  Alternate setting number
497  *
498  * @return true if successfully configured false if error or unconfigured
499  */
500 static bool usbd_set_interface(uint8_t busid, uint8_t iface, uint8_t alt_setting)
501 {
502     const uint8_t *if_desc = NULL;
503     struct usb_endpoint_descriptor *ep_desc;
504     uint8_t cur_alt_setting = 0xFF;
505     uint8_t cur_iface = 0xFF;
506     bool ret = false;
507     const uint8_t *p;
508     uint32_t desc_len = 0;
509     uint32_t current_desc_len = 0;
510 
511 #ifdef CONFIG_USBDEV_ADVANCE_DESC
512     p = g_usbd_core[busid].descriptors->config_descriptor_callback(g_usbd_core[busid].speed);
513 #else
514     p = (uint8_t *)g_usbd_core[busid].descriptors;
515 #endif
516     USB_LOG_DBG("iface %u alt_setting %u\r\n", iface, alt_setting);
517 
518     while (p[DESC_bLength] != 0U) {
519         switch (p[DESC_bDescriptorType]) {
520             case USB_DESCRIPTOR_TYPE_CONFIGURATION:
521                 current_desc_len = 0;
522                 desc_len = (p[CONF_DESC_wTotalLength]) |
523                            (p[CONF_DESC_wTotalLength + 1] << 8);
524 
525                 break;
526 
527             case USB_DESCRIPTOR_TYPE_INTERFACE:
528                 /* remember current alternate setting */
529                 cur_alt_setting = p[INTF_DESC_bAlternateSetting];
530                 cur_iface = p[INTF_DESC_bInterfaceNumber];
531 
532                 if (cur_iface == iface &&
533                     cur_alt_setting == alt_setting) {
534                     if_desc = (void *)p;
535                 }
536 
537                 break;
538 
539             case USB_DESCRIPTOR_TYPE_ENDPOINT:
540                 if (cur_iface == iface) {
541                     ep_desc = (struct usb_endpoint_descriptor *)p;
542 
543                     if (alt_setting == 0) {
544                         ret = usbd_reset_endpoint(busid, ep_desc);
545                     } else if (cur_alt_setting == alt_setting) {
546                         ret = usbd_set_endpoint(busid, ep_desc);
547                     } else {
548                     }
549                 }
550 
551                 break;
552 
553             default:
554                 break;
555         }
556 
557         /* skip to next descriptor */
558         current_desc_len += p[DESC_bLength];
559         p += p[DESC_bLength];
560         if (current_desc_len >= desc_len && desc_len) {
561             break;
562         }
563     }
564 
565     usbd_class_event_notify_handler(busid, USBD_EVENT_SET_INTERFACE, (void *)if_desc);
566 
567     return ret;
568 }
569 
570 /**
571  * @brief handle a standard device request
572  *
573  * @param [in]     busid    busid
574  * @param [in]     setup    The setup packet
575  * @param [in,out] data     Data buffer
576  * @param [in,out] len      Pointer to data length
577  *
578  * @return true if the request was handled successfully
579  */
580 static bool usbd_std_device_req_handler(uint8_t busid, struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
581 {
582     uint16_t value = setup->wValue;
583     bool ret = true;
584 
585     switch (setup->bRequest) {
586         case USB_REQUEST_GET_STATUS:
587             /* bit 0: self-powered */
588             /* bit 1: remote wakeup */
589             (*data)[0] = 0x00;
590             if (g_usbd_core[busid].self_powered) {
591                 (*data)[0] |= USB_GETSTATUS_SELF_POWERED;
592             }
593             if (g_usbd_core[busid].remote_wakeup_enabled) {
594                 (*data)[0] |= USB_GETSTATUS_REMOTE_WAKEUP;
595             }
596             (*data)[1] = 0x00;
597             *len = 2;
598             break;
599 
600         case USB_REQUEST_CLEAR_FEATURE:
601         case USB_REQUEST_SET_FEATURE:
602             if (value == USB_FEATURE_REMOTE_WAKEUP) {
603                 if (setup->bRequest == USB_REQUEST_SET_FEATURE) {
604                     g_usbd_core[busid].remote_wakeup_enabled = true;
605                     g_usbd_core[busid].event_handler(busid, USBD_EVENT_SET_REMOTE_WAKEUP);
606                 } else {
607                     g_usbd_core[busid].remote_wakeup_enabled = false;
608                     g_usbd_core[busid].event_handler(busid, USBD_EVENT_CLR_REMOTE_WAKEUP);
609                 }
610             } else if (value == USB_FEATURE_TEST_MODE) {
611 #ifdef CONFIG_USBDEV_TEST_MODE
612                 g_usbd_core[busid].test_req = true;
613 #endif
614             }
615             *len = 0;
616             break;
617 
618         case USB_REQUEST_SET_ADDRESS:
619             g_usbd_core[busid].device_address = value;
620             usbd_set_address(busid, value);
621             *len = 0;
622             break;
623 
624         case USB_REQUEST_GET_DESCRIPTOR:
625             ret = usbd_get_descriptor(busid, value, data, len);
626             break;
627 
628         case USB_REQUEST_SET_DESCRIPTOR:
629             ret = false;
630             break;
631 
632         case USB_REQUEST_GET_CONFIGURATION:
633             (*data)[0] = g_usbd_core[busid].configuration;
634             *len = 1;
635             break;
636 
637         case USB_REQUEST_SET_CONFIGURATION:
638             value &= 0xFF;
639 
640             if (value == 0) {
641                 g_usbd_core[busid].configuration = 0;
642             } else if (!usbd_set_configuration(busid, value, 0)) {
643                 ret = false;
644             } else {
645                 g_usbd_core[busid].configuration = value;
646                 g_usbd_core[busid].is_suspend = false;
647                 usbd_class_event_notify_handler(busid, USBD_EVENT_CONFIGURED, NULL);
648                 g_usbd_core[busid].event_handler(busid, USBD_EVENT_CONFIGURED);
649             }
650             *len = 0;
651             break;
652 
653         case USB_REQUEST_GET_INTERFACE:
654         case USB_REQUEST_SET_INTERFACE:
655             ret = false;
656             break;
657 
658         default:
659             ret = false;
660             break;
661     }
662 
663     return ret;
664 }
665 
666 /**
667  * @brief handle a standard interface request
668  *
669  * @param [in]     busid    busid
670  * @param [in]     setup    The setup packet
671  * @param [in,out] data     Data buffer
672  * @param [in,out] len      Pointer to data length
673  *
674  * @return true if the request was handled successfully
675  */
676 static bool usbd_std_interface_req_handler(uint8_t busid, struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
677 {
678     uint8_t type = HI_BYTE(setup->wValue);
679     uint8_t intf_num = LO_BYTE(setup->wIndex);
680     bool ret = true;
681     const uint8_t *p;
682     uint32_t desc_len = 0;
683     uint32_t current_desc_len = 0;
684     uint8_t cur_iface = 0xFF;
685 
686 #ifdef CONFIG_USBDEV_ADVANCE_DESC
687     p = g_usbd_core[busid].descriptors->config_descriptor_callback(g_usbd_core[busid].speed);
688 #else
689     p = (uint8_t *)g_usbd_core[busid].descriptors;
690 #endif
691 
692     /* Only when device is configured, then interface requests can be valid. */
693     if (!is_device_configured(busid)) {
694         return false;
695     }
696 
697     switch (setup->bRequest) {
698         case USB_REQUEST_GET_STATUS:
699             (*data)[0] = 0x00;
700             (*data)[1] = 0x00;
701             *len = 2;
702             break;
703 
704         case USB_REQUEST_GET_DESCRIPTOR:
705             if (type == 0x21) { /* HID_DESCRIPTOR_TYPE_HID */
706                 while (p[DESC_bLength] != 0U) {
707                     switch (p[DESC_bDescriptorType]) {
708                         case USB_DESCRIPTOR_TYPE_CONFIGURATION:
709                             current_desc_len = 0;
710                             desc_len = (p[CONF_DESC_wTotalLength]) |
711                                        (p[CONF_DESC_wTotalLength + 1] << 8);
712 
713                             break;
714 
715                         case USB_DESCRIPTOR_TYPE_INTERFACE:
716                             cur_iface = p[INTF_DESC_bInterfaceNumber];
717                             break;
718                         case 0x21:
719                             if (cur_iface == intf_num) {
720                                 *data = (uint8_t *)p;
721                                 //memcpy(*data, p, p[DESC_bLength]);
722                                 *len = p[DESC_bLength];
723                                 return true;
724                             }
725                             break;
726                         default:
727                             break;
728                     }
729 
730                     /* skip to next descriptor */
731                     current_desc_len += p[DESC_bLength];
732                     p += p[DESC_bLength];
733                     if (current_desc_len >= desc_len && desc_len) {
734                         break;
735                     }
736                 }
737             } else if (type == 0x22) { /* HID_DESCRIPTOR_TYPE_HID_REPORT */
738                 for (uint8_t i = 0; i < g_usbd_core[busid].intf_offset; i++) {
739                     struct usbd_interface *intf = g_usbd_core[busid].intf[i];
740 
741                     if (intf && (intf->intf_num == intf_num)) {
742                         *data = (uint8_t *)intf->hid_report_descriptor;
743                         //memcpy(*data, intf->hid_report_descriptor, intf->hid_report_descriptor_len);
744                         *len = intf->hid_report_descriptor_len;
745                         return true;
746                     }
747                 }
748             }
749             ret = false;
750             break;
751         case USB_REQUEST_CLEAR_FEATURE:
752         case USB_REQUEST_SET_FEATURE:
753             ret = false;
754             break;
755         case USB_REQUEST_GET_INTERFACE:
756             (*data)[0] = g_usbd_core[busid].intf_altsetting[intf_num];
757             *len = 1;
758             break;
759 
760         case USB_REQUEST_SET_INTERFACE:
761             g_usbd_core[busid].intf_altsetting[intf_num] = LO_BYTE(setup->wValue);
762             usbd_set_interface(busid, setup->wIndex, setup->wValue);
763             *len = 0;
764             break;
765 
766         default:
767             ret = false;
768             break;
769     }
770 
771     return ret;
772 }
773 
774 /**
775  * @brief handle a standard endpoint request
776  *
777  * @param [in]     busid    busid
778  * @param [in]     setup    The setup packet
779  * @param [in,out] data     Data buffer
780  * @param [in,out] len      Pointer to data length
781  *
782  * @return true if the request was handled successfully
783  */
784 static bool usbd_std_endpoint_req_handler(uint8_t busid, struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
785 {
786     uint8_t ep = (uint8_t)setup->wIndex;
787     bool ret = true;
788     uint8_t stalled;
789 
790     /* Only when device is configured, then endpoint requests can be valid. */
791     if (!is_device_configured(busid)) {
792         return false;
793     }
794 
795     switch (setup->bRequest) {
796         case USB_REQUEST_GET_STATUS:
797             usbd_ep_is_stalled(busid, ep, &stalled);
798             if (stalled) {
799                 (*data)[0] = 0x01;
800             } else {
801                 (*data)[0] = 0x00;
802             }
803             (*data)[1] = 0x00;
804             *len = 2;
805             break;
806         case USB_REQUEST_CLEAR_FEATURE:
807             if (setup->wValue == USB_FEATURE_ENDPOINT_HALT) {
808                 USB_LOG_ERR("ep:%02x clear halt\r\n", ep);
809 
810                 usbd_ep_clear_stall(busid, ep);
811                 break;
812             } else {
813                 ret = false;
814             }
815             *len = 0;
816             break;
817         case USB_REQUEST_SET_FEATURE:
818             if (setup->wValue == USB_FEATURE_ENDPOINT_HALT) {
819                 USB_LOG_ERR("ep:%02x set halt\r\n", ep);
820 
821                 usbd_ep_set_stall(busid, ep);
822             } else {
823                 ret = false;
824             }
825             *len = 0;
826             break;
827 
828         case USB_REQUEST_SYNCH_FRAME:
829             ret = false;
830             break;
831         default:
832             ret = false;
833             break;
834     }
835 
836     return ret;
837 }
838 
839 /**
840  * @brief handle standard requests (list in chapter 9)
841  *
842  * @param [in]     busid    busid
843  * @param [in]     setup    The setup packet
844  * @param [in,out] data     Data buffer
845  * @param [in,out] len      Pointer to data length
846  *
847  * @return true if the request was handled successfully
848  */
849 static int usbd_standard_request_handler(uint8_t busid, struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
850 {
851     int rc = 0;
852 
853     switch (setup->bmRequestType & USB_REQUEST_RECIPIENT_MASK) {
854         case USB_REQUEST_RECIPIENT_DEVICE:
855             if (usbd_std_device_req_handler(busid, setup, data, len) == false) {
856                 rc = -1;
857             }
858 
859             break;
860 
861         case USB_REQUEST_RECIPIENT_INTERFACE:
862             if (usbd_std_interface_req_handler(busid, setup, data, len) == false) {
863                 rc = -1;
864             }
865 
866             break;
867 
868         case USB_REQUEST_RECIPIENT_ENDPOINT:
869             if (usbd_std_endpoint_req_handler(busid, setup, data, len) == false) {
870                 rc = -1;
871             }
872 
873             break;
874 
875         default:
876             rc = -1;
877             break;
878     }
879 
880     return rc;
881 }
882 
883 /**
884  * @brief handler for class requests
885  *
886  * @param [in]     busid    busid
887  * @param [in]     setup    The setup packet
888  * @param [in,out] data     Data buffer
889  * @param [in,out] len      Pointer to data length
890  *
891  * @return true if the request was handled successfully
892  */
893 static int usbd_class_request_handler(uint8_t busid, struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
894 {
895     if ((setup->bmRequestType & USB_REQUEST_RECIPIENT_MASK) == USB_REQUEST_RECIPIENT_INTERFACE) {
896         for (uint8_t i = 0; i < g_usbd_core[busid].intf_offset; i++) {
897             struct usbd_interface *intf = g_usbd_core[busid].intf[i];
898 
899             if (intf && intf->class_interface_handler && (intf->intf_num == (setup->wIndex & 0xFF))) {
900                 return intf->class_interface_handler(busid, setup, data, len);
901             }
902         }
903     } else if ((setup->bmRequestType & USB_REQUEST_RECIPIENT_MASK) == USB_REQUEST_RECIPIENT_ENDPOINT) {
904         for (uint8_t i = 0; i < g_usbd_core[busid].intf_offset; i++) {
905             struct usbd_interface *intf = g_usbd_core[busid].intf[i];
906 
907             if (intf && intf->class_endpoint_handler) {
908                 return intf->class_endpoint_handler(busid, setup, data, len);
909             }
910         }
911     }
912     return -1;
913 }
914 
915 /**
916  * @brief handler for vendor requests
917  *
918  * @param [in]     busid    busid
919  * @param [in]     setup    The setup packet
920  * @param [in,out] data     Data buffer
921  * @param [in,out] len      Pointer to data length
922  *
923  * @return true if the request was handled successfully
924  */
925 static int usbd_vendor_request_handler(uint8_t busid, struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
926 {
927     uint32_t desclen;
928 #ifdef CONFIG_USBDEV_ADVANCE_DESC
929     if (g_usbd_core[busid].descriptors->msosv1_descriptor) {
930         if (setup->bRequest == g_usbd_core[busid].descriptors->msosv1_descriptor->vendor_code) {
931             switch (setup->wIndex) {
932                 case 0x04:
933                     desclen = g_usbd_core[busid].descriptors->msosv1_descriptor->compat_id[0] +
934                               (g_usbd_core[busid].descriptors->msosv1_descriptor->compat_id[1] << 8) +
935                               (g_usbd_core[busid].descriptors->msosv1_descriptor->compat_id[2] << 16) +
936                               (g_usbd_core[busid].descriptors->msosv1_descriptor->compat_id[3] << 24);
937 
938                     *data = (uint8_t *)g_usbd_core[busid].descriptors->msosv1_descriptor->compat_id;
939                     //memcpy(*data, g_usbd_core[busid].descriptors->msosv1_descriptor->compat_id, desclen);
940                     *len = desclen;
941                     return 0;
942                 case 0x05:
943                     desclen = g_usbd_core[busid].descriptors->msosv1_descriptor->comp_id_property[setup->wValue][0] +
944                               (g_usbd_core[busid].descriptors->msosv1_descriptor->comp_id_property[setup->wValue][1] << 8) +
945                               (g_usbd_core[busid].descriptors->msosv1_descriptor->comp_id_property[setup->wValue][2] << 16) +
946                               (g_usbd_core[busid].descriptors->msosv1_descriptor->comp_id_property[setup->wValue][3] << 24);
947 
948                     *data = (uint8_t *)g_usbd_core[busid].descriptors->msosv1_descriptor->comp_id_property[setup->wValue];
949                     //memcpy(*data, g_usbd_core[busid].descriptors->msosv1_descriptor->comp_id_property[setup->wValue], desclen);
950                     *len = desclen;
951                     return 0;
952                 default:
953                     return -1;
954             }
955         }
956     } else if (g_usbd_core[busid].descriptors->msosv2_descriptor) {
957         if (setup->bRequest == g_usbd_core[busid].descriptors->msosv2_descriptor->vendor_code) {
958             switch (setup->wIndex) {
959                 case WINUSB_REQUEST_GET_DESCRIPTOR_SET:
960                     desclen = g_usbd_core[busid].descriptors->msosv2_descriptor->compat_id_len;
961                     *data = (uint8_t *)g_usbd_core[busid].descriptors->msosv2_descriptor->compat_id;
962                     //memcpy(*data, g_usbd_core[busid].descriptors->msosv2_descriptor->compat_id, desclen);
963                     *len = g_usbd_core[busid].descriptors->msosv2_descriptor->compat_id_len;
964                     return 0;
965                 default:
966                     return -1;
967             }
968         }
969     }
970 
971     if (g_usbd_core[busid].descriptors->webusb_url_descriptor) {
972         if (setup->bRequest == g_usbd_core[busid].descriptors->webusb_url_descriptor->vendor_code) {
973             switch (setup->wIndex) {
974                 case WEBUSB_REQUEST_GET_URL:
975                     desclen = g_usbd_core[busid].descriptors->webusb_url_descriptor->string_len;
976                     *data = (uint8_t *)g_usbd_core[busid].descriptors->webusb_url_descriptor->string;
977                     //memcpy(*data, g_usbd_core[busid].descriptors->webusb_url_descriptor->string, desclen);
978                     *len = desclen;
979                     return 0;
980                 default:
981                     return -1;
982             }
983         }
984     }
985 #else
986     if (g_usbd_core[busid].msosv1_desc) {
987         if (setup->bRequest == g_usbd_core[busid].msosv1_desc->vendor_code) {
988             switch (setup->wIndex) {
989                 case 0x04:
990                     *data = (uint8_t *)g_usbd_core[busid].msosv1_desc->compat_id;
991                     desclen = g_usbd_core[busid].msosv1_desc->compat_id[0] +
992                               (g_usbd_core[busid].msosv1_desc->compat_id[1] << 8) +
993                               (g_usbd_core[busid].msosv1_desc->compat_id[2] << 16) +
994                               (g_usbd_core[busid].msosv1_desc->compat_id[3] << 24);
995                     //memcpy(*data, g_usbd_core[busid].msosv1_desc->compat_id, desclen);
996                     *len = desclen;
997                     return 0;
998                 case 0x05:
999                     *data = (uint8_t *)g_usbd_core[busid].msosv1_desc->comp_id_property[setup->wValue];
1000                     desclen = g_usbd_core[busid].msosv1_desc->comp_id_property[setup->wValue][0] +
1001                               (g_usbd_core[busid].msosv1_desc->comp_id_property[setup->wValue][1] << 8) +
1002                               (g_usbd_core[busid].msosv1_desc->comp_id_property[setup->wValue][2] << 16) +
1003                               (g_usbd_core[busid].msosv1_desc->comp_id_property[setup->wValue][3] << 24);
1004                     //memcpy(*data, g_usbd_core[busid].msosv1_desc->comp_id_property[setup->wValue], desclen);
1005                     *len = desclen;
1006                     return 0;
1007                 default:
1008                     return -1;
1009             }
1010         }
1011     } else if (g_usbd_core[busid].msosv2_desc) {
1012         if (setup->bRequest == g_usbd_core[busid].msosv2_desc->vendor_code) {
1013             switch (setup->wIndex) {
1014                 case WINUSB_REQUEST_GET_DESCRIPTOR_SET:
1015                     *data = (uint8_t *)g_usbd_core[busid].msosv2_desc->compat_id;
1016                     //memcpy(*data, g_usbd_core[busid].msosv2_desc->compat_id, g_usbd_core[busid].msosv2_desc->compat_id_len);
1017                     *len = g_usbd_core[busid].msosv2_desc->compat_id_len;
1018                     return 0;
1019                 default:
1020                     return -1;
1021             }
1022         }
1023     }
1024 
1025     if (g_usbd_core[busid].webusb_url_desc) {
1026         if (setup->bRequest == g_usbd_core[busid].webusb_url_desc->vendor_code) {
1027             switch (setup->wIndex) {
1028                 case WEBUSB_REQUEST_GET_URL:
1029                     desclen = g_usbd_core[busid].webusb_url_desc->string_len;
1030                     *data = (uint8_t *)g_usbd_core[busid].webusb_url_desc->string;
1031                     //memcpy(*data, g_usbd_core[busid].webusb_url_desc->string, desclen);
1032                     *len = desclen;
1033                     return 0;
1034                 default:
1035                     return -1;
1036             }
1037         }
1038     }
1039 #endif
1040     for (uint8_t i = 0; i < g_usbd_core[busid].intf_offset; i++) {
1041         struct usbd_interface *intf = g_usbd_core[busid].intf[i];
1042 
1043         if (intf && intf->vendor_handler && (intf->vendor_handler(busid, setup, data, len) == 0)) {
1044             return 0;
1045         }
1046     }
1047 
1048     return -1;
1049 }
1050 
1051 /**
1052  * @brief handle setup request( standard/class/vendor/other)
1053  *
1054  * @param [in]     busid busid
1055  * @param [in]     setup The setup packet
1056  * @param [in,out] data  Data buffer
1057  * @param [in,out] len   Pointer to data length
1058  *
1059  * @return true if the request was handles successfully
1060  */
1061 static bool usbd_setup_request_handler(uint8_t busid, struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
1062 {
1063     switch (setup->bmRequestType & USB_REQUEST_TYPE_MASK) {
1064         case USB_REQUEST_STANDARD:
1065             if (usbd_standard_request_handler(busid, setup, data, len) < 0) {
1066                 /* Ignore error log for getting Device Qualifier Descriptor request */
1067                 if ((setup->bRequest == 0x06) && (setup->wValue == 0x0600)) {
1068                     //USB_LOG_DBG("Ignore DQD in fs\r\n");
1069                     return false;
1070                 }
1071                 USB_LOG_ERR("standard request error\r\n");
1072                 usbd_print_setup(setup);
1073                 return false;
1074             }
1075             break;
1076         case USB_REQUEST_CLASS:
1077             if (usbd_class_request_handler(busid, setup, data, len) < 0) {
1078                 USB_LOG_ERR("class request error\r\n");
1079                 usbd_print_setup(setup);
1080                 return false;
1081             }
1082             break;
1083         case USB_REQUEST_VENDOR:
1084             if (usbd_vendor_request_handler(busid, setup, data, len) < 0) {
1085                 USB_LOG_ERR("vendor request error\r\n");
1086                 usbd_print_setup(setup);
1087                 return false;
1088             }
1089             break;
1090 
1091         default:
1092             return false;
1093     }
1094 
1095     return true;
1096 }
1097 
1098 static void usbd_class_event_notify_handler(uint8_t busid, uint8_t event, void *arg)
1099 {
1100     for (uint8_t i = 0; i < g_usbd_core[busid].intf_offset; i++) {
1101         struct usbd_interface *intf = g_usbd_core[busid].intf[i];
1102 
1103         if (arg) {
1104             struct usb_interface_descriptor *desc = (struct usb_interface_descriptor *)arg;
1105             if (intf && intf->notify_handler && (desc->bInterfaceNumber == (intf->intf_num))) {
1106                 intf->notify_handler(busid, event, arg);
1107             }
1108         } else {
1109             if (intf && intf->notify_handler) {
1110                 intf->notify_handler(busid, event, arg);
1111             }
1112         }
1113     }
1114 }
1115 
1116 void usbd_event_sof_handler(uint8_t busid)
1117 {
1118     g_usbd_core[busid].event_handler(busid, USBD_EVENT_SOF);
1119 }
1120 
1121 void usbd_event_connect_handler(uint8_t busid)
1122 {
1123     g_usbd_core[busid].event_handler(busid, USBD_EVENT_CONNECTED);
1124 }
1125 
1126 void usbd_event_disconnect_handler(uint8_t busid)
1127 {
1128     g_usbd_core[busid].configuration = 0;
1129     g_usbd_core[busid].event_handler(busid, USBD_EVENT_DISCONNECTED);
1130 }
1131 
1132 void usbd_event_resume_handler(uint8_t busid)
1133 {
1134     g_usbd_core[busid].is_suspend = false;
1135     g_usbd_core[busid].event_handler(busid, USBD_EVENT_RESUME);
1136 }
1137 
1138 void usbd_event_suspend_handler(uint8_t busid)
1139 {
1140     if (g_usbd_core[busid].device_address > 0) {
1141         g_usbd_core[busid].is_suspend = true;
1142         g_usbd_core[busid].event_handler(busid, USBD_EVENT_SUSPEND);
1143     }
1144 }
1145 
1146 void usbd_event_reset_handler(uint8_t busid)
1147 {
1148     usbd_set_address(busid, 0);
1149     g_usbd_core[busid].device_address = 0;
1150     g_usbd_core[busid].configuration = 0;
1151     g_usbd_core[busid].ep0_next_state = USBD_EP0_STATE_SETUP;
1152 #ifdef CONFIG_USBDEV_ADVANCE_DESC
1153     g_usbd_core[busid].speed = USB_SPEED_UNKNOWN;
1154 #endif
1155     struct usb_endpoint_descriptor ep0;
1156 
1157     ep0.bLength = 7;
1158     ep0.bDescriptorType = USB_DESCRIPTOR_TYPE_ENDPOINT;
1159     ep0.wMaxPacketSize = USB_CTRL_EP_MPS;
1160     ep0.bmAttributes = USB_ENDPOINT_TYPE_CONTROL;
1161     ep0.bEndpointAddress = USB_CONTROL_IN_EP0;
1162     ep0.bInterval = 0;
1163     usbd_ep_open(busid, &ep0);
1164 
1165     ep0.bEndpointAddress = USB_CONTROL_OUT_EP0;
1166     usbd_ep_open(busid, &ep0);
1167 
1168     usbd_class_event_notify_handler(busid, USBD_EVENT_RESET, NULL);
1169     g_usbd_core[busid].event_handler(busid, USBD_EVENT_RESET);
1170 }
1171 
1172 static void __usbd_event_ep0_setup_complete_handler(uint8_t busid, struct usb_setup_packet *setup)
1173 {
1174     uint8_t *buf;
1175 
1176     USB_LOG_DBG("[%s] 0x%02x 0x%02x 0x%04x 0x%04x 0x%04x\r\n",
1177                 usb_ep0_state_string[usbd_get_ep0_next_state(busid)],
1178                 setup->bmRequestType,
1179                 setup->bRequest,
1180                 setup->wValue,
1181                 setup->wIndex,
1182                 setup->wLength);
1183 
1184     if (setup->wLength > CONFIG_USBDEV_REQUEST_BUFFER_LEN) {
1185         if ((setup->bmRequestType & USB_REQUEST_DIR_MASK) == USB_REQUEST_DIR_OUT) {
1186             USB_LOG_ERR("Request buffer too small\r\n");
1187             usbd_ep_set_stall(busid, USB_CONTROL_IN_EP0);
1188             return;
1189         }
1190     }
1191 
1192     g_usbd_core[busid].ep0_data_buf = g_usbd_core[busid].req_data;
1193     g_usbd_core[busid].ep0_data_buf_residue = setup->wLength;
1194     g_usbd_core[busid].ep0_data_buf_len = setup->wLength;
1195     g_usbd_core[busid].zlp_flag = false;
1196     buf = g_usbd_core[busid].ep0_data_buf;
1197 
1198     /* handle class request when all the data is received */
1199     if (setup->wLength && ((setup->bmRequestType & USB_REQUEST_DIR_MASK) == USB_REQUEST_DIR_OUT)) {
1200         USB_LOG_DBG("Start reading %d bytes from ep0\r\n", setup->wLength);
1201         g_usbd_core[busid].ep0_next_state = USBD_EP0_STATE_OUT_DATA;
1202         usbd_ep_start_read(busid, USB_CONTROL_OUT_EP0, g_usbd_core[busid].ep0_data_buf, setup->wLength);
1203         return;
1204     }
1205 
1206     /* Ask installed handler to process request */
1207     if (!usbd_setup_request_handler(busid, setup, &buf, &g_usbd_core[busid].ep0_data_buf_len)) {
1208         g_usbd_core[busid].ep0_next_state = USBD_EP0_STATE_SETUP;
1209         usbd_ep_set_stall(busid, USB_CONTROL_IN_EP0);
1210         return;
1211     }
1212 
1213     /* Send smallest of requested and offered length */
1214     g_usbd_core[busid].ep0_data_buf_residue = MIN(g_usbd_core[busid].ep0_data_buf_len, setup->wLength);
1215     if (g_usbd_core[busid].ep0_data_buf_residue > CONFIG_USBDEV_REQUEST_BUFFER_LEN) {
1216         USB_LOG_ERR("Request buffer too small\r\n");
1217         g_usbd_core[busid].ep0_next_state = USBD_EP0_STATE_SETUP;
1218         usbd_ep_set_stall(busid, USB_CONTROL_IN_EP0);
1219         return;
1220     }
1221 
1222     /* use *data = xxx; g_usbd_core[busid].ep0_data_buf records real data address, we should copy data into ep0 buffer.
1223      * Why we should copy once? because some chips are not access to flash with dma if real data address is in flash address(such as ch32).
1224      */
1225     if (buf != g_usbd_core[busid].ep0_data_buf) {
1226 #ifdef CONFIG_USBDEV_EP0_INDATA_NO_COPY
1227         g_usbd_core[busid].ep0_data_buf = buf;
1228 #else
1229         usb_memcpy(g_usbd_core[busid].ep0_data_buf, buf, g_usbd_core[busid].ep0_data_buf_residue);
1230 #endif
1231     } else {
1232         /* use memcpy(*data, xxx, len); has copied into ep0 buffer, we do nothing */
1233     }
1234 
1235     if (g_usbd_core[busid].ep0_data_buf_residue > 0) {
1236         g_usbd_core[busid].ep0_next_state = USBD_EP0_STATE_IN_DATA;
1237     } else {
1238         g_usbd_core[busid].ep0_next_state = USBD_EP0_STATE_IN_STATUS;
1239     }
1240 
1241     /* Send data or status to host */
1242     usbd_ep_start_write(busid, USB_CONTROL_IN_EP0, g_usbd_core[busid].ep0_data_buf, g_usbd_core[busid].ep0_data_buf_residue);
1243     /*
1244     * Set ZLP flag when host asks for a bigger length and the data size is
1245     * multiplier of USB_CTRL_EP_MPS, to indicate the transfer done after zlp
1246     * sent.
1247     */
1248     if ((setup->wLength > g_usbd_core[busid].ep0_data_buf_len) && (!(g_usbd_core[busid].ep0_data_buf_len % USB_CTRL_EP_MPS))) {
1249         g_usbd_core[busid].zlp_flag = true;
1250     }
1251 }
1252 
1253 void usbd_event_ep0_setup_complete_handler(uint8_t busid, uint8_t *psetup)
1254 {
1255     struct usb_setup_packet *setup = &g_usbd_core[busid].setup;
1256 
1257     memcpy(setup, psetup, 8);
1258 
1259 #ifdef CONFIG_USBDEV_EP0_THREAD
1260     usb_osal_mq_send(g_usbd_core[busid].usbd_ep0_mq, USB_EP0_STATE_SETUP);
1261 #else
1262     __usbd_event_ep0_setup_complete_handler(busid, setup);
1263 #endif
1264 }
1265 
1266 static void usbd_event_ep0_in_complete_handler(uint8_t busid, uint8_t ep, uint32_t nbytes)
1267 {
1268     struct usb_setup_packet *setup = &g_usbd_core[busid].setup;
1269 
1270     (void)ep;
1271 
1272     g_usbd_core[busid].ep0_data_buf += nbytes;
1273     g_usbd_core[busid].ep0_data_buf_residue -= nbytes;
1274 
1275     USB_LOG_DBG("[%s] in %d bytes, %d remained\r\n",
1276                 usb_ep0_state_string[usbd_get_ep0_next_state(busid)],
1277                 (unsigned int)nbytes,
1278                 (unsigned int)g_usbd_core[busid].ep0_data_buf_residue);
1279 
1280     if (g_usbd_core[busid].ep0_data_buf_residue != 0) {
1281         /* Start sending the remain data */
1282         usbd_ep_start_write(busid, USB_CONTROL_IN_EP0, g_usbd_core[busid].ep0_data_buf, g_usbd_core[busid].ep0_data_buf_residue);
1283     } else {
1284         if (g_usbd_core[busid].zlp_flag == true) {
1285             g_usbd_core[busid].zlp_flag = false;
1286             /* Send zlp to host */
1287             USB_LOG_DBG("EP0 Send zlp\r\n");
1288             usbd_ep_start_write(busid, USB_CONTROL_IN_EP0, NULL, 0);
1289         } else {
1290             /* Satisfying three conditions will jump here.
1291                 * 1. send status completely
1292                 * 2. send zlp completely
1293                 * 3. send last data completely.
1294                 */
1295             if (setup->wLength && ((setup->bmRequestType & USB_REQUEST_DIR_MASK) == USB_REQUEST_DIR_IN)) {
1296                 /* if all data has sent completely, start reading out status */
1297                 g_usbd_core[busid].ep0_next_state = USBD_EP0_STATE_OUT_STATUS;
1298                 usbd_ep_start_read(busid, USB_CONTROL_OUT_EP0, NULL, 0);
1299                 return;
1300             }
1301 
1302             if (g_usbd_core[busid].ep0_next_state == USBD_EP0_STATE_IN_STATUS) {
1303                 g_usbd_core[busid].ep0_next_state = USBD_EP0_STATE_SETUP;
1304             }
1305 
1306 #ifdef CONFIG_USBDEV_TEST_MODE
1307             if (g_usbd_core[busid].test_req) {
1308                 usbd_execute_test_mode(busid, HI_BYTE(setup->wIndex));
1309                 g_usbd_core[busid].test_req = false;
1310             }
1311 #endif
1312         }
1313     }
1314 }
1315 
1316 static void usbd_event_ep0_out_complete_handler(uint8_t busid, uint8_t ep, uint32_t nbytes)
1317 {
1318     struct usb_setup_packet *setup = &g_usbd_core[busid].setup;
1319 
1320     (void)ep;
1321     (void)setup;
1322 
1323     USB_LOG_DBG("[%s] out %d bytes, %d remained\r\n",
1324                 usb_ep0_state_string[usbd_get_ep0_next_state(busid)],
1325                 (unsigned int)nbytes,
1326                 (unsigned int)g_usbd_core[busid].ep0_data_buf_residue);
1327 
1328     if (nbytes > 0) {
1329         g_usbd_core[busid].ep0_data_buf += nbytes;
1330         g_usbd_core[busid].ep0_data_buf_residue -= nbytes;
1331 
1332         if (g_usbd_core[busid].ep0_data_buf_residue == 0) {
1333 #ifdef CONFIG_USBDEV_EP0_THREAD
1334             usb_osal_mq_send(g_usbd_core[busid].usbd_ep0_mq, USB_EP0_STATE_OUT);
1335 #else
1336             /* Received all, send data to handler */
1337             g_usbd_core[busid].ep0_data_buf = g_usbd_core[busid].req_data;
1338             if (!usbd_setup_request_handler(busid, setup, &g_usbd_core[busid].ep0_data_buf, &g_usbd_core[busid].ep0_data_buf_len)) {
1339                 g_usbd_core[busid].ep0_next_state = USBD_EP0_STATE_SETUP;
1340                 usbd_ep_set_stall(busid, USB_CONTROL_IN_EP0);
1341                 return;
1342             }
1343 
1344             g_usbd_core[busid].ep0_next_state = USBD_EP0_STATE_IN_STATUS;
1345             /*Send status to host*/
1346             usbd_ep_start_write(busid, USB_CONTROL_IN_EP0, NULL, 0);
1347 #endif
1348         } else {
1349             /* Start reading the remain data */
1350             usbd_ep_start_read(busid, USB_CONTROL_OUT_EP0, g_usbd_core[busid].ep0_data_buf, g_usbd_core[busid].ep0_data_buf_residue);
1351         }
1352     } else {
1353         /* Read out status completely, do nothing */
1354         g_usbd_core[busid].ep0_next_state = USBD_EP0_STATE_SETUP;
1355     }
1356 }
1357 
1358 void usbd_event_ep_in_complete_handler(uint8_t busid, uint8_t ep, uint32_t nbytes)
1359 {
1360     if (g_usbd_core[busid].tx_msg[ep & 0x7f].cb) {
1361         g_usbd_core[busid].tx_msg[ep & 0x7f].cb(busid, ep, nbytes);
1362     }
1363 }
1364 
1365 void usbd_event_ep_out_complete_handler(uint8_t busid, uint8_t ep, uint32_t nbytes)
1366 {
1367     if (g_usbd_core[busid].rx_msg[ep & 0x7f].cb) {
1368         g_usbd_core[busid].rx_msg[ep & 0x7f].cb(busid, ep, nbytes);
1369     }
1370 }
1371 
1372 #ifdef CONFIG_USBDEV_ADVANCE_DESC
1373 void usbd_desc_register(uint8_t busid, const struct usb_descriptor *desc)
1374 {
1375     memset(&g_usbd_core[busid], 0, sizeof(struct usbd_core_priv));
1376 
1377     g_usbd_core[busid].descriptors = desc;
1378     g_usbd_core[busid].intf_offset = 0;
1379 
1380     g_usbd_core[busid].tx_msg[0].ep = 0x80;
1381     g_usbd_core[busid].tx_msg[0].cb = usbd_event_ep0_in_complete_handler;
1382     g_usbd_core[busid].rx_msg[0].ep = 0x00;
1383     g_usbd_core[busid].rx_msg[0].cb = usbd_event_ep0_out_complete_handler;
1384 }
1385 #else
1386 void usbd_desc_register(uint8_t busid, const uint8_t *desc)
1387 {
1388     memset(&g_usbd_core[busid], 0, sizeof(struct usbd_core_priv));
1389 
1390     g_usbd_core[busid].descriptors = desc;
1391     g_usbd_core[busid].intf_offset = 0;
1392 
1393     g_usbd_core[busid].tx_msg[0].ep = 0x80;
1394     g_usbd_core[busid].tx_msg[0].cb = usbd_event_ep0_in_complete_handler;
1395     g_usbd_core[busid].rx_msg[0].ep = 0x00;
1396     g_usbd_core[busid].rx_msg[0].cb = usbd_event_ep0_out_complete_handler;
1397 }
1398 
1399 /* Register MS OS Descriptors version 1 */
1400 void usbd_msosv1_desc_register(uint8_t busid, struct usb_msosv1_descriptor *desc)
1401 {
1402     g_usbd_core[busid].msosv1_desc = desc;
1403 }
1404 
1405 /* Register MS OS Descriptors version 2 */
1406 void usbd_msosv2_desc_register(uint8_t busid, struct usb_msosv2_descriptor *desc)
1407 {
1408     g_usbd_core[busid].msosv2_desc = desc;
1409 }
1410 
1411 void usbd_bos_desc_register(uint8_t busid, struct usb_bos_descriptor *desc)
1412 {
1413     g_usbd_core[busid].bos_desc = desc;
1414 }
1415 
1416 void usbd_webusb_desc_register(uint8_t busid, struct usb_webusb_descriptor *desc)
1417 {
1418     g_usbd_core[busid].webusb_url_desc = desc;
1419 }
1420 #endif
1421 
1422 void usbd_add_interface(uint8_t busid, struct usbd_interface *intf)
1423 {
1424     intf->intf_num = g_usbd_core[busid].intf_offset;
1425     g_usbd_core[busid].intf[g_usbd_core[busid].intf_offset] = intf;
1426     g_usbd_core[busid].intf_offset++;
1427 }
1428 
1429 void usbd_add_endpoint(uint8_t busid, struct usbd_endpoint *ep)
1430 {
1431     if (ep->ep_addr & 0x80) {
1432         g_usbd_core[busid].tx_msg[ep->ep_addr & 0x7f].ep = ep->ep_addr;
1433         g_usbd_core[busid].tx_msg[ep->ep_addr & 0x7f].cb = ep->ep_cb;
1434     } else {
1435         g_usbd_core[busid].rx_msg[ep->ep_addr & 0x7f].ep = ep->ep_addr;
1436         g_usbd_core[busid].rx_msg[ep->ep_addr & 0x7f].cb = ep->ep_cb;
1437     }
1438 }
1439 
1440 uint16_t usbd_get_ep_mps(uint8_t busid, uint8_t ep)
1441 {
1442     if (ep & 0x80) {
1443         return g_usbd_core[busid].tx_msg[ep & 0x7f].ep_mps;
1444     } else {
1445         return g_usbd_core[busid].rx_msg[ep & 0x7f].ep_mps;
1446     }
1447 }
1448 
1449 uint8_t usbd_get_ep_mult(uint8_t busid, uint8_t ep)
1450 {
1451     if (ep & 0x80) {
1452         return g_usbd_core[busid].tx_msg[ep & 0x7f].ep_mult;
1453     } else {
1454         return g_usbd_core[busid].rx_msg[ep & 0x7f].ep_mult;
1455     }
1456 }
1457 
1458 bool usb_device_is_configured(uint8_t busid)
1459 {
1460     return g_usbd_core[busid].configuration;
1461 }
1462 
1463 bool usb_device_is_suspend(uint8_t busid)
1464 {
1465     return g_usbd_core[busid].is_suspend;
1466 }
1467 
1468 int usbd_send_remote_wakeup(uint8_t busid)
1469 {
1470     if (g_usbd_core[busid].remote_wakeup_support && g_usbd_core[busid].remote_wakeup_enabled && g_usbd_core[busid].is_suspend) {
1471         return usbd_set_remote_wakeup(busid);
1472     } else {
1473         if (!g_usbd_core[busid].remote_wakeup_support) {
1474             USB_LOG_ERR("device does not support remote wakeup\r\n");
1475         }
1476         if (!g_usbd_core[busid].remote_wakeup_enabled) {
1477             USB_LOG_ERR("device remote wakeup is not enabled\r\n");
1478         }
1479         if (!g_usbd_core[busid].is_suspend) {
1480             USB_LOG_ERR("device is not in suspend state\r\n");
1481         }
1482         return -1;
1483     }
1484 }
1485 
1486 uint8_t usbd_get_ep0_next_state(uint8_t busid)
1487 {
1488     return g_usbd_core[busid].ep0_next_state;
1489 }
1490 
1491 #ifdef CONFIG_USBDEV_EP0_THREAD
1492 static void usbdev_ep0_thread(CONFIG_USB_OSAL_THREAD_SET_ARGV)
1493 {
1494     uintptr_t event;
1495     int ret;
1496     uint8_t busid = (uint8_t)CONFIG_USB_OSAL_THREAD_GET_ARGV;
1497     struct usb_setup_packet *setup = &g_usbd_core[busid].setup;
1498 
1499     while (1) {
1500         ret = usb_osal_mq_recv(g_usbd_core[busid].usbd_ep0_mq, (uintptr_t *)&event, USB_OSAL_WAITING_FOREVER);
1501         if (ret < 0) {
1502             continue;
1503         }
1504         USB_LOG_DBG("event:%d\r\n", (unsigned int)event);
1505 
1506         switch (event) {
1507             case USB_EP0_STATE_SETUP:
1508                 __usbd_event_ep0_setup_complete_handler(busid, setup);
1509                 break;
1510             case USB_EP0_STATE_IN:
1511                 // do nothing
1512                 break;
1513             case USB_EP0_STATE_OUT:
1514                 /* Received all, send data to handler */
1515                 g_usbd_core[busid].ep0_data_buf = g_usbd_core[busid].req_data;
1516                 if (!usbd_setup_request_handler(busid, setup, &g_usbd_core[busid].ep0_data_buf, &g_usbd_core[busid].ep0_data_buf_len)) {
1517                     g_usbd_core[busid].ep0_next_state = USBD_EP0_STATE_SETUP;
1518                     usbd_ep_set_stall(busid, USB_CONTROL_IN_EP0);
1519                     continue;
1520                 }
1521 
1522                 g_usbd_core[busid].ep0_next_state = USBD_EP0_STATE_IN_STATUS;
1523                 /*Send status to host*/
1524                 usbd_ep_start_write(busid, USB_CONTROL_IN_EP0, NULL, 0);
1525                 break;
1526 
1527             default:
1528                 break;
1529         }
1530     }
1531 }
1532 #endif
1533 
1534 int usbd_initialize(uint8_t busid, uintptr_t reg_base, void (*event_handler)(uint8_t busid, uint8_t event))
1535 {
1536     int ret;
1537     struct usbd_bus *bus;
1538 
1539     if (busid >= CONFIG_USBDEV_MAX_BUS) {
1540         USB_LOG_ERR("bus overflow\r\n");
1541         while (1) {
1542         }
1543     }
1544 
1545     bus = &g_usbdev_bus[busid];
1546     bus->reg_base = reg_base;
1547 
1548 #ifdef CONFIG_USBDEV_EP0_THREAD
1549     g_usbd_core[busid].usbd_ep0_mq = usb_osal_mq_create(1);
1550     if (g_usbd_core[busid].usbd_ep0_mq == NULL) {
1551         USB_LOG_ERR("No memory to alloc for g_usbd_core[busid].usbd_ep0_mq\r\n");
1552         while (1) {
1553         }
1554     }
1555     g_usbd_core[busid].usbd_ep0_thread = usb_osal_thread_create("usbd_ep0", CONFIG_USBDEV_EP0_STACKSIZE, CONFIG_USBDEV_EP0_PRIO, usbdev_ep0_thread, (void *)(uint32_t)busid);
1556     if (g_usbd_core[busid].usbd_ep0_thread == NULL) {
1557         USB_LOG_ERR("No memory to alloc for g_usbd_core[busid].usbd_ep0_thread\r\n");
1558         while (1) {
1559         }
1560     }
1561 #endif
1562 
1563     g_usbd_core[busid].event_handler = event_handler;
1564     ret = usb_dc_init(busid);
1565     usbd_class_event_notify_handler(busid, USBD_EVENT_INIT, NULL);
1566     g_usbd_core[busid].event_handler(busid, USBD_EVENT_INIT);
1567     return ret;
1568 }
1569 
1570 int usbd_deinitialize(uint8_t busid)
1571 {
1572     if (busid >= CONFIG_USBDEV_MAX_BUS) {
1573         USB_LOG_ERR("bus overflow\r\n");
1574         while (1) {
1575         }
1576     }
1577 
1578     g_usbd_core[busid].event_handler(busid, USBD_EVENT_DEINIT);
1579     usbd_class_event_notify_handler(busid, USBD_EVENT_DEINIT, NULL);
1580     usb_dc_deinit(busid);
1581     g_usbd_core[busid].intf_offset = 0;
1582 #ifdef CONFIG_USBDEV_EP0_THREAD
1583     if (g_usbd_core[busid].usbd_ep0_mq) {
1584         usb_osal_mq_delete(g_usbd_core[busid].usbd_ep0_mq);
1585     }
1586     if (g_usbd_core[busid].usbd_ep0_thread) {
1587         usb_osal_thread_delete(g_usbd_core[busid].usbd_ep0_thread);
1588     }
1589 #endif
1590 
1591     return 0;
1592 }
1593