forked from hathach/tinyusb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusbh.c
More file actions
2042 lines (1740 loc) · 69.6 KB
/
usbh.c
File metadata and controls
2042 lines (1740 loc) · 69.6 KB
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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if CFG_TUH_ENABLED
#include "hcd.h"
#include "tusb.h"
#include "usbh_pvt.h"
#include "hub.h"
//--------------------------------------------------------------------+
// Configuration
//--------------------------------------------------------------------+
#ifndef CFG_TUH_TASK_QUEUE_SZ
#define CFG_TUH_TASK_QUEUE_SZ 16
#endif
#ifndef CFG_TUH_INTERFACE_MAX
#define CFG_TUH_INTERFACE_MAX 8
#endif
enum {
USBH_CONTROL_RETRY_MAX = 3,
};
//--------------------------------------------------------------------+
// Weak stubs: invoked if no strong implementation is available
//--------------------------------------------------------------------+
TU_ATTR_WEAK bool hcd_deinit(uint8_t rhport) {
(void) rhport; return false;
}
TU_ATTR_WEAK bool hcd_configure(uint8_t rhport, uint32_t cfg_id, const void* cfg_param) {
(void) rhport; (void) cfg_id; (void) cfg_param;
return false;
}
TU_ATTR_WEAK void tuh_enum_descriptor_device_cb(uint8_t daddr, const tusb_desc_device_t *desc_device) {
(void) daddr; (void) desc_device;
}
TU_ATTR_WEAK bool tuh_enum_descriptor_configuration_cb(uint8_t daddr, uint8_t cfg_index, const tusb_desc_configuration_t *desc_config) {
(void) daddr; (void) cfg_index; (void) desc_config;
return true;
}
TU_ATTR_WEAK void tuh_event_hook_cb(uint8_t rhport, uint32_t eventid, bool in_isr) {
(void) rhport; (void) eventid; (void) in_isr;
}
TU_ATTR_WEAK bool hcd_dcache_clean(const void* addr, uint32_t data_size) {
(void) addr; (void) data_size;
return false;
}
TU_ATTR_WEAK bool hcd_dcache_invalidate(const void* addr, uint32_t data_size) {
(void) addr; (void) data_size;
return false;
}
TU_ATTR_WEAK bool hcd_dcache_clean_invalidate(const void* addr, uint32_t data_size) {
(void) addr; (void) data_size;
return false;
}
TU_ATTR_WEAK usbh_class_driver_t const* usbh_app_driver_get_cb(uint8_t* driver_count) {
*driver_count = 0;
return NULL;
}
TU_ATTR_WEAK void tuh_mount_cb(uint8_t daddr) {
(void) daddr;
}
TU_ATTR_WEAK void tuh_umount_cb(uint8_t daddr) {
(void) daddr;
}
//--------------------------------------------------------------------+
// Data Structure
//--------------------------------------------------------------------+
// Device Descriptor (without bLength and bDescriptorType header)
typedef struct TU_ATTR_PACKED {
uint16_t bcdUSB;
uint8_t bDeviceClass;
uint8_t bDeviceSubClass;
uint8_t bDeviceProtocol;
uint8_t bMaxPacketSize0;
uint16_t idVendor;
uint16_t idProduct;
uint16_t bcdDevice;
uint8_t iManufacturer;
uint8_t iProduct;
uint8_t iSerialNumber;
uint8_t bNumConfigurations;
} desc_device_noheader_t;
TU_VERIFY_STATIC( sizeof(desc_device_noheader_t) == 16u, "size is not correct");
typedef struct {
tuh_bus_info_t bus_info;
desc_device_noheader_t desc_device;
// Device State
struct TU_ATTR_PACKED {
volatile uint8_t connected : 1; // After 1st transfer
volatile uint8_t addressed : 1; // After SET_ADDR
volatile uint8_t configured : 1; // After SET_CONFIG and all drivers are configured
volatile uint8_t suspended : 1; // Bus suspended
// volatile uint8_t removing : 1; // Physically disconnected, waiting to be processed by usbh
};
// Endpoint & Interface
uint8_t itf2drv[CFG_TUH_INTERFACE_MAX]; // map interface number to driver (0xff is invalid)
uint8_t ep2drv[CFG_TUH_ENDPOINT_MAX][2]; // map endpoint to driver ( 0xff is invalid ), can use only 4-bit each
tu_edpt_state_t ep_status[CFG_TUH_ENDPOINT_MAX][2];
#if CFG_TUH_API_EDPT_XFER
// TODO array can be CFG_TUH_ENDPOINT_MAX-1
struct {
tuh_xfer_cb_t complete_cb;
uintptr_t user_data;
}ep_callback[CFG_TUH_ENDPOINT_MAX][2];
#endif
} usbh_device_t;
// sum of end device + hub
#define TOTAL_DEVICES (CFG_TUH_DEVICE_MAX + CFG_TUH_HUB)
// all devices excluding zero-address
// hub address start from CFG_TUH_DEVICE_MAX+1
// TODO: hub can has its own simpler struct to save memory
static usbh_device_t _usbh_devices[TOTAL_DEVICES];
// Mutex for claiming endpoint
#if OSAL_MUTEX_REQUIRED
static osal_mutex_def_t _usbh_mutexdef;
static osal_mutex_t _usbh_mutex;
#else
#define _usbh_mutex NULL
#endif
// Spinlock for interrupt handler
static OSAL_SPINLOCK_DEF(_usbh_spin, usbh_int_set);
// Event queue: usbh_int_set() is used as mutex in OS NONE config
OSAL_QUEUE_DEF(usbh_int_set, _usbh_qdef, CFG_TUH_TASK_QUEUE_SZ, hcd_event_t);
static osal_queue_t _usbh_q;
#if CFG_TUH_HUB
// Deferred attachment queue, only needed when using hub
OSAL_QUEUE_DEF(usbh_int_set, _usbh_daqdef, CFG_TUH_HUB, hcd_event_t);
static osal_queue_t _usbh_daq;
#endif
// Control transfers: since most controllers do not support multiple control transfers
// on multiple devices concurrently and control transfers are not used much except for
// enumeration, we will only execute control transfers one at a time.
typedef struct {
uint8_t* buffer;
tuh_xfer_cb_t complete_cb;
uintptr_t user_data;
volatile uint8_t stage;
uint8_t daddr;
volatile uint16_t actual_len;
uint8_t failed_count;
} usbh_ctrl_xfer_info_t;
typedef struct {
tusb_defer_func_t func;
uintptr_t arg;
uint32_t at_ms;
} usbh_call_after_t;
typedef struct {
uint8_t controller_id; // controller ID
uint8_t enumerating_daddr; // device address of the device being enumerated
uint8_t attach_debouncing_bm; // bitmask for roothub port attach debouncing
tuh_bus_info_t dev0_bus; // bus info for dev0 in enumeration
usbh_ctrl_xfer_info_t ctrl_xfer_info; // control transfer
usbh_call_after_t call_after;
} usbh_data_t;
static usbh_data_t _usbh_data = {
.controller_id = TUSB_INDEX_INVALID_8,
};
typedef struct {
TUH_EPBUF_TYPE_DEF(tusb_control_request_t, request);
TUH_EPBUF_DEF(ctrl, CFG_TUH_ENUMERATION_BUFSIZE);
} usbh_epbuf_t;
CFG_TUH_MEM_SECTION static usbh_epbuf_t _usbh_epbuf;
//--------------------------------------------------------------------+
// Class Driver
//--------------------------------------------------------------------+
#if CFG_TUSB_DEBUG >= CFG_TUH_LOG_LEVEL
#define DRIVER_NAME(_name) _name
#else
#define DRIVER_NAME(_name) NULL
#endif
static usbh_class_driver_t const usbh_class_drivers[] = {
#if CFG_TUH_CDC
{
.name = DRIVER_NAME("CDC"),
.init = cdch_init,
.deinit = cdch_deinit,
.open = cdch_open,
.set_config = cdch_set_config,
.xfer_cb = cdch_xfer_cb,
.close = cdch_close
},
#endif
#if CFG_TUH_MSC
{
.name = DRIVER_NAME("MSC"),
.init = msch_init,
.deinit = msch_deinit,
.open = msch_open,
.set_config = msch_set_config,
.xfer_cb = msch_xfer_cb,
.close = msch_close
},
#endif
#if CFG_TUH_HID
{
.name = DRIVER_NAME("HID"),
.init = hidh_init,
.deinit = hidh_deinit,
.open = hidh_open,
.set_config = hidh_set_config,
.xfer_cb = hidh_xfer_cb,
.close = hidh_close
},
#endif
#if CFG_TUH_MIDI
{
.name = DRIVER_NAME("MIDI"),
.init = midih_init,
.deinit = midih_deinit,
.open = midih_open,
.set_config = midih_set_config,
.xfer_cb = midih_xfer_cb,
.close = midih_close
},
#endif
#if CFG_TUH_HUB
{
.name = DRIVER_NAME("HUB"),
.init = hub_init,
.deinit = hub_deinit,
.open = hub_open,
.set_config = hub_set_config,
.xfer_cb = hub_xfer_cb,
.close = hub_close
},
#endif
#if CFG_TUH_VENDOR
{
.name = DRIVER_NAME("VENDOR"),
.init = cush_init,
.deinit = cush_deinit,
.open = cush_open,
.set_config = cush_set_config,
.xfer_cb = cush_isr,
.close = cush_close
}
#endif
};
enum { BUILTIN_DRIVER_COUNT = TU_ARRAY_SIZE(usbh_class_drivers) };
// Additional class drivers implemented by application
static usbh_class_driver_t const * _app_driver = NULL;
static uint8_t _app_driver_count = 0;
#define TOTAL_DRIVER_COUNT (_app_driver_count + BUILTIN_DRIVER_COUNT)
// virtually joins built-in and application drivers together.
// Application is positioned first to allow overwriting built-in ones.
TU_ATTR_ALWAYS_INLINE static inline usbh_class_driver_t const *get_driver(uint8_t drv_id) {
usbh_class_driver_t const *driver = NULL;
if (drv_id < _app_driver_count) {
driver = &_app_driver[drv_id];
} else {
drv_id -= _app_driver_count;
if (drv_id < BUILTIN_DRIVER_COUNT) {
driver = &usbh_class_drivers[drv_id];
}
}
return driver;
}
//--------------------------------------------------------------------+
// Function Inline and Prototypes
//--------------------------------------------------------------------+
static void enum_new_device(hcd_event_t* event);
static void enum_delay_async(uintptr_t state);
static void process_remove_event(hcd_event_t *event);
static void remove_device_tree(uint8_t rhport, uint8_t hub_addr, uint8_t hub_port);
static bool usbh_edpt_control_open(uint8_t dev_addr, uint8_t max_packet_size);
static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes);
TU_ATTR_ALWAYS_INLINE static inline usbh_device_t* get_device(uint8_t dev_addr) {
TU_VERIFY(dev_addr > 0 && dev_addr <= TOTAL_DEVICES, NULL);
return &_usbh_devices[dev_addr-1];
}
TU_ATTR_ALWAYS_INLINE static inline bool is_hub_addr(uint8_t daddr) {
return (CFG_TUH_HUB > 0) && (daddr > CFG_TUH_DEVICE_MAX); //-V560
}
TU_ATTR_ALWAYS_INLINE static inline bool queue_event(hcd_event_t const * event, bool in_isr) {
TU_ASSERT(osal_queue_send(_usbh_q, event, in_isr));
tuh_event_hook_cb(event->rhport, event->event_id, in_isr);
return true;
}
TU_ATTR_ALWAYS_INLINE static inline void _control_set_xfer_stage(uint8_t stage) {
if (_usbh_data.ctrl_xfer_info.stage != stage) {
(void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER);
_usbh_data.ctrl_xfer_info.stage = stage;
(void) osal_mutex_unlock(_usbh_mutex);
}
}
TU_ATTR_ALWAYS_INLINE static inline bool usbh_setup_send(uint8_t daddr, const uint8_t setup_packet[8]) {
const uint8_t rhport = usbh_get_rhport(daddr);
const bool ret = hcd_setup_send(rhport, daddr, setup_packet);
if (!ret) {
_control_set_xfer_stage(CONTROL_STAGE_IDLE);
}
return ret;
}
bool usbh_defer_func_ms_async(uint32_t ms, tusb_defer_func_t func, uintptr_t param) {
TU_ASSERT(_usbh_data.call_after.func == NULL);
TU_LOG_USBH("USBH schedule function after %u ms\r\n", (unsigned int)ms);
_usbh_data.call_after.func = func;
_usbh_data.call_after.arg = param;
_usbh_data.call_after.at_ms = tusb_time_millis_api() + ms;
return true;
}
TU_ATTR_ALWAYS_INLINE static inline void usbh_device_close(uint8_t rhport, uint8_t daddr) {
hcd_device_close(rhport, daddr);
// abort any ongoing control transfer
if (daddr == _usbh_data.ctrl_xfer_info.daddr) {
_control_set_xfer_stage(CONTROL_STAGE_IDLE);
}
// invalidate if enumerating
if (daddr == _usbh_data.enumerating_daddr) {
_usbh_data.enumerating_daddr = TUSB_INDEX_INVALID_8;
// clear enum delay function of the device being removed
if (_usbh_data.call_after.func == enum_delay_async) {
_usbh_data.call_after.func = NULL;
}
}
}
//--------------------------------------------------------------------+
// Device API
//--------------------------------------------------------------------+
bool tuh_mounted(uint8_t dev_addr) {
usbh_device_t *dev = get_device(dev_addr);
TU_VERIFY(dev);
return dev->configured;
}
bool tuh_connected(uint8_t daddr) {
if (daddr == 0) {
return _usbh_data.enumerating_daddr == 0;
} else {
const usbh_device_t* dev = get_device(daddr);
TU_VERIFY(dev != NULL);
return dev->connected;
}
}
bool tuh_vid_pid_get(uint8_t dev_addr, uint16_t *vid, uint16_t *pid) {
*vid = *pid = 0;
usbh_device_t const *dev = get_device(dev_addr);
TU_VERIFY(dev && dev->addressed && dev->desc_device.idVendor != 0);
*vid = dev->desc_device.idVendor;
*pid = dev->desc_device.idProduct;
return true;
}
bool tuh_descriptor_get_device_local(uint8_t daddr, tusb_desc_device_t* desc_device) {
usbh_device_t *dev = get_device(daddr);
TU_VERIFY(dev && desc_device);
desc_device->bLength = sizeof(tusb_desc_device_t);
desc_device->bDescriptorType = TUSB_DESC_DEVICE;
memcpy((uint8_t*) desc_device + offsetof(tusb_desc_device_t, bcdUSB), &dev->desc_device, sizeof(desc_device_noheader_t));
return true;
}
tusb_speed_t tuh_speed_get(uint8_t daddr) {
tuh_bus_info_t bus_info;
tuh_bus_info_get(daddr, &bus_info);
return (tusb_speed_t)bus_info.speed;
}
bool tuh_rhport_is_active(uint8_t rhport) {
return _usbh_data.controller_id == rhport;
}
bool tuh_rhport_reset_bus(uint8_t rhport, bool active) {
TU_VERIFY(tuh_rhport_is_active(rhport));
if (active) {
hcd_port_reset(rhport);
} else {
hcd_port_reset_end(rhport);
}
return true;
}
//--------------------------------------------------------------------+
// PUBLIC API (Parameter Verification is required)
//--------------------------------------------------------------------+
bool tuh_configure(uint8_t rhport, uint32_t cfg_id, const void *cfg_param) {
return hcd_configure(rhport, cfg_id, cfg_param);
}
static void clear_device(usbh_device_t* dev) {
tu_memclr(dev, sizeof(usbh_device_t));
(void) memset(dev->itf2drv, TUSB_INDEX_INVALID_8, sizeof(dev->itf2drv)); // invalid mapping
(void) memset(dev->ep2drv , TUSB_INDEX_INVALID_8, sizeof(dev->ep2drv )); // invalid mapping
}
bool tuh_inited(void) {
return _usbh_data.controller_id != TUSB_INDEX_INVALID_8;
}
bool tuh_rhport_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) {
if (tuh_rhport_is_active(rhport)) {
return true; // skip if already initialized
}
#if CFG_TUSB_DEBUG >= CFG_TUH_LOG_LEVEL
char const* speed_str = 0;
switch (rh_init->speed) {
case TUSB_SPEED_HIGH:
speed_str = "High";
break;
case TUSB_SPEED_FULL:
speed_str = "Full";
break;
case TUSB_SPEED_LOW:
speed_str = "Low";
break;
case TUSB_SPEED_AUTO:
speed_str = "Auto";
break;
default:
break;
}
TU_LOG_USBH("USBH init on controller %u, speed = %s\r\n", rhport, speed_str);
#endif
// Init host stack if not already
if (!tuh_inited()) {
TU_LOG_INT_USBH(sizeof(usbh_data_t));
TU_LOG_INT_USBH(sizeof(usbh_device_t));
TU_LOG_INT_USBH(sizeof(hcd_event_t));
TU_LOG_INT_USBH(sizeof(tuh_xfer_t));
TU_LOG_INT_USBH(sizeof(tu_fifo_t));
TU_LOG_INT_USBH(sizeof(tu_edpt_stream_t));
osal_spin_init(&_usbh_spin);
// Event queue
_usbh_q = osal_queue_create(&_usbh_qdef);
TU_ASSERT(_usbh_q != NULL);
#if CFG_TUH_HUB
// Deferred attachment queue
_usbh_daq = osal_queue_create(&_usbh_daqdef);
TU_ASSERT(_usbh_daq != NULL);
#endif
#if OSAL_MUTEX_REQUIRED
// Init mutex
_usbh_mutex = osal_mutex_create(&_usbh_mutexdef);
TU_ASSERT(_usbh_mutex);
#endif
// Get application driver if available
_app_driver = usbh_app_driver_get_cb(&_app_driver_count);
// Device
tu_memclr(_usbh_devices, sizeof(_usbh_devices));
tu_memclr(&_usbh_data, sizeof(_usbh_data));
_usbh_data.controller_id = TUSB_INDEX_INVALID_8;
_usbh_data.enumerating_daddr = TUSB_INDEX_INVALID_8;
for (uint8_t i = 0; i < TOTAL_DEVICES; i++) {
clear_device(&_usbh_devices[i]);
}
// Class drivers
for (uint8_t drv_id = 0; drv_id < TOTAL_DRIVER_COUNT; drv_id++) {
usbh_class_driver_t const* driver = get_driver(drv_id);
if (driver != NULL && driver->init) {
TU_LOG_USBH("%s init\r\n", driver->name);
driver->init();
}
}
}
// Init host controller
_usbh_data.controller_id = rhport;
TU_ASSERT(hcd_init(rhport, rh_init));
hcd_int_enable(rhport);
return true;
}
bool tuh_deinit(uint8_t rhport) {
if (!tuh_rhport_is_active(rhport)) {
return true;
}
// deinit host controller
hcd_int_disable(rhport);
TU_ASSERT(hcd_deinit(rhport));
_usbh_data.controller_id = TUSB_INDEX_INVALID_8;
// remove all devices on this rhport (hub_addr = 0, hub_port = 0)
remove_device_tree(rhport, 0, 0);
// deinit host stack if no controller is active
if (!tuh_inited()) {
// Class drivers
for (uint8_t drv_id = 0; drv_id < TOTAL_DRIVER_COUNT; drv_id++) {
usbh_class_driver_t const* driver = get_driver(drv_id);
if (driver && driver->deinit) {
TU_LOG_USBH("%s deinit\r\n", driver->name);
driver->deinit();
}
}
osal_queue_delete(_usbh_q);
_usbh_q = NULL;
#if CFG_TUH_HUB
osal_queue_delete(_usbh_daq);
_usbh_daq = NULL;
#endif
#if OSAL_MUTEX_REQUIRED
// TODO make sure there is no task waiting on this mutex
osal_mutex_delete(_usbh_mutex);
_usbh_mutex = NULL;
#endif
}
return true;
}
bool tuh_task_event_ready(void) {
if (!tuh_inited()) {
return false; // Skip if tusb stack is not initialized
}
if (!osal_queue_empty(_usbh_q)) {
return true;
}
#if CFG_TUH_HUB
if (!osal_queue_empty(_usbh_daq)) {
return true;
}
#endif
return false;
}
/* USB Host Driver task
* This top level thread manages all host controller event and delegates events to class-specific drivers.
* This should be called periodically within the mainloop or rtos thread.
*
@code
int main(void) {
application_init();
tusb_init(0, TUSB_ROLE_HOST);
while(1) { // the mainloop
application_code();
tuh_task(); // tinyusb host task
}
}
@endcode
*/
void tuh_task_ext(uint32_t timeout_ms, bool in_isr) {
// Skip if stack is not initialized
if (!tuh_inited()) {
return;
}
(void) in_isr; // not implemented yet
// Loop until there are no more events in the queue or CFG_TUH_TASK_EVENTS_PER_RUN is reached
for (unsigned epr = 0;; epr++) {
#if CFG_TUH_TASK_EVENTS_PER_RUN > 0
if (epr >= CFG_TUH_TASK_EVENTS_PER_RUN) {
TU_LOG_USBH("USBH event limit (" TU_XSTRING(CFG_TUH_TASK_EVENTS_PER_RUN) ") reached\r\n");
break;
}
#endif
// Process call_after_ms function if ms is reached
tusb_defer_func_t after_cb = _usbh_data.call_after.func;
if (after_cb) {
int32_t remain_ms = (int32_t)(_usbh_data.call_after.at_ms - tusb_time_millis_api());
if (remain_ms <= 0) {
// delay expired, run callback now
TU_LOG_USBH("USBH invoke scheduled function\r\n");
_usbh_data.call_after.func = NULL;
after_cb(_usbh_data.call_after.arg);
}
// above after_cb() can re-schedule another function, we need to re-check and reduce timeout of
// the main event timeout to make sure we aren't blocking more than call_after remaining ms.
if (_usbh_data.call_after.func != NULL) {
remain_ms = (int32_t) (_usbh_data.call_after.at_ms - tusb_time_millis_api());
if (remain_ms <= 0) {
timeout_ms = 0; // expired already
} else if (timeout_ms > (uint32_t)remain_ms) {
timeout_ms = (uint32_t)remain_ms;
}
}
}
hcd_event_t event;
#if CFG_TUH_HUB
// Get deferred device attachments if none is enumerating
bool has_deferred_attach = false;
if (_usbh_data.enumerating_daddr == TUSB_INDEX_INVALID_8) {
// zero wait to avoid blocking the main event queue
has_deferred_attach = osal_queue_receive(_usbh_daq, &event, 0);
}
if (!has_deferred_attach) // skip event queue to process deferred attach
#endif
{
if (!osal_queue_receive(_usbh_q, &event, timeout_ms)) {
return;
}
}
switch (event.event_id) {
case HCD_EVENT_DEVICE_ATTACH:
// Should we miss the hub detach event due to high traffic, Or due to physical debouncing, some devices can
// cause multiple attaches (actually reset) without a detached event.
// Force remove currently mounted with the same bus info (rhport, hub addr, hub port) if exists
process_remove_event(&event);
// due to the shared control buffer, we must fully complete enumerating one device first.
if (_usbh_data.enumerating_daddr == TUSB_INDEX_INVALID_8) {
// New device attached and we are ready
TU_LOG_USBH("[%u:] USBH Device Attach\r\n", event.rhport);
_usbh_data.enumerating_daddr = 0; // enumerate new device with address 0
enum_new_device(&event);
}
#if CFG_TUH_HUB
else {
TU_LOG_USBH("[%u:] USBH Defer Attach until current enumeration complete\r\n", event.rhport);
TU_ASSERT(osal_queue_send(_usbh_daq, &event, in_isr), );
}
#endif
break;
case HCD_EVENT_DEVICE_REMOVE:
TU_LOG_USBH("[%u:%u:%u] USBH Device Removed\r\n", event.rhport, event.connection.hub_addr, event.connection.hub_port);
process_remove_event(&event);
break;
case HCD_EVENT_XFER_COMPLETE: {
uint8_t const ep_addr = event.xfer_complete.ep_addr;
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const ep_dir = (uint8_t) tu_edpt_dir(ep_addr);
TU_LOG_USBH("[:%u] on EP %02X with %u bytes: %s\r\n",
event.dev_addr, ep_addr, (unsigned int) event.xfer_complete.len, tu_str_xfer_result[event.xfer_complete.result]);
if (event.dev_addr == 0) {
// device 0 only has control endpoint
TU_ASSERT(epnum == 0,);
usbh_control_xfer_cb(event.dev_addr, ep_addr, (xfer_result_t) event.xfer_complete.result, event.xfer_complete.len);
} else {
usbh_device_t* dev = get_device(event.dev_addr);
TU_VERIFY(dev && dev->connected,);
dev->ep_status[epnum][ep_dir].busy = 0;
dev->ep_status[epnum][ep_dir].claimed = 0;
if (0 == epnum) {
usbh_control_xfer_cb(event.dev_addr, ep_addr, (xfer_result_t) event.xfer_complete.result, event.xfer_complete.len);
} else {
// Prefer application callback over built-in one if available. This occurs when tuh_edpt_xfer() is used
// with enabled driver e.g HID endpoint
#if CFG_TUH_API_EDPT_XFER
tuh_xfer_cb_t const complete_cb = dev->ep_callback[epnum][ep_dir].complete_cb;
if (complete_cb != NULL) {
// re-construct xfer info
tuh_xfer_t xfer = {
.daddr = event.dev_addr,
.ep_addr = ep_addr,
.result = (xfer_result_t)event.xfer_complete.result,
.actual_len = event.xfer_complete.len,
.buflen = 0, // not available
.buffer = NULL, // not available
.complete_cb = complete_cb,
.user_data = dev->ep_callback[epnum][ep_dir].user_data
};
complete_cb(&xfer);
}else
#endif
{
uint8_t drv_id = dev->ep2drv[epnum][ep_dir];
usbh_class_driver_t const* driver = get_driver(drv_id);
if (driver != NULL) {
TU_LOG_USBH(" %s xfer callback\r\n", driver->name);
driver->xfer_cb(event.dev_addr, ep_addr, (xfer_result_t) event.xfer_complete.result,
event.xfer_complete.len);
} else {
// no driver/callback responsible for this transfer
TU_ASSERT(false,);
}
}
}
}
break;
}
case USBH_EVENT_FUNC_CALL:
if (event.func_call.func != NULL) {
event.func_call.func(event.func_call.param);
}
break;
default:
// unknown event
break;
}
// allow to exit tuh_task() if there is no event in the next run
timeout_ms = 0;
}
}
//--------------------------------------------------------------------+
// Control transfer
//--------------------------------------------------------------------+
static void _control_blocking_complete_cb(tuh_xfer_t* xfer) {
// update result
*((xfer_result_t*) xfer->user_data) = xfer->result;
}
// TODO timeout_ms is not supported yet
bool tuh_control_xfer (tuh_xfer_t* xfer) {
TU_VERIFY(xfer->ep_addr == 0 && xfer->setup); // EP0 with setup packet
const uint8_t daddr = xfer->daddr;
TU_VERIFY(tuh_connected(daddr));
usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info;
TU_VERIFY(ctrl_info->stage == CONTROL_STAGE_IDLE); // pre-check to help reducing mutex lock
(void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER);
bool const is_idle = (ctrl_info->stage == CONTROL_STAGE_IDLE);
if (is_idle) {
ctrl_info->stage = CONTROL_STAGE_SETUP;
ctrl_info->daddr = daddr;
ctrl_info->actual_len = 0;
ctrl_info->failed_count = 0;
ctrl_info->buffer = xfer->buffer;
ctrl_info->complete_cb = xfer->complete_cb;
ctrl_info->user_data = xfer->user_data;
_usbh_epbuf.request = (*xfer->setup);
}
(void) osal_mutex_unlock(_usbh_mutex);
TU_VERIFY(is_idle);
TU_LOG_USBH("[%u:%u] %s: ", usbh_get_rhport(daddr), daddr,
(xfer->setup->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD && xfer->setup->bRequest <= TUSB_REQ_SYNCH_FRAME) ?
tu_str_std_request[xfer->setup->bRequest] : "Class Request");
TU_LOG_BUF_USBH(xfer->setup, 8);
if (xfer->complete_cb != NULL) {
TU_ASSERT(usbh_setup_send(daddr, (uint8_t const *) &_usbh_epbuf.request));
}else {
// blocking if complete callback is not provided
// change callback to internal blocking, and result as user argument
volatile xfer_result_t result = XFER_RESULT_INVALID;
// use user_data to point to xfer_result_t
ctrl_info->user_data = (uintptr_t) &result;
ctrl_info->complete_cb = _control_blocking_complete_cb;
TU_ASSERT(usbh_setup_send(daddr, (uint8_t const *) &_usbh_epbuf.request));
while (result == XFER_RESULT_INVALID) {
// Note: this can be called within an callback ie. part of tuh_task()
// therefore even with RTOS tuh_task_ext() still need to be invoked
tuh_task_ext(0, false);
// TODO probably some timeout to prevent hanged
}
// update transfer result, user_data is expected to point to xfer_result_t
if (xfer->user_data != 0) {
*((xfer_result_t*) xfer->user_data) = result;
}
xfer->result = result;
xfer->actual_len = ctrl_info->actual_len;
}
return true;
}
static void _control_xfer_complete(uint8_t daddr, xfer_result_t result) {
TU_LOG_USBH("\r\n");
usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info;
// duplicate xfer since user can execute control transfer within callback
tusb_control_request_t const request = _usbh_epbuf.request;
tuh_xfer_t xfer_temp = {
.daddr = daddr,
.ep_addr = 0,
.result = result,
.setup = &request,
.actual_len = (uint32_t) ctrl_info->actual_len,
.buffer = ctrl_info->buffer,
.complete_cb = ctrl_info->complete_cb,
.user_data = ctrl_info->user_data
};
_control_set_xfer_stage(CONTROL_STAGE_IDLE);
if (xfer_temp.complete_cb != NULL) {
xfer_temp.complete_cb(&xfer_temp);
}
}
static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) {
(void) ep_addr;
const uint8_t rhport = usbh_get_rhport(daddr);
tusb_control_request_t const * request = &_usbh_epbuf.request;
usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info;
switch (result) {
case XFER_RESULT_STALLED:
TU_LOG_USBH("[%u:%u] Control STALLED, xferred_bytes = %" PRIu32 "\r\n", rhport, daddr, xferred_bytes);
TU_LOG_BUF_USBH(request, 8);
_control_xfer_complete(daddr, result);
break;
case XFER_RESULT_FAILED:
if (tuh_connected(daddr) && ctrl_info->failed_count < USBH_CONTROL_RETRY_MAX) {
TU_LOG_USBH("[%u:%u] Control FAILED %u/%u, retrying\r\n", rhport, daddr, ctrl_info->failed_count+1, USBH_CONTROL_RETRY_MAX);
(void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER);
ctrl_info->stage = CONTROL_STAGE_SETUP;
ctrl_info->failed_count++;
ctrl_info->actual_len = 0; // reset actual_len
(void) osal_mutex_unlock(_usbh_mutex);
TU_ASSERT(usbh_setup_send(daddr, (uint8_t const *) request));
} else {
TU_LOG_USBH("[%u:%u] Control FAILED, xferred_bytes = %" PRIu32 "\r\n", rhport, daddr, xferred_bytes);
TU_LOG_BUF_USBH(request, 8);
_control_xfer_complete(daddr, result);
}
break;
case XFER_RESULT_SUCCESS:
switch(ctrl_info->stage) {
case CONTROL_STAGE_SETUP:
if (request->wLength > 0) {
// DATA stage: initial data toggle is always 1
_control_set_xfer_stage(CONTROL_STAGE_DATA);
const uint8_t ep_data = tu_edpt_addr(0, request->bmRequestType_bit.direction);
TU_ASSERT(hcd_edpt_xfer(rhport, daddr, ep_data, ctrl_info->buffer, request->wLength));
return true;
}
TU_ATTR_FALLTHROUGH;
case CONTROL_STAGE_DATA: {
if (request->wLength > 0) {
TU_LOG_USBH("[%u:%u] Control data:\r\n", rhport, daddr);
TU_LOG_MEM_USBH(ctrl_info->buffer, xferred_bytes, 2);
}
ctrl_info->actual_len = (uint16_t) xferred_bytes;
// ACK stage: toggle is always 1
_control_set_xfer_stage(CONTROL_STAGE_ACK);
const uint8_t ep_status = tu_edpt_addr(0, 1 - request->bmRequestType_bit.direction);
TU_ASSERT(hcd_edpt_xfer(rhport, daddr, ep_status, NULL, 0));
break;
}
case CONTROL_STAGE_ACK: {
// Abort all pending transfers if SET_CONFIGURATION request
// NOTE: should we force closing all non-control endpoints in the future?
if (request->bRequest == TUSB_REQ_SET_CONFIGURATION && request->bmRequestType == 0x00) {
for(uint8_t epnum=1; epnum<CFG_TUH_ENDPOINT_MAX; epnum++) {
for(uint8_t dir=0; dir<2; dir++) {
tuh_edpt_abort_xfer(daddr, tu_edpt_addr(epnum, dir));
}
}
}
_control_xfer_complete(daddr, result);
break;
}
default: return false; // unsupported stage
}
break;
default: return false; // unsupported result
}
return true;
}
//--------------------------------------------------------------------+
//
//--------------------------------------------------------------------+
bool tuh_edpt_xfer(tuh_xfer_t* xfer) {
uint8_t const daddr = xfer->daddr;
uint8_t const ep_addr = xfer->ep_addr;
TU_VERIFY(daddr && ep_addr);
TU_VERIFY(usbh_edpt_claim(daddr, ep_addr));
if (!usbh_edpt_xfer_with_callback(daddr, ep_addr, xfer->buffer, (uint16_t) xfer->buflen,
xfer->complete_cb, xfer->user_data)) {
usbh_edpt_release(daddr, ep_addr);
return false;
}
return true;
}
bool tuh_edpt_abort_xfer(uint8_t daddr, uint8_t ep_addr) {
TU_LOG_USBH("[%u] Aborted transfer on EP %02X\r\n", daddr, ep_addr);
const uint8_t epnum = tu_edpt_number(ep_addr);
const uint8_t dir = tu_edpt_dir(ep_addr);
if (epnum == 0) {
// Also include dev0 for aborting enumerating
const uint8_t rhport = usbh_get_rhport(daddr);