summaryrefslogtreecommitdiff
path: root/core/usbd_core.c
blob: 612e79519229f2c58274273feae3cb9c1d3add9e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
/*
 * Copyright (C) 2006 Bertrik Sikken ([email protected])
 * Copyright (c) 2016 Intel Corporation
 * Copyright (c) 2022, sakumisu
 *
 * SPDX-License-Identifier: Apache-2.0
 */
#include "usbd_core.h"

/* general descriptor field offsets */
#define DESC_bLength         0 /** Length offset */
#define DESC_bDescriptorType 1 /** Descriptor type offset */

/* config descriptor field offsets */
#define CONF_DESC_wTotalLength        2 /** Total length offset */
#define CONF_DESC_bConfigurationValue 5 /** Configuration value offset */
#define CONF_DESC_bmAttributes        7 /** configuration characteristics */

/* interface descriptor field offsets */
#define INTF_DESC_bInterfaceNumber  2 /** Interface number offset */
#define INTF_DESC_bAlternateSetting 3 /** Alternate setting offset */

#define USB_EP_OUT_NUM 8
#define USB_EP_IN_NUM  8

USB_NOCACHE_RAM_SECTION struct usbd_core_cfg_priv {
    /** Setup packet */
    USB_MEM_ALIGNX struct usb_setup_packet setup;
    /** Pointer to data buffer */
    uint8_t *ep0_data_buf;
    /** Remaining bytes in buffer */
    uint32_t ep0_data_buf_residue;
    /** Total length of control transfer */
    uint32_t ep0_data_buf_len;
    /** Zero length packet flag of control transfer */
    bool zlp_flag;
    /** Pointer to registered descriptors */
    const uint8_t *descriptors;
    /* Buffer used for storing standard, class and vendor request data */
    USB_MEM_ALIGNX uint8_t req_data[CONFIG_USBDEV_REQUEST_BUFFER_LEN];

    usbd_endpoint_callback in_ep_cb[USB_EP_IN_NUM];
    usbd_endpoint_callback out_ep_cb[USB_EP_OUT_NUM];

    /** Variable to check whether the usb has been configured */
    bool configured;
    /** Currently selected configuration */
    uint8_t configuration;
#ifdef CONFIG_USBDEV_TEST_MODE
    bool test_mode;
#endif
    uint8_t intf_offset;
} usbd_core_cfg;

usb_slist_t usbd_intf_head = USB_SLIST_OBJECT_INIT(usbd_intf_head);

static struct usb_msosv1_descriptor *msosv1_desc;
static struct usb_msosv2_descriptor *msosv2_desc;
static struct usb_bos_descriptor *bos_desc;

static void usbd_class_event_notify_handler(uint8_t event, void *arg);

static void usbd_print_setup(struct usb_setup_packet *setup)
{
    USB_LOG_INFO("Setup: "
                 "bmRequestType 0x%02x, bRequest 0x%02x, wValue 0x%04x, wIndex 0x%04x, wLength 0x%04x\r\n",
                 setup->bmRequestType,
                 setup->bRequest,
                 setup->wValue,
                 setup->wIndex,
                 setup->wLength);
}

static bool is_device_configured(void)
{
    return (usbd_core_cfg.configuration != 0);
}

/**
 * @brief configure and enable endpoint
 *
 * This function sets endpoint configuration according to one specified in USB
 * endpoint descriptor and then enables it for data transfers.
 *
 * @param [in]  ep_desc Endpoint descriptor byte array
 *
 * @return true if successfully configured and enabled
 */
static bool usbd_set_endpoint(const struct usb_endpoint_descriptor *ep_desc)
{
    struct usbd_endpoint_cfg ep_cfg;

    ep_cfg.ep_addr = ep_desc->bEndpointAddress;
    ep_cfg.ep_mps = ep_desc->wMaxPacketSize & USB_MAXPACKETSIZE_MASK;
    ep_cfg.ep_type = ep_desc->bmAttributes & USB_ENDPOINT_TYPE_MASK;

    USB_LOG_INFO("Open endpoint:0x%x type:%u mps:%u\r\n",
                 ep_cfg.ep_addr, ep_cfg.ep_type, ep_cfg.ep_mps);

    return usbd_ep_open(&ep_cfg) == 0 ? true : false;
}
/**
 * @brief Disable endpoint for transferring data
 *
 * This function cancels transfers that are associated with endpoint and
 * disabled endpoint itself.
 *
 * @param [in]  ep_desc Endpoint descriptor byte array
 *
 * @return true if successfully deconfigured and disabled
 */
static bool usbd_reset_endpoint(const struct usb_endpoint_descriptor *ep_desc)
{
    struct usbd_endpoint_cfg ep_cfg;

    ep_cfg.ep_addr = ep_desc->bEndpointAddress;
    ep_cfg.ep_mps = ep_desc->wMaxPacketSize & USB_MAXPACKETSIZE_MASK;
    ep_cfg.ep_type = ep_desc->bmAttributes & USB_ENDPOINT_TYPE_MASK;

    USB_LOG_INFO("Close endpoint:0x%x type:%u\r\n",
                 ep_cfg.ep_addr, ep_cfg.ep_type);

    return usbd_ep_close(ep_cfg.ep_addr) == 0 ? true : false;
}

/**
 * @brief get specified USB descriptor
 *
 * This function parses the list of installed USB descriptors and attempts
 * to find the specified USB descriptor.
 *
 * @param [in]  type_index Type and index of the descriptor
 * @param [out] data       Descriptor data
 * @param [out] len        Descriptor length
 *
 * @return true if the descriptor was found, false otherwise
 */
static bool usbd_get_descriptor(uint16_t type_index, uint8_t **data, uint32_t *len)
{
    uint8_t type = 0U;
    uint8_t index = 0U;
    uint8_t *p = NULL;
    uint32_t cur_index = 0U;
    bool found = false;

    type = HI_BYTE(type_index);
    index = LO_BYTE(type_index);

    if ((type == USB_DESCRIPTOR_TYPE_STRING) && (index == USB_OSDESC_STRING_DESC_INDEX)) {
        USB_LOG_INFO("read MS OS 2.0 descriptor string\r\n");

        if (!msosv1_desc) {
            return false;
        }

        *data = (uint8_t *)msosv1_desc->string;
        *len = msosv1_desc->string_len;

        return true;
    } else if (type == USB_DESCRIPTOR_TYPE_BINARY_OBJECT_STORE) {
        USB_LOG_INFO("read BOS descriptor string\r\n");

        if (!bos_desc) {
            return false;
        }

        *data = bos_desc->string;
        *len = bos_desc->string_len;
        return true;
    }
    /*
     * Invalid types of descriptors,
     * see USB Spec. Revision 2.0, 9.4.3 Get Descriptor
     */
    else if ((type == USB_DESCRIPTOR_TYPE_INTERFACE) || (type == USB_DESCRIPTOR_TYPE_ENDPOINT) ||
#ifndef CONFIG_USB_HS
             (type > USB_DESCRIPTOR_TYPE_ENDPOINT)) {
#else
             (type > USB_DESCRIPTOR_TYPE_OTHER_SPEED)) {
#endif
        return false;
    }

    p = (uint8_t *)usbd_core_cfg.descriptors;

    cur_index = 0U;

    while (p[DESC_bLength] != 0U) {
        if (p[DESC_bDescriptorType] == type) {
            if (cur_index == index) {
                found = true;
                break;
            }

            cur_index++;
        }

        /* skip to next descriptor */
        p += p[DESC_bLength];
    }

    if (found) {
        /* found descriptor, save descriptor premiere address */
        *data = p;

        if ((type == USB_DESCRIPTOR_TYPE_CONFIGURATION) || ((type == USB_DESCRIPTOR_TYPE_OTHER_SPEED))) {
            /* configuration or other speed descriptor is an
             * exception, length is at offset 2 and 3
             */
            *len = (p[CONF_DESC_wTotalLength]) |
                   (p[CONF_DESC_wTotalLength + 1] << 8);
        } else {
            /* normally length is at offset 0 */
            *len = p[DESC_bLength];
        }
    } else {
        /* nothing found */
        USB_LOG_ERR("descriptor <type:%x,index:%x> not found!\r\n", type, index);
    }

    return found;
}

/**
 * @brief set USB configuration
 *
 * This function configures the device according to the specified configuration
 * index and alternate setting by parsing the installed USB descriptor list.
 * A configuration index of 0 unconfigures the device.
 *
 * @param [in] config_index Configuration index
 * @param [in] alt_setting  Alternate setting number
 *
 * @return true if successfully configured false if error or unconfigured
 */
static bool usbd_set_configuration(uint8_t config_index, uint8_t alt_setting)
{
    uint8_t *p = (uint8_t *)usbd_core_cfg.descriptors;
    uint8_t cur_alt_setting = 0xFF;
    uint8_t cur_config = 0xFF;
    bool found = false;

    /* configure endpoints for this configuration/altsetting */
    while (p[DESC_bLength] != 0U) {
        switch (p[DESC_bDescriptorType]) {
            case USB_DESCRIPTOR_TYPE_CONFIGURATION:
                /* remember current configuration index */
                cur_config = p[CONF_DESC_bConfigurationValue];

                if (cur_config == config_index) {
                    found = true;
                }

                break;

            case USB_DESCRIPTOR_TYPE_INTERFACE:
                /* remember current alternate setting */
                cur_alt_setting =
                    p[INTF_DESC_bAlternateSetting];
                break;

            case USB_DESCRIPTOR_TYPE_ENDPOINT:
                if ((cur_config != config_index) ||
                    (cur_alt_setting != alt_setting)) {
                    break;
                }

                found = usbd_set_endpoint((struct usb_endpoint_descriptor *)p);
                break;

            default:
                break;
        }

        /* skip to next descriptor */
        p += p[DESC_bLength];
    }

    return found;
}

/**
 * @brief set USB interface
 *
 * @param [in] iface Interface index
 * @param [in] alt_setting  Alternate setting number
 *
 * @return true if successfully configured false if error or unconfigured
 */
static bool usbd_set_interface(uint8_t iface, uint8_t alt_setting)
{
    const uint8_t *p = usbd_core_cfg.descriptors;
    const uint8_t *if_desc = NULL;
    struct usb_endpoint_descriptor *ep_desc;
    uint8_t cur_alt_setting = 0xFF;
    uint8_t cur_iface = 0xFF;
    bool ret = false;

    USB_LOG_DBG("iface %u alt_setting %u\r\n", iface, alt_setting);

    while (p[DESC_bLength] != 0U) {
        switch (p[DESC_bDescriptorType]) {
            case USB_DESCRIPTOR_TYPE_INTERFACE:
                /* remember current alternate setting */
                cur_alt_setting = p[INTF_DESC_bAlternateSetting];
                cur_iface = p[INTF_DESC_bInterfaceNumber];

                if (cur_iface == iface &&
                    cur_alt_setting == alt_setting) {
                    if_desc = (void *)p;
                }

                USB_LOG_DBG("Current iface %u alt setting %u",
                            cur_iface, cur_alt_setting);
                break;

            case USB_DESCRIPTOR_TYPE_ENDPOINT:
                if (cur_iface == iface) {
                    ep_desc = (struct usb_endpoint_descriptor *)p;

                    if (cur_alt_setting != alt_setting) {
                        ret = usbd_reset_endpoint(ep_desc);
                    } else {
                        ret = usbd_set_endpoint(ep_desc);
                    }
                }

                break;

            default:
                break;
        }

        /* skip to next descriptor */
        p += p[DESC_bLength];
    }

    usbd_class_event_notify_handler(USBD_EVENT_SET_INTERFACE, (void *)if_desc);

    return ret;
}

/**
 * @brief handle a standard device request
 *
 * @param [in]     setup    The setup packet
 * @param [in,out] data     Data buffer
 * @param [in,out] len      Pointer to data length
 *
 * @return true if the request was handled successfully
 */
static bool usbd_std_device_req_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
{
    uint16_t value = setup->wValue;
    bool ret = true;

    switch (setup->bRequest) {
        case USB_REQUEST_GET_STATUS:
            /* bit 0: self-powered */
            /* bit 1: remote wakeup */
            (*data)[0] = 0x00;
            (*data)[1] = 0x00;
            *len = 2;
            break;

        case USB_REQUEST_CLEAR_FEATURE:
        case USB_REQUEST_SET_FEATURE:
            if (value == USB_FEATURE_REMOTE_WAKEUP) {
            } else if (value == USB_FEATURE_TEST_MODE) {
#ifdef CONFIG_USBDEV_TEST_MODE
                usbd_core_cfg.test_mode = true;
                usbd_execute_test_mode(setup);
#endif
            }
            *len = 0;
            break;

        case USB_REQUEST_SET_ADDRESS:
            usbd_set_address(value);
            *len = 0;
            break;

        case USB_REQUEST_GET_DESCRIPTOR:
            ret = usbd_get_descriptor(value, data, len);
            break;

        case USB_REQUEST_SET_DESCRIPTOR:
            ret = false;
            break;

        case USB_REQUEST_GET_CONFIGURATION:
            *data = (uint8_t *)&usbd_core_cfg.configuration;
            *len = 1;
            break;

        case USB_REQUEST_SET_CONFIGURATION:
            value &= 0xFF;

            if (!usbd_set_configuration(value, 0)) {
                ret = false;
            } else {
                usbd_core_cfg.configuration = value;
                usbd_core_cfg.configured = true;
                usbd_class_event_notify_handler(USBD_EVENT_CONFIGURED, NULL);
                usbd_configure_done_callback();
            }
            *len = 0;
            break;

        case USB_REQUEST_GET_INTERFACE:
        case USB_REQUEST_SET_INTERFACE:
            ret = false;
            break;

        default:
            ret = false;
            break;
    }

    return ret;
}

/**
 * @brief handle a standard interface request
 *
 * @param [in]     setup    The setup packet
 * @param [in,out] data     Data buffer
 * @param [in,out] len      Pointer to data length
 *
 * @return true if the request was handled successfully
 */
static bool usbd_std_interface_req_handler(struct usb_setup_packet *setup,
                                           uint8_t **data, uint32_t *len)
{
    uint8_t type = HI_BYTE(setup->wValue);
    uint8_t intf_num = LO_BYTE(setup->wIndex);
    bool ret = true;

    /* Only when device is configured, then interface requests can be valid. */
    if (!is_device_configured()) {
        return false;
    }

    switch (setup->bRequest) {
        case USB_REQUEST_GET_STATUS:
            (*data)[0] = 0x00;
            (*data)[1] = 0x00;
            *len = 2;
            break;

        case USB_REQUEST_GET_DESCRIPTOR:
            if (type == 0x22) { /* HID_DESCRIPTOR_TYPE_HID_REPORT */
                USB_LOG_INFO("read hid report descriptor\r\n");
                usb_slist_t *i;

                usb_slist_for_each(i, &usbd_intf_head)
                {
                    struct usbd_interface *intf = usb_slist_entry(i, struct usbd_interface, list);

                    if (intf->intf_num == intf_num) {
                        *data = (uint8_t *)intf->hid_report_descriptor;
                        *len = intf->hid_report_descriptor_len;
                        return true;
                    }
                }
            }
            ret = false;
            break;
        case USB_REQUEST_CLEAR_FEATURE:
        case USB_REQUEST_SET_FEATURE:
            ret = false;
            break;
        case USB_REQUEST_GET_INTERFACE:
            (*data)[0] = 0;
            *len = 1;
            break;

        case USB_REQUEST_SET_INTERFACE:
            usbd_set_interface(setup->wIndex, setup->wValue);
            *len = 0;
            break;

        default:
            ret = false;
            break;
    }

    return ret;
}

/**
 * @brief handle a standard endpoint request
 *
 * @param [in]     setup    The setup packet
 * @param [in,out] data     Data buffer
 * @param [in,out] len      Pointer to data length
 *
 * @return true if the request was handled successfully
 */
static bool usbd_std_endpoint_req_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
{
    uint8_t ep = (uint8_t)setup->wIndex;
    bool ret = true;

    /* Only when device is configured, then endpoint requests can be valid. */
    if (!is_device_configured()) {
        return false;
    }

    switch (setup->bRequest) {
        case USB_REQUEST_GET_STATUS:
            (*data)[0] = 0x00;
            (*data)[1] = 0x00;
            *len = 2;
            break;
        case USB_REQUEST_CLEAR_FEATURE:
            if (setup->wValue == USB_FEATURE_ENDPOINT_HALT) {
                USB_LOG_ERR("ep:%02x clear halt\r\n", ep);

                usbd_ep_clear_stall(ep);
                break;
            } else {
                ret = false;
            }
            *len = 0;
            break;
        case USB_REQUEST_SET_FEATURE:
            if (setup->wValue == USB_FEATURE_ENDPOINT_HALT) {
                USB_LOG_ERR("ep:%02x set halt\r\n", ep);

                usbd_ep_set_stall(ep);
            } else {
                ret = false;
            }
            *len = 0;
            break;

        case USB_REQUEST_SYNCH_FRAME:
            ret = false;
            break;
        default:
            ret = false;
            break;
    }

    return ret;
}

/**
 * @brief handle standard requests (list in chapter 9)
 *
 * @param [in]     setup    The setup packet
 * @param [in,out] data     Data buffer
 * @param [in,out] len      Pointer to data length
 *
 * @return true if the request was handled successfully
 */
static int usbd_standard_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
{
    int rc = 0;

    switch (setup->bmRequestType & USB_REQUEST_RECIPIENT_MASK) {
        case USB_REQUEST_RECIPIENT_DEVICE:
            if (usbd_std_device_req_handler(setup, data, len) == false) {
                rc = -1;
            }

            break;

        case USB_REQUEST_RECIPIENT_INTERFACE:
            if (usbd_std_interface_req_handler(setup, data, len) == false) {
                rc = -1;
            }

            break;

        case USB_REQUEST_RECIPIENT_ENDPOINT:
            if (usbd_std_endpoint_req_handler(setup, data, len) == false) {
                rc = -1;
            }

            break;

        default:
            rc = -1;
            break;
    }

    return rc;
}

/**
 * @brief handler for class requests
 *
 * If a custom request handler was installed, this handler is called first.
 *
 * @param [in]     setup    The setup packet
 * @param [in,out] data     Data buffer
 * @param [in,out] len      Pointer to data length
 *
 * @return true if the request was handled successfully
 */
static int usbd_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
{
    usb_slist_t *i;
    if ((setup->bmRequestType & USB_REQUEST_RECIPIENT_MASK) == USB_REQUEST_RECIPIENT_INTERFACE) {
        usb_slist_for_each(i, &usbd_intf_head)
        {
            struct usbd_interface *intf = usb_slist_entry(i, struct usbd_interface, list);

            if (intf->class_interface_handler && (intf->intf_num == (setup->wIndex & 0xFF))) {
                return intf->class_interface_handler(setup, data, len);
            }
        }
    } else if ((setup->bmRequestType & USB_REQUEST_RECIPIENT_MASK) == USB_REQUEST_RECIPIENT_ENDPOINT) {
        usb_slist_for_each(i, &usbd_intf_head)
        {
            struct usbd_interface *intf = usb_slist_entry(i, struct usbd_interface, list);

            if (intf->class_endpoint_handler && (intf->intf_num == ((setup->wIndex >> 8) & 0xFF))) {
                return intf->class_endpoint_handler(setup, data, len);
            }
        }
    }
    return -1;
}

/**
 * @brief handler for vendor requests
 *
 * If a custom request handler was installed, this handler is called first.
 *
 * @param [in]     setup    The setup packet
 * @param [in,out] data     Data buffer
 * @param [in,out] len      Pointer to data length
 *
 * @return true if the request was handled successfully
 */
static int usbd_vendor_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
{
    if (msosv1_desc) {
        if (setup->bRequest == msosv1_desc->vendor_code) {
            switch (setup->wIndex) {
                case 0x04:
                    USB_LOG_INFO("get Compat ID\r\n");
                    *data = (uint8_t *)msosv1_desc->compat_id;
                    *len = msosv1_desc->compat_id_len;

                    return 0;
                case 0x05:
                    USB_LOG_INFO("get Compat id properties\r\n");
                    *data = (uint8_t *)msosv1_desc->comp_id_property;
                    *len = msosv1_desc->comp_id_property_len;

                    return 0;
                default:
                    USB_LOG_ERR("unknown vendor code\r\n");
                    return -1;
            }
        }
    } else if (msosv2_desc) {
        if (setup->bRequest == msosv2_desc->vendor_code) {
            switch (setup->wIndex) {
                case WINUSB_REQUEST_GET_DESCRIPTOR_SET:
                    USB_LOG_INFO("GET MS OS 2.0 Descriptor\r\n");
                    *data = (uint8_t *)msosv2_desc->compat_id;
                    *len = msosv2_desc->compat_id_len;
                    return 0;
                default:
                    USB_LOG_ERR("unknown vendor code\r\n");
                    return -1;
            }
        }
    }

    usb_slist_t *i;

    usb_slist_for_each(i, &usbd_intf_head)
    {
        struct usbd_interface *intf = usb_slist_entry(i, struct usbd_interface, list);

        if (intf->vendor_handler && !intf->vendor_handler(setup, data, len)) {
            return 0;
        }
    }

    return -1;
}

/**
 * @brief handle setup request( standard/class/vendor/other)
 *
 * @param [in]     setup The setup packet
 * @param [in,out] data  Data buffer
 * @param [in,out] len   Pointer to data length
 *
 * @return true if the request was handles successfully
 */
static bool usbd_setup_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
{
    switch (setup->bmRequestType & USB_REQUEST_TYPE_MASK) {
        case USB_REQUEST_STANDARD:
            if (usbd_standard_request_handler(setup, data, len) < 0) {
                USB_LOG_ERR("standard request error\r\n");
                usbd_print_setup(setup);
                return false;
            }
            break;
        case USB_REQUEST_CLASS:
            if (usbd_class_request_handler(setup, data, len) < 0) {
                USB_LOG_ERR("class request error\r\n");
                usbd_print_setup(setup);
                return false;
            }
            break;
        case USB_REQUEST_VENDOR:
            if (usbd_vendor_request_handler(setup, data, len) < 0) {
                USB_LOG_ERR("vendor request error\r\n");
                usbd_print_setup(setup);
                return false;
            }
            break;

        default:
            return false;
    }

    return true;
}

static void usbd_class_event_notify_handler(uint8_t event, void *arg)
{
    usb_slist_t *i;
    usb_slist_for_each(i, &usbd_intf_head)
    {
        struct usbd_interface *intf = usb_slist_entry(i, struct usbd_interface, list);

        if (intf->notify_handler) {
            intf->notify_handler(event, arg);
        }
    }
}

void usbd_event_connect_handler(void)
{
    usbd_class_event_notify_handler(USBD_EVENT_CONNECTED, NULL);
}

void usbd_event_disconnect_handler(void)
{
    usbd_class_event_notify_handler(USBD_EVENT_DISCONNECTED, NULL);
}

void usbd_event_resume_handler(void)
{
    usbd_class_event_notify_handler(USBD_EVENT_RESUME, NULL);
}

void usbd_event_suspend_handler(void)
{
    usbd_class_event_notify_handler(USBD_EVENT_SUSPEND, NULL);
}

void usbd_event_reset_handler(void)
{
    usbd_set_address(0);
    usbd_core_cfg.configured = 0;
    usbd_core_cfg.configuration = 0;
#ifdef CONFIG_USBDEV_TEST_MODE
    usbd_core_cfg.test_mode = false;
#endif
    struct usbd_endpoint_cfg ep0_cfg;

    ep0_cfg.ep_mps = USB_CTRL_EP_MPS;
    ep0_cfg.ep_type = USB_ENDPOINT_TYPE_CONTROL;
    ep0_cfg.ep_addr = USB_CONTROL_IN_EP0;
    usbd_ep_open(&ep0_cfg);

    ep0_cfg.ep_addr = USB_CONTROL_OUT_EP0;
    usbd_ep_open(&ep0_cfg);

    usbd_class_event_notify_handler(USBD_EVENT_RESET, NULL);
}

void usbd_event_ep0_setup_complete_handler(uint8_t *psetup)
{
    struct usb_setup_packet *setup = &usbd_core_cfg.setup;

    memcpy(setup, psetup, 8);
#ifdef CONFIG_USBDEV_SETUP_LOG_PRINT
    usbd_print_setup(setup);
#endif
    if (setup->wLength > CONFIG_USBDEV_REQUEST_BUFFER_LEN) {
        if ((setup->bmRequestType & USB_REQUEST_DIR_MASK) == USB_REQUEST_DIR_OUT) {
            USB_LOG_ERR("Request buffer too small\r\n");
            usbd_ep_set_stall(USB_CONTROL_IN_EP0);
            return;
        }
    }

    usbd_core_cfg.ep0_data_buf = usbd_core_cfg.req_data;
    usbd_core_cfg.ep0_data_buf_residue = setup->wLength;
    usbd_core_cfg.ep0_data_buf_len = setup->wLength;
    usbd_core_cfg.zlp_flag = false;

    /* handle class request when all the data is received */
    if (setup->wLength && ((setup->bmRequestType & USB_REQUEST_DIR_MASK) == USB_REQUEST_DIR_OUT)) {
        USB_LOG_DBG("Start reading %d bytes from ep0\r\n", setup->wLength);
        usbd_ep_start_read(USB_CONTROL_OUT_EP0, usbd_core_cfg.ep0_data_buf, setup->wLength);
        return;
    }

    /* Ask installed handler to process request */
    if (!usbd_setup_request_handler(setup, &usbd_core_cfg.ep0_data_buf, &usbd_core_cfg.ep0_data_buf_len)) {
        usbd_ep_set_stall(USB_CONTROL_IN_EP0);
        return;
    }
#ifdef CONFIG_USBDEV_TEST_MODE
    /* send status in test mode, so do not execute downward, just return */
    if (usbd_core_cfg.test_mode) {
        usbd_core_cfg.test_mode = false;
        return;
    }
#endif
    /* Send smallest of requested and offered length */
    usbd_core_cfg.ep0_data_buf_residue = MIN(usbd_core_cfg.ep0_data_buf_len,
                                             setup->wLength);

    /* check if the data buf addr matches align size,if not, copy into align buf */
#ifndef CONFIG_USBDEV_ALIGN_CHECK_DISABLE
    if (((unsigned long)usbd_core_cfg.ep0_data_buf) & (CONFIG_USB_ALIGN_SIZE - 1)) {
        if (usbd_core_cfg.ep0_data_buf_residue > CONFIG_USBDEV_REQUEST_BUFFER_LEN) {
            USB_LOG_ERR("Request buffer too small\r\n");
            return;
        }
        /* copy data buf from misalignx addr to alignx addr */
        memcpy(usbd_core_cfg.req_data, usbd_core_cfg.ep0_data_buf, usbd_core_cfg.ep0_data_buf_residue);
        usbd_core_cfg.ep0_data_buf = usbd_core_cfg.req_data;
    }
#endif
    /* Send data or status to host */
    usbd_ep_start_write(USB_CONTROL_IN_EP0, usbd_core_cfg.ep0_data_buf, usbd_core_cfg.ep0_data_buf_residue);
    /*
    * Set ZLP flag when host asks for a bigger length and the data size is multiplier of USB_CTRL_EP_MPS,
    * to indicate the transfer done after zlp sent.
    */
    if ((setup->wLength > usbd_core_cfg.ep0_data_buf_len) && (!(usbd_core_cfg.ep0_data_buf_len % USB_CTRL_EP_MPS))) {
        usbd_core_cfg.zlp_flag = true;
        USB_LOG_DBG("EP0 Set zlp\r\n");
    }
}

void usbd_event_ep_in_complete_handler(uint8_t ep, uint32_t nbytes)
{
    if (ep == USB_CONTROL_IN_EP0) {
        struct usb_setup_packet *setup = &usbd_core_cfg.setup;

        usbd_core_cfg.ep0_data_buf += nbytes;
        usbd_core_cfg.ep0_data_buf_residue -= nbytes;

        USB_LOG_DBG("EP0 send %d bytes, %d remained\r\n", nbytes, usbd_core_cfg.ep0_data_buf_residue);

        if (usbd_core_cfg.ep0_data_buf_residue != 0) {
            /* Start sending the remain data */
            usbd_ep_start_write(USB_CONTROL_IN_EP0, usbd_core_cfg.ep0_data_buf, usbd_core_cfg.ep0_data_buf_residue);
        } else {
            if (usbd_core_cfg.zlp_flag == true) {
                usbd_core_cfg.zlp_flag = false;
                /* Send zlp to host */
                USB_LOG_DBG("EP0 Send zlp\r\n");
                usbd_ep_start_write(USB_CONTROL_IN_EP0, NULL, 0);
            } else {
                /* Satisfying three conditions will jump here.
                * 1. send status completely
                * 2. send zlp completely
                * 3. send last data completely.
                */
                if (setup->wLength && ((setup->bmRequestType & USB_REQUEST_DIR_MASK) == USB_REQUEST_DIR_IN)) {
                    /* if all data has sent completely, start reading out status */
                    usbd_ep_start_read(USB_CONTROL_OUT_EP0, NULL, 0);
                }
            }
        }
    } else {
        if (usbd_core_cfg.in_ep_cb[ep & 0x7f]) {
            usbd_core_cfg.in_ep_cb[ep & 0x7f](ep, nbytes);
        }
    }
}

void usbd_event_ep_out_complete_handler(uint8_t ep, uint32_t nbytes)
{
    if (ep == USB_CONTROL_OUT_EP0) {
        struct usb_setup_packet *setup = &usbd_core_cfg.setup;

        if (nbytes > 0) {
            usbd_core_cfg.ep0_data_buf += nbytes;
            usbd_core_cfg.ep0_data_buf_residue -= nbytes;

            USB_LOG_DBG("EP0 recv %d bytes, %d remained\r\n", nbytes, usbd_core_cfg.ep0_data_buf_residue);

            if (usbd_core_cfg.ep0_data_buf_residue == 0) {
                /* Received all, send data to handler */
                usbd_core_cfg.ep0_data_buf = usbd_core_cfg.req_data;
                if (!usbd_setup_request_handler(setup, &usbd_core_cfg.ep0_data_buf, &usbd_core_cfg.ep0_data_buf_len)) {
                    usbd_ep_set_stall(USB_CONTROL_IN_EP0);
                    return;
                }

                /*Send status to host*/
                usbd_ep_start_write(USB_CONTROL_IN_EP0, NULL, 0);
            } else {
                /* Start reading the remain data */
                usbd_ep_start_read(USB_CONTROL_OUT_EP0, usbd_core_cfg.ep0_data_buf, usbd_core_cfg.ep0_data_buf_residue);
            }
        } else {
            /* Read out status completely, do nothing */
            USB_LOG_DBG("EP0 recv out status\r\n");
        }
    } else {
        if (usbd_core_cfg.out_ep_cb[ep & 0x7f]) {
            usbd_core_cfg.out_ep_cb[ep & 0x7f](ep, nbytes);
        }
    }
}

void usbd_desc_register(const uint8_t *desc)
{
    usbd_core_cfg.descriptors = desc;
    usbd_core_cfg.intf_offset = 0;
}

/* Register MS OS Descriptors version 1 */
void usbd_msosv1_desc_register(struct usb_msosv1_descriptor *desc)
{
    msosv1_desc = desc;
}

/* Register MS OS Descriptors version 2 */
void usbd_msosv2_desc_register(struct usb_msosv2_descriptor *desc)
{
    msosv2_desc = desc;
}

void usbd_bos_desc_register(struct usb_bos_descriptor *desc)
{
    bos_desc = desc;
}

void usbd_add_interface(struct usbd_interface *intf)
{
    intf->intf_num = usbd_core_cfg.intf_offset;
    usb_slist_add_tail(&usbd_intf_head, &intf->list);
    usbd_core_cfg.intf_offset++;
}

void usbd_add_endpoint(struct usbd_endpoint *ep)
{
    if (ep->ep_addr & 0x80) {
        usbd_core_cfg.in_ep_cb[ep->ep_addr & 0x7f] = ep->ep_cb;
    } else {
        usbd_core_cfg.out_ep_cb[ep->ep_addr & 0x7f] = ep->ep_cb;
    }
}

bool usb_device_is_configured(void)
{
    return usbd_core_cfg.configured;
}

int usbd_initialize(void)
{
    return usb_dc_init();
}

int usbd_deinitialize(void)
{
    usbd_core_cfg.intf_offset = 0;
    usb_slist_init(&usbd_intf_head);
    usb_dc_deinit();
    return 0;
}