-
Notifications
You must be signed in to change notification settings - Fork 87
/
ehci.cpp
1468 lines (1384 loc) · 47.9 KB
/
ehci.cpp
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
/* USB EHCI Host for Teensy 3.6
* Copyright 2017 Paul Stoffregen ([email protected])
*
* 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.
*/
#include <Arduino.h>
#include "USBHost_t36.h" // Read this header first for key info
// All USB EHCI controller hardware access is done from this file's code.
// Hardware services are made available to the rest of this library by
// three structures:
//
// Pipe_t: Every USB endpoint is accessed by a pipe. new_Pipe()
// sets up the EHCI to support the pipe/endpoint, and delete_Pipe()
// removes this configuration.
//
// Transfer_t: These are used for all communication. Data transfers
// are placed into work queues, to be executed by the EHCI in
// the future. Transfer_t only manages data. The actual data
// is stored in a separate buffer (usually from a device driver)
// which is referenced from Transfer_t. All data transfer is queued,
// never done with blocking functions that wait. When transfers
// complete, a driver-supplied callback function is called to notify
// the driver.
//
// USBDriverTimer: Some drivers require timers. These allow drivers
// to share the hardware timer, with each USBDriverTimer object
// able to schedule a callback function a configurable number of
// microseconds in the future.
//
// In addition to these 3 services, the EHCI interrupt also responds
// to changes on the main port, creating and deleting the root device.
// See enumeration.cpp for all device-level code.
// Size of the periodic list, in milliseconds. This determines the
// slowest rate we can poll interrupt endpoints. Each entry uses
// 12 bytes (4 for a pointer, 8 for bandwidth management).
// Supported values: 8, 16, 32, 64, 128, 256, 512, 1024
#if defined(USBHS_PERIODIC_LIST_SIZE)
#define PERIODIC_LIST_SIZE (USBHS_PERIODIC_LIST_SIZE)
#else
#define PERIODIC_LIST_SIZE 32
#endif
// The EHCI periodic schedule, used for interrupt pipes/endpoints
static uint32_t periodictable[PERIODIC_LIST_SIZE] __attribute__ ((aligned(4096), used));
static uint8_t uframe_bandwidth[PERIODIC_LIST_SIZE*8];
// State of the 1 and only physical USB host port on Teensy 3.6
static uint8_t port_state;
#define PORT_STATE_DISCONNECTED 0
#define PORT_STATE_DEBOUNCE 1
#define PORT_STATE_RESET 2
#define PORT_STATE_RECOVERY 3
#define PORT_STATE_ACTIVE 4
// The device currently connected, or NULL when no device
static Device_t *rootdev=NULL;
// List of all queued transfers in the asychronous schedule (control & bulk).
// When the EHCI completes these transfers, this list is how we locate them
// in memory.
static Transfer_t *async_followup_first=NULL;
static Transfer_t *async_followup_last=NULL;
// List of all queued transfers in the asychronous schedule (interrupt endpoints)
// When the EHCI completes these transfers, this list is how we locate them
// in memory.
static Transfer_t *periodic_followup_first=NULL;
static Transfer_t *periodic_followup_last=NULL;
// List of all pending timers. This double linked list is stored in
// chronological order. Each timer is stored with the number of
// microseconds which need to elapsed from the prior timer on this
// list, to allow efficient servicing from the timer interrupt.
static USBDriverTimer *active_timers=NULL;
static void init_qTD(volatile Transfer_t *t, void *buf, uint32_t len,
uint32_t pid, uint32_t data01, bool irq);
static void add_to_async_followup_list(Transfer_t *first, Transfer_t *last);
static void remove_from_async_followup_list(Transfer_t *transfer);
static void add_to_periodic_followup_list(Transfer_t *first, Transfer_t *last);
static void remove_from_periodic_followup_list(Transfer_t *transfer);
#define print USBHost::print_
#define println USBHost::println_
void USBHost::begin()
{
#if defined(__MK66FX1M0__)
// Teensy 3.6 has USB host power controlled by PTE6
PORTE_PCR6 = PORT_PCR_MUX(1);
GPIOE_PDDR |= (1<<6);
GPIOE_PSOR = (1<<6); // turn on USB host power
delay(10);
println("sizeof Device = ", sizeof(Device_t));
println("sizeof Pipe = ", sizeof(Pipe_t));
println("sizeof Transfer = ", sizeof(Transfer_t));
if ((sizeof(Pipe_t) & 0x1F) || (sizeof(Transfer_t) & 0x1F)) {
println("ERROR: Pipe_t & Transfer_t must be multiples of 32 bytes!");
while (1) ; // die here
}
// configure the MPU to allow USBHS DMA to access memory
MPU_RGDAAC0 |= 0x30000000;
//println("MPU_RGDAAC0 = ", MPU_RGDAAC0, HEX);
// turn on clocks
MCG_C1 |= MCG_C1_IRCLKEN; // enable MCGIRCLK 32kHz
OSC0_CR |= OSC_ERCLKEN;
SIM_SOPT2 |= SIM_SOPT2_USBREGEN; // turn on USB regulator
SIM_SOPT2 &= ~SIM_SOPT2_USBSLSRC; // use IRC for slow clock
println("power up USBHS PHY");
SIM_USBPHYCTL |= SIM_USBPHYCTL_USBDISILIM; // disable USB current limit
//SIM_USBPHYCTL = SIM_USBPHYCTL_USBDISILIM | SIM_USBPHYCTL_USB3VOUTTRG(6); // pg 237
SIM_SCGC3 |= SIM_SCGC3_USBHSDCD | SIM_SCGC3_USBHSPHY | SIM_SCGC3_USBHS;
USBHSDCD_CLOCK = 33 << 2;
//print("init USBHS PHY & PLL");
// init process: page 1681-1682
USBPHY_CTRL_CLR = (USBPHY_CTRL_SFTRST | USBPHY_CTRL_CLKGATE); // // CTRL pg 1698
USBPHY_CTRL_SET = USBPHY_CTRL_ENUTMILEVEL2 | USBPHY_CTRL_ENUTMILEVEL3;
//USBPHY_CTRL_SET = USBPHY_CTRL_FSDLL_RST_EN; // TODO: what does this do??
USBPHY_TRIM_OVERRIDE_EN_SET = 1;
USBPHY_PLL_SIC = USBPHY_PLL_SIC_PLL_POWER | USBPHY_PLL_SIC_PLL_ENABLE |
USBPHY_PLL_SIC_PLL_DIV_SEL(1) | USBPHY_PLL_SIC_PLL_EN_USB_CLKS;
// wait for the PLL to lock
int pll_count=0;
while ((USBPHY_PLL_SIC & USBPHY_PLL_SIC_PLL_LOCK) == 0) {
pll_count++;
}
//println("PLL locked, waited ", pll_count);
// turn on power to PHY
USBPHY_PWD = 0;
// sanity check, connect 470K pullup & 100K pulldown and watch D+ voltage change
//USBPHY_ANACTRL_CLR = (1<<10); // turn off both 15K pulldowns... works! :)
// sanity check, output clocks on pin 9 for testing
//SIM_SOPT2 = SIM_SOPT2 & (~SIM_SOPT2_CLKOUTSEL(7)) | SIM_SOPT2_CLKOUTSEL(3); // LPO 1kHz
//SIM_SOPT2 = SIM_SOPT2 & (~SIM_SOPT2_CLKOUTSEL(7)) | SIM_SOPT2_CLKOUTSEL(2); // Flash
//SIM_SOPT2 = SIM_SOPT2 & (~SIM_SOPT2_CLKOUTSEL(7)) | SIM_SOPT2_CLKOUTSEL(6); // XTAL
//SIM_SOPT2 = SIM_SOPT2 & (~SIM_SOPT2_CLKOUTSEL(7)) | SIM_SOPT2_CLKOUTSEL(7); // IRC 48MHz
//SIM_SOPT2 = SIM_SOPT2 & (~SIM_SOPT2_CLKOUTSEL(7)) | SIM_SOPT2_CLKOUTSEL(4); // MCGIRCLK
//CORE_PIN9_CONFIG = PORT_PCR_MUX(5); // CLKOUT on PTC3 Alt5 (Arduino pin 9)
#elif defined(__IMXRT1052__) || defined(__IMXRT1062__)
// Teensy 4.0 PLL & USB PHY powerup
while (1) {
uint32_t n = CCM_ANALOG_PLL_USB2;
if (n & CCM_ANALOG_PLL_USB2_DIV_SELECT) {
CCM_ANALOG_PLL_USB2_CLR = 0xC000; // get out of 528 MHz mode
CCM_ANALOG_PLL_USB2_SET = CCM_ANALOG_PLL_USB2_BYPASS;
CCM_ANALOG_PLL_USB2_CLR = CCM_ANALOG_PLL_USB2_POWER |
CCM_ANALOG_PLL_USB2_DIV_SELECT |
CCM_ANALOG_PLL_USB2_ENABLE |
CCM_ANALOG_PLL_USB2_EN_USB_CLKS;
continue;
}
if (!(n & CCM_ANALOG_PLL_USB2_ENABLE)) {
CCM_ANALOG_PLL_USB2_SET = CCM_ANALOG_PLL_USB2_ENABLE; // enable
continue;
}
if (!(n & CCM_ANALOG_PLL_USB2_POWER)) {
CCM_ANALOG_PLL_USB2_SET = CCM_ANALOG_PLL_USB2_POWER; // power up
continue;
}
if (!(n & CCM_ANALOG_PLL_USB2_LOCK)) {
continue; // wait for lock
}
if (n & CCM_ANALOG_PLL_USB2_BYPASS) {
CCM_ANALOG_PLL_USB2_CLR = CCM_ANALOG_PLL_USB2_BYPASS; // turn off bypass
continue;
}
if (!(n & CCM_ANALOG_PLL_USB2_EN_USB_CLKS)) {
CCM_ANALOG_PLL_USB2_SET = CCM_ANALOG_PLL_USB2_EN_USB_CLKS; // enable
continue;
}
println("USB2 PLL running");
break; // USB2 PLL up and running
}
// turn on USB clocks (should already be on)
CCM_CCGR6 |= CCM_CCGR6_USBOH3(CCM_CCGR_ON);
// turn on USB2 PHY
USBPHY2_CTRL_CLR = USBPHY_CTRL_SFTRST | USBPHY_CTRL_CLKGATE;
USBPHY2_CTRL_SET = USBPHY_CTRL_ENUTMILEVEL2 | USBPHY_CTRL_ENUTMILEVEL3;
USBPHY2_PWD = 0;
#ifdef ARDUINO_TEENSY41
IOMUXC_SW_MUX_CTL_PAD_GPIO_EMC_40 = 5;
IOMUXC_SW_PAD_CTL_PAD_GPIO_EMC_40 = 0x0008; // slow speed, weak 150 ohm drive
GPIO8_GDIR |= 1<<26;
GPIO8_DR_SET = 1<<26;
#endif
#endif
delay(10);
// now with the PHY up and running, start up USBHS
//print("begin ehci reset");
USBHS_USBCMD |= USBHS_USBCMD_RST;
int reset_count = 0;
while (USBHS_USBCMD & USBHS_USBCMD_RST) {
reset_count++;
}
println(" reset waited ", reset_count);
init_Device_Pipe_Transfer_memory();
for (int i=0; i < PERIODIC_LIST_SIZE; i++) {
periodictable[i] = 1;
}
memset(uframe_bandwidth, 0, sizeof(uframe_bandwidth));
port_state = PORT_STATE_DISCONNECTED;
USBHS_USB_SBUSCFG = 1; // System Bus Interface Configuration
// turn on the USBHS controller
//USBHS_USBMODE = USBHS_USBMODE_TXHSD(5) | USBHS_USBMODE_CM(3); // host mode
USBHS_USBMODE = USBHS_USBMODE_CM(3); // host mode
USBHS_USBINTR = 0;
USBHS_PERIODICLISTBASE = (uint32_t)periodictable;
USBHS_FRINDEX = 0;
USBHS_ASYNCLISTADDR = 0;
USBHS_USBCMD = USBHS_USBCMD_ITC(1) | USBHS_USBCMD_RS |
USBHS_USBCMD_ASP(3) | USBHS_USBCMD_ASPE | USBHS_USBCMD_PSE |
#if PERIODIC_LIST_SIZE == 8
USBHS_USBCMD_FS2 | USBHS_USBCMD_FS(3);
#elif PERIODIC_LIST_SIZE == 16
USBHS_USBCMD_FS2 | USBHS_USBCMD_FS(2);
#elif PERIODIC_LIST_SIZE == 32
USBHS_USBCMD_FS2 | USBHS_USBCMD_FS(1);
#elif PERIODIC_LIST_SIZE == 64
USBHS_USBCMD_FS2 | USBHS_USBCMD_FS(0);
#elif PERIODIC_LIST_SIZE == 128
USBHS_USBCMD_FS(3);
#elif PERIODIC_LIST_SIZE == 256
USBHS_USBCMD_FS(2);
#elif PERIODIC_LIST_SIZE == 512
USBHS_USBCMD_FS(1);
#elif PERIODIC_LIST_SIZE == 1024
USBHS_USBCMD_FS(0);
#else
#error "Unsupported PERIODIC_LIST_SIZE"
#endif
// turn on the USB port
//USBHS_PORTSC1 = USBHS_PORTSC_PP;
USBHS_PORTSC1 |= USBHS_PORTSC_PP;
//USBHS_PORTSC1 |= USBHS_PORTSC_PFSC; // force 12 Mbit/sec
//USBHS_PORTSC1 |= USBHS_PORTSC_PHCD; // phy off
println("USBHS_ASYNCLISTADDR = ", USBHS_ASYNCLISTADDR, HEX);
println("USBHS_PERIODICLISTBASE = ", USBHS_PERIODICLISTBASE, HEX);
println("periodictable = ", (uint32_t)periodictable, HEX);
// enable interrupts, after this point interruts to all the work
attachInterruptVector(IRQ_USBHS, isr);
NVIC_ENABLE_IRQ(IRQ_USBHS);
USBHS_USBINTR = USBHS_USBINTR_PCE | USBHS_USBINTR_TIE0 | USBHS_USBINTR_TIE1;
USBHS_USBINTR |= USBHS_USBINTR_UEE | USBHS_USBINTR_SEE;
USBHS_USBINTR |= USBHS_USBINTR_UPIE | USBHS_USBINTR_UAIE;
}
// EHCI registers page default
// -------------- ---- -------
// USBHS_USBCMD 1599 00080000 USB Command
// USBHS_USBSTS 1602 00000000 USB Status
// USBHS_USBINTR 1606 00000000 USB Interrupt Enable
// USBHS_FRINDEX 1609 00000000 Frame Index Register
// USBHS_PERIODICLISTBASE 1610 undefine Periodic Frame List Base Address
// USBHS_ASYNCLISTADDR 1612 undefine Asynchronous List Address
// USBHS_PORTSC1 1619 00002000 Port Status and Control
// USBHS_USBMODE 1629 00005000 USB Mode
// USBHS_GPTIMERnCTL 1591 00000000 General Purpose Timer n Control
// PORT_STATE_DISCONNECTED 0
// PORT_STATE_DEBOUNCE 1
// PORT_STATE_RESET 2
// PORT_STATE_RECOVERY 3
// PORT_STATE_ACTIVE 4
void USBHost::isr()
{
uint32_t stat = USBHS_USBSTS;
USBHS_USBSTS = stat; // clear pending interrupts
//stat &= USBHS_USBINTR; // mask away unwanted interrupts
#if 0
println();
println("ISR: ", stat, HEX);
//if (stat & USBHS_USBSTS_UI) println(" USB Interrupt");
if (stat & USBHS_USBSTS_UEI) println(" USB Error");
if (stat & USBHS_USBSTS_PCI) println(" Port Change");
//if (stat & USBHS_USBSTS_FRI) println(" Frame List Rollover");
if (stat & USBHS_USBSTS_SEI) println(" System Error");
//if (stat & USBHS_USBSTS_AAI) println(" Async Advance (doorbell)");
if (stat & USBHS_USBSTS_URI) println(" Reset Recv");
//if (stat & USBHS_USBSTS_SRI) println(" SOF");
if (stat & USBHS_USBSTS_SLI) println(" Suspend");
if (stat & USBHS_USBSTS_HCH) println(" Host Halted");
//if (stat & USBHS_USBSTS_RCL) println(" Reclamation");
//if (stat & USBHS_USBSTS_PS) println(" Periodic Sched En");
//if (stat & USBHS_USBSTS_AS) println(" Async Sched En");
if (stat & USBHS_USBSTS_NAKI) println(" NAK");
if (stat & USBHS_USBSTS_UAI) println(" USB Async");
if (stat & USBHS_USBSTS_UPI) println(" USB Periodic");
if (stat & USBHS_USBSTS_TI0) println(" Timer0");
if (stat & USBHS_USBSTS_TI1) println(" Timer1");
#endif
if (stat & USBHS_USBSTS_UAI) { // completed qTD(s) from the async schedule
//println("Async Followup");
//print(async_followup_first, async_followup_last);
Transfer_t *p = async_followup_first;
while (p) {
if (followup_Transfer(p)) {
// transfer completed
Transfer_t *next = p->next_followup;
remove_from_async_followup_list(p);
free_Transfer(p);
p = next;
} else {
// transfer still pending
p = p->next_followup;
}
}
//print(async_followup_first, async_followup_last);
}
if (stat & USBHS_USBSTS_UPI) { // completed qTD(s) from the periodic schedule
//println("Periodic Followup");
Transfer_t *p = periodic_followup_first;
while (p) {
if (followup_Transfer(p)) {
// transfer completed
Transfer_t *next = p->next_followup;
remove_from_periodic_followup_list(p);
free_Transfer(p);
p = next;
} else {
// transfer still pending
p = p->next_followup;
}
}
}
if (stat & USBHS_USBSTS_UEI) {
followup_Error();
}
if (stat & USBHS_USBSTS_PCI) { // port change detected
const uint32_t portstat = USBHS_PORTSC1;
println("port change: ", portstat, HEX);
USBHS_PORTSC1 = portstat | (USBHS_PORTSC_OCC|USBHS_PORTSC_PEC|USBHS_PORTSC_CSC);
if (portstat & USBHS_PORTSC_OCC) {
println(" overcurrent change");
}
if (portstat & USBHS_PORTSC_CSC) {
if (portstat & USBHS_PORTSC_CCS) {
println(" connect");
if (port_state == PORT_STATE_DISCONNECTED
|| port_state == PORT_STATE_DEBOUNCE) {
// 100 ms debounce (USB 2.0: TATTDB, page 150 & 188)
port_state = PORT_STATE_DEBOUNCE;
USBHS_GPTIMER0LD = 100000; // microseconds
USBHS_GPTIMER0CTL =
USBHS_GPTIMERCTL_RST | USBHS_GPTIMERCTL_RUN;
stat &= ~USBHS_USBSTS_TI0;
}
} else {
println(" disconnect");
port_state = PORT_STATE_DISCONNECTED;
USBPHY_CTRL_CLR = USBPHY_CTRL_ENHOSTDISCONDETECT;
disconnect_Device(rootdev);
rootdev = NULL;
}
}
if (portstat & USBHS_PORTSC_PEC) {
// PEC bit only detects disable
println(" disable");
} else if (port_state == PORT_STATE_RESET && portstat & USBHS_PORTSC_PE) {
println(" port enabled");
port_state = PORT_STATE_RECOVERY;
// 10 ms reset recover (USB 2.0: TRSTRCY, page 151 & 188)
USBHS_GPTIMER0LD = 10000; // microseconds
USBHS_GPTIMER0CTL = USBHS_GPTIMERCTL_RST | USBHS_GPTIMERCTL_RUN;
if (USBHS_PORTSC1 & USBHS_PORTSC_HSP) {
// turn on high-speed disconnect detector
USBPHY_CTRL_SET = USBPHY_CTRL_ENHOSTDISCONDETECT;
}
}
if (portstat & USBHS_PORTSC_FPR) {
println(" force resume");
}
}
if (stat & USBHS_USBSTS_TI0) { // timer 0 - used for built-in port events
//println("timer0");
if (port_state == PORT_STATE_DEBOUNCE) {
port_state = PORT_STATE_RESET;
// Since we have only 1 port, no other device can
// be in reset or enumeration. If multiple ports
// are ever supported, we would need to remain in
// debounce if any other port was resetting or
// enumerating a device.
USBHS_PORTSC1 |= USBHS_PORTSC_PR; // begin reset sequence
println(" begin reset");
} else if (port_state == PORT_STATE_RECOVERY) {
port_state = PORT_STATE_ACTIVE;
println(" end recovery");
// HCSPARAMS TTCTRL page 1671
uint32_t speed = (USBHS_PORTSC1 >> 26) & 3;
rootdev = new_Device(speed, 0, 0);
}
}
if (stat & USBHS_USBSTS_TI1) { // timer 1 - used for USBDriverTimer
//println("timer1");
USBDriverTimer *list = NULL, *last = NULL;
USBDriverTimer *timer = active_timers;
while (timer) {
USBDriverTimer *next = timer->next;
active_timers = next;
// create a list of all timer_event() callbacks to do
if (list == NULL) {
list = timer;
last = timer;
} else {
last->next = timer;
last = timer;
}
timer->next = NULL;
if (!next) break;
next->prev = NULL;
if (next->usec >= 5) { // TODO: is 5us a safe minimum?
USBHS_GPTIMER1LD = next->usec - 1;
USBHS_GPTIMER1CTL = USBHS_GPTIMERCTL_RST | USBHS_GPTIMERCTL_RUN;
break;
} else {
// next timer will be too soon for the hardware timer, so
// allow the next loop iteration to add it to the list
if (next->usec > 0 && next->next != NULL) {
// when we "lose" microseconds by calling early,
// adjust future timers so errors don't accumulate
next->next->usec += next->usec;
}
timer = next;
}
}
// do all callbacks after hardware timer is started, so time spent by
// the callback functions can't delay starting the hardware timer
while (list) {
USBDriverTimer *next = list->next;
list->prev = NULL;
list->next = NULL;
list->driver->timer_event(list);
list = next;
}
}
}
void USBDriverTimer::start(uint32_t microseconds)
{
#if 0
USBHost::print_("start_timer, us = ");
USBHost::print_(microseconds);
USBHost::print_(", driver = ");
USBHost::print_((uint32_t)driver, HEX);
USBHost::print_(", this = ");
USBHost::println_((uint32_t)this, HEX);
#endif
if (!driver) return;
if (microseconds < 100) return; // minimum timer duration
started_micros = micros();
if (active_timers == NULL) {
// schedule is empty, just add this timer
usec = microseconds;
next = NULL;
prev = NULL;
active_timers = this;
USBHS_GPTIMER1LD = microseconds - 1;
USBHS_GPTIMER1CTL = USBHS_GPTIMERCTL_RST | USBHS_GPTIMERCTL_RUN;
return;
}
uint32_t remain = USBHS_GPTIMER1CTL & 0xFFFFFF;
//USBHDBGSerial.print("remain = ");
//USBHDBGSerial.println(remain);
if (microseconds < remain) {
// this timer event is before any on the schedule
__disable_irq();
USBHS_GPTIMER1CTL = 0;
USBHS_USBSTS = USBHS_USBSTS_TI1; // TODO: UPI & UAI safety?!
usec = microseconds;
next = active_timers;
prev = NULL;
active_timers->usec = remain - microseconds;
active_timers->prev = this;
active_timers = this;
USBHS_GPTIMER1LD = microseconds - 1;
USBHS_GPTIMER1CTL = USBHS_GPTIMERCTL_RST | USBHS_GPTIMERCTL_RUN;
__enable_irq();
return;
}
// add this timer to the schedule, somewhere after the first timer
microseconds -= remain;
USBDriverTimer *list = active_timers;
while (list->next) {
list = list->next;
if (microseconds < list->usec) {
// add timer into middle of list
list->usec -= microseconds;
usec = microseconds;
next = list;
prev = list->prev;
list->prev = this;
prev->next = this;
return;
}
microseconds -= list->usec;
}
// add timer to the end of the schedule
usec = microseconds;
next = NULL;
prev = list;
list->next = this;
}
void USBDriverTimer::stop()
{
__disable_irq();
if (active_timers) {
if (active_timers == this) {
USBHS_GPTIMER1CTL = 0;
if (next) {
uint32_t usec_til_next = USBHS_GPTIMER1CTL & 0xFFFFFF;
usec_til_next += next->usec;
next->usec = usec_til_next;
USBHS_GPTIMER1LD = usec_til_next;
USBHS_GPTIMER1CTL = USBHS_GPTIMERCTL_RST | USBHS_GPTIMERCTL_RUN;
next->prev = NULL;
active_timers = next;
} else {
active_timers = NULL;
}
} else {
for (USBDriverTimer *t = active_timers->next; t; t = t->next) {
if (t == this) {
t->prev->next = t->next;
if (t->next) {
t->next->usec += t->usec;
t->next->prev = t->prev;
}
break;
}
}
}
}
__enable_irq();
}
static uint32_t QH_capabilities1(uint32_t nak_count_reload, uint32_t control_endpoint_flag,
uint32_t max_packet_length, uint32_t head_of_list, uint32_t data_toggle_control,
uint32_t speed, uint32_t endpoint_number, uint32_t inactivate, uint32_t address)
{
return ( (nak_count_reload << 28) | (control_endpoint_flag << 27) |
(max_packet_length << 16) | (head_of_list << 15) |
(data_toggle_control << 14) | (speed << 12) | (endpoint_number << 8) |
(inactivate << 7) | (address << 0) );
}
static uint32_t QH_capabilities2(uint32_t high_bw_mult, uint32_t hub_port_number,
uint32_t hub_address, uint32_t split_completion_mask, uint32_t interrupt_schedule_mask)
{
return ( (high_bw_mult << 30) | (hub_port_number << 23) | (hub_address << 16) |
(split_completion_mask << 8) | (interrupt_schedule_mask << 0) );
}
// Create a new pipe. It's QH is added to the async or periodic schedule,
// and a halt qTD is added to the QH, so we can grow the qTD list later.
// dev: device owning this pipe/endpoint
// type: 0=control, 2=bulk, 3=interrupt
// endpoint: 0 for control, 1-15 for bulk or interrupt
// direction: 0=OUT, 1=IN (unused for control)
// maxlen: maximum packet size
// interval: polling interval for interrupt, power of 2, unused if control or bulk
//
Pipe_t * USBHost::new_Pipe(Device_t *dev, uint32_t type, uint32_t endpoint,
uint32_t direction, uint32_t maxlen, uint32_t interval)
{
Pipe_t *pipe;
Transfer_t *halt;
uint32_t c=0, dtc=0;
println("new_Pipe");
pipe = allocate_Pipe();
if (!pipe) return NULL;
halt = allocate_Transfer();
if (!halt) {
free_Pipe(pipe);
return NULL;
}
memset(pipe, 0, sizeof(Pipe_t));
memset(halt, 0, sizeof(Transfer_t));
halt->qtd.next = 1;
halt->qtd.token = 0x40;
pipe->device = dev;
pipe->qh.next = (uint32_t)halt;
pipe->qh.alt_next = 1;
pipe->direction = direction;
pipe->type = type;
if (type == 3) {
// interrupt transfers require bandwidth & microframe scheduling
if (!allocate_interrupt_pipe_bandwidth(pipe, maxlen, interval)) {
free_Transfer(halt);
free_Pipe(pipe);
return NULL;
}
}
if (endpoint > 0) {
// if non-control pipe, update dev->data_pipes list
Pipe_t *p = dev->data_pipes;
if (p == NULL) {
dev->data_pipes = pipe;
} else {
while (p->next) p = p->next;
p->next = pipe;
}
}
if (type == 0) {
// control
if (dev->speed < 2) c = 1;
dtc = 1;
} else if (type == 2) {
// bulk
} else if (type == 3) {
// interrupt
//pipe->qh.token = 0x80000000; // TODO: OUT starts with DATA0 or DATA1?
}
pipe->qh.capabilities[0] = QH_capabilities1(15, c, maxlen, 0,
dtc, dev->speed, endpoint, 0, dev->address);
pipe->qh.capabilities[1] = QH_capabilities2(1, dev->hub_port,
dev->hub_address, pipe->complete_mask, pipe->start_mask);
if (type == 0 || type == 2) {
// control or bulk: add to async queue
Pipe_t *list = (Pipe_t *)USBHS_ASYNCLISTADDR;
if (list == NULL) {
pipe->qh.capabilities[0] |= 0x8000; // H bit
pipe->qh.horizontal_link = (uint32_t)&(pipe->qh) | 2; // 2=QH
USBHS_ASYNCLISTADDR = (uint32_t)&(pipe->qh);
USBHS_USBCMD |= USBHS_USBCMD_ASE; // enable async schedule
//println(" first in async list");
} else {
// EHCI 1.0: section 4.8.1, page 72
pipe->qh.horizontal_link = list->qh.horizontal_link;
list->qh.horizontal_link = (uint32_t)&(pipe->qh) | 2;
//println(" added to async list");
}
} else if (type == 3) {
// interrupt: add to periodic schedule
add_qh_to_periodic_schedule(pipe);
}
return pipe;
}
// Fill in the qTD fields (token & data)
// t the Transfer qTD to initialize
// buf data to transfer
// len length of data
// pid type of packet: 0=OUT, 1=IN, 2=SETUP
// data01 value of DATA0/DATA1 toggle on 1st packet
// irq whether to generate an interrupt when transfer complete
//
static void init_qTD(volatile Transfer_t *t, void *buf, uint32_t len,
uint32_t pid, uint32_t data01, bool irq)
{
t->qtd.alt_next = 1; // 1=terminate
if (data01) data01 = 0x80000000;
t->qtd.token = data01 | (len << 16) | (irq ? 0x8000 : 0) | (pid << 8) | 0x80;
uint32_t addr = (uint32_t)buf;
t->qtd.buffer[0] = addr;
addr &= 0xFFFFF000;
t->qtd.buffer[1] = addr + 0x1000;
t->qtd.buffer[2] = addr + 0x2000;
t->qtd.buffer[3] = addr + 0x3000;
t->qtd.buffer[4] = addr + 0x4000;
}
// Create a Control Transfer and queue it
//
bool USBHost::queue_Control_Transfer(Device_t *dev, setup_t *setup, void *buf, USBDriver *driver)
{
Transfer_t *transfer, *data, *status;
uint32_t status_direction;
//println("new_Control_Transfer");
if (setup->wLength > 16384) return false; // max 16K data for control
transfer = allocate_Transfer();
if (!transfer) {
println(" error allocating setup transfer");
return false;
}
status = allocate_Transfer();
if (!status) {
println(" error allocating status transfer");
free_Transfer(transfer);
return false;
}
if (setup->wLength > 0) {
data = allocate_Transfer();
if (!data) {
println(" error allocating data transfer");
free_Transfer(transfer);
free_Transfer(status);
return false;
}
uint32_t pid = (setup->bmRequestType & 0x80) ? 1 : 0;
init_qTD(data, buf, setup->wLength, pid, 1, false);
transfer->qtd.next = (uint32_t)data;
data->qtd.next = (uint32_t)status;
status_direction = pid ^ 1;
} else {
transfer->qtd.next = (uint32_t)status;
status_direction = 1; // always IN, USB 2.0 page 226
}
//println("setup address ", (uint32_t)setup, HEX);
init_qTD(transfer, setup, 8, 2, 0, false);
init_qTD(status, NULL, 0, status_direction, 1, true);
status->pipe = dev->control_pipe;
status->buffer = buf;
status->length = setup->wLength;
status->setup.word1 = setup->word1;
status->setup.word2 = setup->word2;
status->driver = driver;
status->qtd.next = 1;
return queue_Transfer(dev->control_pipe, transfer);
}
// Create a Bulk or Interrupt Transfer and queue it
//
bool USBHost::queue_Data_Transfer(Pipe_t *pipe, void *buffer, uint32_t len, USBDriver *driver)
{
Transfer_t *transfer, *data, *next;
uint8_t *p = (uint8_t *)buffer;
uint32_t count;
bool last = false;
// We always want to do this while the interrupt is disabled.
// But only re-enable if it was enabled coming in.
bool irq_was_enabled = NVIC_IS_ENABLED(IRQ_USBHS);
NVIC_DISABLE_IRQ(IRQ_USBHS);
// TODO: option for zero length packet? Maybe in Pipe_t fields?
//println("new_Data_Transfer");
// allocate qTDs
transfer = allocate_Transfer();
if (!transfer) {
if (irq_was_enabled) NVIC_ENABLE_IRQ(IRQ_USBHS);
return false;
}
data = transfer;
for (count=((len-1) >> 14); count; count--) {
next = allocate_Transfer();
if (!next) {
// free already-allocated qTDs
while (1) {
next = (Transfer_t *)transfer->qtd.next;
free_Transfer(transfer);
if (transfer == data) break;
transfer = next;
}
if (irq_was_enabled) NVIC_ENABLE_IRQ(IRQ_USBHS);
return false;
}
data->qtd.next = (uint32_t)next;
data = next;
}
// last qTD needs info for followup
data->qtd.next = 1;
data->pipe = pipe;
data->buffer = buffer;
data->length = len;
data->setup.word1 = 0;
data->setup.word2 = 0;
data->driver = driver;
// initialize all qTDs
data = transfer;
while (1) {
uint32_t count = len;
if (count > 16384) {
count = 16384;
} else {
last = true;
}
init_qTD(data, p, count, pipe->direction, 0, last);
if (last) break;
p += count;
len -= count;
data = (Transfer_t *)(data->qtd.next);
}
bool return_value = queue_Transfer(pipe, transfer);
if (irq_was_enabled) NVIC_ENABLE_IRQ(IRQ_USBHS);
return return_value;
}
bool USBHost::queue_Transfer(Pipe_t *pipe, Transfer_t *transfer)
{
// find halt qTD
Transfer_t *halt = (Transfer_t *)(pipe->qh.next);
while (!(halt->qtd.token & 0x40)) halt = (Transfer_t *)(halt->qtd.next);
// transfer's token
uint32_t token = transfer->qtd.token;
// transfer becomes new halt qTD
transfer->qtd.token = 0x40;
// copy transfer non-token fields to halt
halt->qtd.next = transfer->qtd.next;
halt->qtd.alt_next = transfer->qtd.alt_next;
halt->qtd.buffer[0] = transfer->qtd.buffer[0]; // TODO: optimize memcpy, all
halt->qtd.buffer[1] = transfer->qtd.buffer[1]; // fields except token
halt->qtd.buffer[2] = transfer->qtd.buffer[2];
halt->qtd.buffer[3] = transfer->qtd.buffer[3];
halt->qtd.buffer[4] = transfer->qtd.buffer[4];
halt->pipe = pipe;
halt->buffer = transfer->buffer;
halt->length = transfer->length;
halt->setup = transfer->setup;
halt->driver = transfer->driver;
// find the last qTD we're adding
Transfer_t *last = halt;
while ((uint32_t)(last->qtd.next) != 1) last = (Transfer_t *)(last->qtd.next);
// last points to transfer (which becomes new halt)
last->qtd.next = (uint32_t)transfer;
transfer->qtd.next = 1;
// link all the new qTD by next_followup & prev_followup
Transfer_t *prev = NULL;
Transfer_t *p = halt;
while (p->qtd.next != (uint32_t)transfer) {
Transfer_t *next = (Transfer_t *)p->qtd.next;
p->prev_followup = prev;
p->next_followup = next;
prev = p;
p = next;
}
p->prev_followup = prev;
p->next_followup = NULL;
//print(halt, p);
// add them to a followup list
if (pipe->type == 0 || pipe->type == 2) {
// control or bulk
add_to_async_followup_list(halt, p);
} else {
// interrupt
add_to_periodic_followup_list(halt, p);
}
// old halt becomes new transfer, this commits all new qTDs to QH
halt->qtd.token = token;
return true;
}
bool USBHost::followup_Transfer(Transfer_t *transfer)
{
//print(" Followup ", (uint32_t)transfer, HEX);
//println(" token=", transfer->qtd.token, HEX);
if (!(transfer->qtd.token & 0x80)) {
// TODO: check error status
if (transfer->qtd.token & 0x8000) {
// this transfer caused an interrupt
if (transfer->pipe->callback_function) {
// do the callback
(*(transfer->pipe->callback_function))(transfer);
}
}
// do callback function...
//println(" completed");
return true;
}
return false;
}
void USBHost::followup_Error(void)
{
println("ERROR Followup");
Transfer_t *p = async_followup_first;
while (p) {
if (followup_Transfer(p)) {
// transfer completed
Transfer_t *next = p->next_followup;
remove_from_async_followup_list(p);
println(" remove from followup list");
if (p->qtd.token & 0x40) {
Pipe_t *haltedpipe = p->pipe;
free_Transfer(p);
// traverse the rest of the list for unfinished work
// from this halted pipe. Remove from the followup
// list and put onto our own temporary list
Transfer_t *first = NULL;
Transfer_t *last = NULL;
p = next;
while (p) {
Transfer_t *next2 = p->next_followup;
if (p->pipe == haltedpipe) {
println(" stray halted ", (uint32_t)p, HEX);
remove_from_async_followup_list(p);
if (first == NULL) {
first = p;
last = p;
} else {
last->next_followup = p;
}
p->next_followup = NULL;
if (next == p) next = next2;
}
p = next2;
}
// halted pipe (probably) still has unfinished transfers
// find the halted pipe's dummy halt transfer
p = (Transfer_t *)(haltedpipe->qh.next & ~0x1F);
while (p && ((p->qtd.token & 0x40) == 0)) {
print(" qtd: ", (uint32_t)p, HEX);
print(", token=", (uint32_t)p->qtd.token, HEX);
println(", next=", (uint32_t)p->qtd.next, HEX);
p = (Transfer_t *)(p->qtd.next & ~0x1F);
}
if (p) {
// unhalt the pipe, "forget" unfinished transfers
// hopefully they're all on the list we made!
println(" dummy halt: ", (uint32_t)p, HEX);
haltedpipe->qh.next = (uint32_t)p;
haltedpipe->qh.current = 0;
haltedpipe->qh.token = 0;
} else {
println(" no dummy halt found, yikes!");
// TODO: this should never happen, but what if it does?
}
// Do any driver callbacks belonging to the unfinished
// transfers. This is done last, after retoring the
// pipe to a working state (if possible) so the driver
// callback can use the pipe.
p = first;
while (p) {
uint32_t token = p->qtd.token;
if (token & 0x8000 && haltedpipe->callback_function) {
// driver expects a callback
p->qtd.token = token | 0x40;
(*(p->pipe->callback_function))(p);
}
Transfer_t *next2 = p->next_followup;
free_Transfer(p);
p = next2;
}
} else {
free_Transfer(p);
}
p = next;
} else {
// transfer still pending
println(" remain on followup list");
p = p->next_followup;
}
}
// TODO: handle errors from periodic schedule!
}
static void add_to_async_followup_list(Transfer_t *first, Transfer_t *last)
{
last->next_followup = NULL; // always add to end of list
if (async_followup_last == NULL) {
first->prev_followup = NULL;
async_followup_first = first;
} else {
first->prev_followup = async_followup_last;