forked from palera1n/PongoOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
synopsys_otg.c
1903 lines (1783 loc) · 71 KB
/
synopsys_otg.c
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
//
// @bazad's synopsysOTG driver
// Copyright 2019 Google LLC
// Copyright 2019 checkra1n team
//
#include <pongo.h>
uint64_t gSynopsysBase;
uint64_t gSynopsysOTGBase;
uint64_t gSynopsysComplexBase;
uint32_t gSynopsysCoreVersion;
struct _reg { uint32_t off; };
#define SYNOPSYS_OTG_REGISTER(_x) ((struct _reg) { _x })
#include "synopsys_otg_regs.h"
static uint32_t reg_read(struct _reg reg) {
return *(volatile uint32_t *)(gSynopsysBase + reg.off);
}
static void reg_write(struct _reg reg, uint32_t val) {
#if defined(USB_DEBUG_LEVEL) && USB_DEBUG_LEVEL >= 2
if (reg.off != rGINTSTS.off) {
USB_DEBUG(USB_DEBUG_REG, "wr%03x %x", reg.off, val);
}
#endif
*(volatile uint32_t *)(gSynopsysBase + reg.off) = val;
}
static void reg_and(struct _reg reg, uint32_t val) {
#if defined(USB_DEBUG_LEVEL) && USB_DEBUG_LEVEL >= 2
USB_DEBUG(USB_DEBUG_REG, "an%03x %x", reg.off, val);
#endif
*(volatile uint32_t *)(gSynopsysBase + reg.off) &= val;
}
static void reg_or(struct _reg reg, uint32_t val) {
#if defined(USB_DEBUG_LEVEL) && USB_DEBUG_LEVEL >= 2
USB_DEBUG(USB_DEBUG_REG, "or%03x %x", reg.off, val);
#endif
*(volatile uint32_t *)(gSynopsysBase + reg.off) |= val;
}
static void USB_DEBUG_PRINT_REGISTERS();
static void USB_DEBUG_PRINT_REGISTERS() {
disable_interrupts();
#define USB_DEBUG_REG_VALUE(reg) USB_DEBUG(USB_DEBUG_STANDARD, #reg " = 0x%x\n", reg_read(reg));
USB_DEBUG_REG_VALUE(rGOTGCTL);
USB_DEBUG_REG_VALUE(rGOTGINT);
USB_DEBUG_REG_VALUE(rGAHBCFG);
USB_DEBUG_REG_VALUE(rGUSBCFG);
USB_DEBUG_REG_VALUE(rGRSTCTL);
USB_DEBUG_REG_VALUE(rGINTSTS);
USB_DEBUG_REG_VALUE(rGINTMSK);
USB_DEBUG_REG_VALUE(rGRXSTSR);
USB_DEBUG_REG_VALUE(rGRXSTSP);
USB_DEBUG_REG_VALUE(rGRXFSIZ);
USB_DEBUG_REG_VALUE(rGNPTXFSIZ);
USB_DEBUG_REG_VALUE(rGNPTXSTS);
USB_DEBUG_REG_VALUE(rGI2CCTL);
USB_DEBUG_REG_VALUE(rGPVNDCTL);
USB_DEBUG_REG_VALUE(rGGPIO);
USB_DEBUG_REG_VALUE(rGUID);
USB_DEBUG_REG_VALUE(rGSNPSID);
USB_DEBUG_REG_VALUE(rGHWCFG1);
USB_DEBUG_REG_VALUE(rGHWCFG2);
USB_DEBUG_REG_VALUE(rGHWCFG3);
USB_DEBUG_REG_VALUE(rGHWCFG4);
USB_DEBUG_REG_VALUE(rGLPMCFG);
USB_DEBUG_REG_VALUE(rGPWRDN);
USB_DEBUG_REG_VALUE(rGDFIFOCFG);
USB_DEBUG_REG_VALUE(rADPCTL);
USB_DEBUG_REG_VALUE(rHPTXFSIZ);
USB_DEBUG_REG_VALUE(rDTXFSIZ(0));
USB_DEBUG_REG_VALUE(rDTXFSIZ(1));
USB_DEBUG_REG_VALUE(rDTXFSIZ(2));
USB_DEBUG_REG_VALUE(rDTXFSIZ(3));
USB_DEBUG_REG_VALUE(rDTXFSIZ(4));
USB_DEBUG_REG_VALUE(rDCFG);
USB_DEBUG_REG_VALUE(rDCTL);
USB_DEBUG_REG_VALUE(rDSTS);
USB_DEBUG_REG_VALUE(rDIEPMSK);
USB_DEBUG_REG_VALUE(rDOEPMSK);
USB_DEBUG_REG_VALUE(rDAINT);
USB_DEBUG_REG_VALUE(rDAINTMSK);
USB_DEBUG_REG_VALUE(rDIEPCTL(0));
USB_DEBUG_REG_VALUE(rDIEPINT(0));
USB_DEBUG_REG_VALUE(rDIEPTSIZ(0));
USB_DEBUG_REG_VALUE(rDIEPDMA(0));
USB_DEBUG_REG_VALUE(rDTXFSTS(0));
USB_DEBUG_REG_VALUE(rDOEPCTL(0));
USB_DEBUG_REG_VALUE(rDOEPINT(0));
USB_DEBUG_REG_VALUE(rDOEPTSIZ(0));
USB_DEBUG_REG_VALUE(rDOEPDMA(0));
USB_DEBUG_REG_VALUE(rDIEPCTL(1));
USB_DEBUG_REG_VALUE(rDIEPINT(1));
USB_DEBUG_REG_VALUE(rDIEPTSIZ(1));
USB_DEBUG_REG_VALUE(rDIEPDMA(1));
USB_DEBUG_REG_VALUE(rDTXFSTS(1));
enable_interrupts();
}
struct task usb_task = {.name = "usb"};
static const char *string_descriptors[] = {
[iManufacturer] = "checkra1n team",
[iProduct] = "pongoOS USB Device",
[iSerialNumber] = ("pongoOS / checkra1n "PONGO_VERSION),
};
static const uint32_t string_descriptor_count = sizeof(string_descriptors) / sizeof(string_descriptors[0]);
struct device_descriptor device_descriptor = {
.bLength = sizeof(struct device_descriptor),
.bDescriptorType = 1,
.bcdUSB = 0x200,
.bDeviceClass = 0,
.bDeviceSubClass = 0,
.bDeviceProtocol = 0,
.bMaxPacketSize0 = EP0_MAX_PACKET_SIZE,
.idVendor = 0x5ac,
.idProduct = 0x4141,
.bcdDevice = 0,
.iManufacturer = iManufacturer,
.iProduct = iProduct,
.iSerialNumber = iSerialNumber,
.bNumConfigurations = 1,
};
struct full_configuration_descriptor {
struct configuration_descriptor configuration;
struct interface_descriptor interface;
struct endpoint_descriptor endpoint_81;
struct endpoint_descriptor endpoint_02;
} __attribute__((packed));
struct full_configuration_descriptor configuration_descriptor = {
.configuration = {
.bLength = sizeof(configuration_descriptor.configuration),
.bDescriptorType = 2,
.wTotalLength = sizeof(configuration_descriptor),
.bNumInterfaces = 1,
.bConfigurationValue = 1,
.iConfiguration = iProduct,
.bmAttributes = 0x80,
.bMaxPower = 250,
},
.interface = {
.bLength = sizeof(configuration_descriptor.interface),
.bDescriptorType = 4,
.bInterfaceNumber = 0,
.bAlternateSetting = 0,
.bNumEndpoints = 2,
.bInterfaceClass = 0xfe,
.bInterfaceSubClass = 0x13,
.bInterfaceProtocol = 0x37,
.iInterface = 0,
},
.endpoint_81 = {
.bLength = sizeof(configuration_descriptor.endpoint_81),
.bDescriptorType = 5,
.bEndpointAddress = 0x81, // IN
.bmAttributes = 3, // Interrupt
.wMaxPacketSize = INTR_EP_MAX_PACKET_SIZE,
.bInterval = 1, // Poll every 125us
},
.endpoint_02 = {
.bLength = sizeof(configuration_descriptor.endpoint_02),
.bDescriptorType = 5,
.bEndpointAddress = 0x02, // OUT
.bmAttributes = 2, // Bulk
.wMaxPacketSize = BULK_EP_MAX_PACKET_SIZE,
.bInterval = 0,
},
};
// ---- The KTRW USB API --------------------------------------------------------------------------
// These functions are provided by the layer below us.
void ep0_begin_data_in_stage(const void *data, uint32_t size, void (*callback)(void));
void ep0_begin_data_out_stage(bool (*callback)(const void *data, uint32_t size));
// The KTRW USB protocol supports 2 control transfer types:
//
// - IN 0x41: Send data from KTRW to GDB.
//
// wValue starts at 0 and is incremented each time the data is received successfully. That
// way, if another request comes in for the same wValue index, we can detect that the
// previous data was not received and resend it. (This feature isn't currently used.)
//
// wIndex is 0x1337.
//
// - OUT 0x41: Receive data from GDB to KTRW.
//
// wValue starts at 0 and is incremented each time new data is sent. (This feature isn't
// currently used.)
//
// wIndex is 0x1337.
//
static uint8_t ktrw_send_data[0x1000];
static uint16_t ktrw_send_count;
static uint16_t ktrw_send_in_flight;
static uint8_t ktrw_recv_data[0x1000];
static uint16_t ktrw_recv_count;
static void
ktrw_send_done() {
USB_DEBUG(USB_DEBUG_APP, "ktrw_send done");
if (ktrw_send_in_flight > ktrw_send_count) {
USB_DEBUG(USB_DEBUG_FATAL, "in_flight %u > %u send_count",
ktrw_send_in_flight, ktrw_send_count);
BUG(0x6966203e207363); // 'if > sc'
}
uint16_t send_left = ktrw_send_count - ktrw_send_in_flight;
memcpy(ktrw_send_data, ktrw_send_data + ktrw_send_in_flight, send_left);
ktrw_send_count = send_left;
ktrw_send_in_flight = send_left;
if (send_left > 0) {
USB_DEBUG(USB_DEBUG_APP, "ktrw_send'(%.*s)", (int) ktrw_send_in_flight,
(char *) ktrw_send_data);
usb_in_transfer(0x81, ktrw_send_data, send_left, ktrw_send_done);
}
}
static bool
ktrw_recv_done(const void *data, uint32_t size) {
uint16_t copy_size = sizeof(ktrw_recv_data) - ktrw_recv_count;
if (copy_size < size) {
return false;
}
if (copy_size > size) {
copy_size = size;
}
USB_DEBUG(USB_DEBUG_APP, "ktrw_recv(%.*s)", (int) size, (char *) data);
memcpy(ktrw_recv_data + ktrw_recv_count, data, copy_size);
ktrw_recv_count += copy_size;
return true;
}
static bool
ktrw_recv(uint16_t wLength) {
uint16_t capacity = sizeof(ktrw_recv_data) - ktrw_recv_count;
if (wLength > capacity) {
return false;
}
ep0_begin_data_out_stage(ktrw_recv_done);
return true;
}
extern bool ep0_device_request(struct setup_packet *setup);
static bool
ep0_vendor_request(struct setup_packet *setup) {
if ((setup->bmRequestType & 0x80) == 0) {
if (setup->bRequest == 0x41 && setup->wIndex == 0x1337) {
return ktrw_recv(setup->wLength);
}
}
return false;
}
size_t
usb_read(void *data, size_t size) {
size_t read_size = ktrw_recv_count;
if (read_size > size) {
read_size = size;
}
memcpy(data, ktrw_recv_data, read_size);
size_t recv_left = ktrw_recv_count - read_size;
memcpy(ktrw_recv_data, ktrw_recv_data + read_size, recv_left);
ktrw_recv_count = recv_left;
return read_size;
}
size_t
usb_write(const void *data, size_t size) {
size_t write_size = sizeof(ktrw_send_data) - ktrw_send_count;
if (write_size > size) {
write_size = size;
}
memcpy(ktrw_send_data + ktrw_send_count, data, write_size);
ktrw_send_count += write_size;
return write_size;
}
void
usb_write_commit() {
if (ktrw_send_count > 0 && ktrw_send_in_flight == 0) {
ktrw_send_in_flight = ktrw_send_count;
USB_DEBUG(USB_DEBUG_APP, "ktrw_send(%.*s)", (int) ktrw_send_in_flight,
(char *) ktrw_send_data);
usb_in_transfer(0x81, ktrw_send_data, ktrw_send_count, ktrw_send_done);
}
}
// ---- The high-level USB API --------------------------------------------------------------------
// USB functions needed by this level.
static void usb_set_address(uint8_t address);
#define MAX_USB_DESCRIPTOR_LENGTH 63
static bool
get_string_descriptor(uint8_t index) {
if (index >= string_descriptor_count) {
return false;
}
struct {
struct string_descriptor descriptor; // 2 bytes
uint16_t utf16[MAX_USB_DESCRIPTOR_LENGTH]; // 126 bytes
} sd;
uint16_t length;
if (index == 0) {
length = 1;
sd.utf16[0] = 0x0409;
} else {
const char *string = string_descriptors[index];
length = strlen(string);
if (length > MAX_USB_DESCRIPTOR_LENGTH) {
length = MAX_USB_DESCRIPTOR_LENGTH;
}
for (uint8_t i = 0; i < length; i++) {
sd.utf16[i] = string[i];
}
}
uint16_t size = sizeof(sd.descriptor) + length * sizeof(sd.utf16[0]);
sd.descriptor.bLength = size;
sd.descriptor.bDescriptorType = 3; // String descriptor
ep0_begin_data_in_stage(&sd, size, NULL);
return true;
}
static bool
ep0_get_descriptor_request(struct setup_packet *setup) {
uint8_t type = (uint8_t) (setup->wValue >> 8);
uint8_t index = (uint8_t) (setup->wValue & 0xff);
switch (type) {
case 1: // Device descriptor
ep0_begin_data_in_stage(&device_descriptor,
sizeof(device_descriptor), NULL);
return true;
case 2: // Configuration descriptor
ep0_begin_data_in_stage(&configuration_descriptor,
sizeof(configuration_descriptor), NULL);
return true;
case 3: // String descriptor
return get_string_descriptor(index);
default:
goto invalid;
}
invalid:
USB_DEBUG(USB_DEBUG_STANDARD, "Unhandled get descriptor type %d", type);
USB_DEBUG_ABORT();
return false;
}
static bool
ep0_standard_in_request(struct setup_packet *setup) {
switch (setup->bRequest) {
case 6: // GET_DESCRIPTOR
return ep0_get_descriptor_request(setup);
case 8: // GET_CONFIGURATION
ep0_begin_data_in_stage(&configuration_descriptor.configuration
.bConfigurationValue, 1, NULL);
return true;
case 10: // GET_INTERFACE
ep0_begin_data_in_stage(&configuration_descriptor.interface
.bAlternateSetting, 1, NULL);
return true;
}
USB_DEBUG(USB_DEBUG_STANDARD, "Unhandled standard IN request %d", setup->bRequest);
USB_DEBUG_ABORT();
return false;
}
static bool
ep0_standard_out_request(struct setup_packet *setup) {
switch (setup->bRequest) {
case 5: // SET_ADDRESS
usb_set_address(setup->wValue & 0x7f);
return true;
case 9: // SET_CONFIGURATION
// Ignore :)
return true;
case 11: // SET_INTERFACE
// Ignore :)
return true;
}
USB_DEBUG(USB_DEBUG_STANDARD, "Unhandled standard OUT request %d", setup->bRequest);
USB_DEBUG_ABORT();
return false;
}
static bool
ep0_standard_request(struct setup_packet *setup) {
if ((setup->bmRequestType & 0x80) == 0x80) {
return ep0_standard_in_request(setup);
} else {
return ep0_standard_out_request(setup);
}
}
static bool
ep0_setup_stage(struct setup_packet *setup) {
USB_DEBUG(USB_DEBUG_STAGE, "[%u] SETUP {%02x,%02x,%04x,%04x,%04x}",
USB_DEBUG_ITERATION, setup->bmRequestType, setup->bRequest,
setup->wValue, setup->wIndex, setup->wLength);
uint8_t type = setup->bmRequestType & 0x60;
enable_interrupts();
bool rv = false;
switch (type) {
case 0: // Standard
rv = ep0_standard_request(setup);
break;
case 0x20: // Device
rv = ep0_device_request(setup);
break;
case 0x40: // Vendor
rv = ep0_vendor_request(setup);
break;
default:
USB_DEBUG(USB_DEBUG_STAGE, "Unhandled request type 0x%x", type);
break;
}
disable_interrupts();
return rv;
}
// ---- USB endpoint state ------------------------------------------------------------------------
// The size of the default DMA buffer. There is a 0x4000-byte DMA page divided between 4 endpoints.
#define DMA_BUFFER_SIZE (0x4000 / 4)
// A sentinel value for tarnsfer_size to indicate that we actually want to send an empty packet
// (ZLP).
#define TRANSFER_ZLP ((uint32_t)(-1))
// For EP 0 OUT transactions, indicates that we expect the next packet to be an OUT DATA
// transaction. Otherwise, the default is that we always expect a SETUP packet.
#define RECV_DATA 0x1
// State for managing data transfer over an endpoint.
struct endpoint_state {
// -- Endpoint info --
//
// Information about the endpoint itself.
//
// Initialized during endpoint activation.
// The endpoint type. 0 = Control, 1 = Isochronous, 2 = Bulk, 3 = Interrupt.
uint8_t type;
// The endpoint number.
uint8_t n:7;
// The endpoint direction. 0 = OUT, 1 = IN.
uint8_t dir_in:1;
// The maximum packet size on this endpoint.
uint16_t max_packet_size;
// -- Default DMA buffer --
//
// The following fields define the default buffer to use in DMA transfers. See "DMA buffer
// management" below.
//
// Initialized during usb_init().
// The virtual address of the default DMA buffer.
uint8_t *default_xfer_dma_data;
// The size of the default DMA buffer.
uint32_t default_xfer_dma_size;
// The physical address of the default DMA buffer.
uint32_t default_xfer_dma_phys;
// -- DMA buffer management --
//
// The following fields are used to manage DMA transfers. Physical pages suitable for DMA
// may be a scarce resource; in order to accomodate transfers larger than the amount of
// available DMA buffer space, the DMA buffer address and size are stored separately from
// the transfer buffer.
//
// Usually, these will be equal to the default DMA buffer.
//
// As a special-case optimization, a USB transfer may be given a custom DMA buffer to use
// in place of the default buffer. When this happens, DMA will be performed directly
// from/to the specified buffer, eliminating the need to periodically copy data out of the
// DMA buffer as it fills.
// The virtual address of the DMA buffer of data to transfer.
uint8_t *xfer_dma_data;
// The size of the DMA buffer.
uint32_t xfer_dma_size;
// The physical address of the DMA buffer.
uint32_t xfer_dma_phys;
// -- Transfer state --
//
// The endpoint state keeps track of only one USB transfer at a time; requests cannot be
// queued on the endpoint as with the SecureROM's USB stack. The transfer_data buffer is
// managed in units of size xfer_dma_size (or units of 1 packet for OUT Control endpoints).
// The buffer to/from which data is transferred. This is usually a pointer to a buffer
// larger than the size of the DMA buffer.
uint8_t *transfer_data;
// The amount of data to transfer to/from the host. If transfer_size == TRANSFER_ZLP, then
// we expect to send/receive an empty packet.
uint32_t transfer_size;
// The amount of data transferred so far. This can be greater than transfer_size only for
// OUT endpoints and only if the host unexpectedly sent us more data than it claimed it
// would.
uint32_t transferred;
// For IN endpoints, the amount of data in flight to the host.
//
// For OUT Control endpoints, RECV_DATA to indicate that we expect to receive a data
// packet, and 0 to indicate that we expect to receive a setup packet.
//
// For OUT non-Control endpoints, RECV_DATA to indicate that we are in an OUT transfer, and
// 0 to indicate that there is no currently scheduled OUT transfer.
uint32_t in_flight;
};
// The endpoints.
static struct endpoint_state ep0_in;
static struct endpoint_state ep0_out;
static struct endpoint_state ep1_in;
static struct endpoint_state ep2_out;
// ---- Low-level transfer API for IN endpoints ---------------------------------------------------
// Compute the parameters for an IN transfer.
static void
ep_in_send_compute_xfer(struct endpoint_state *ep,
uint32_t *dma_offset_out, uint32_t *hw_xfer_size_out, uint32_t *packet_count_out) {
// New data is copied from the transfer_data buffer into the DMA buffer only once the DMA
// buffer has been fully sent. Thus, we will transfer data from the DMA buffer starting at
// offset transferred % xfer_dma_size.
//
// Maths: We know xfer_dma_size and transferred are both 0 mod max_packet_size, so
// dma_offset and dma_left are 0 mod max_packet_size. dma_offset < xfer_dma_size, so
// dma_left > 0. Thus dma_left >= max_packet_size.
uint32_t dma_offset = ep->transferred % ep->xfer_dma_size;
uint32_t dma_left = ep->xfer_dma_size - dma_offset;
// Compute the amount of transfer left.
uint32_t xfer_size = ep->transfer_size - ep->transferred;
uint32_t packet_count = 1;
if (ep->transfer_size == TRANSFER_ZLP) {
// If we are sending an empty packet, xfer_size is 0.
xfer_size = 0;
} else {
if (ep->type == 0) {
// If we are sending data on EP 0 IN, then cap the transfer size at 1
// packet.
if (xfer_size > ep->max_packet_size) {
xfer_size = ep->max_packet_size;
}
} else {
// Cap the transfer size to the size of the DMA buffer.
if (xfer_size > dma_left) {
xfer_size = dma_left;
}
// Cap the transfer size by the width of DIEPTSIZ.xfersize. We round down
// one full packet to ensure that we don't send a partial packet and signal
// the end of the transfer.
if (xfer_size > 0x7ffff) {
xfer_size = 0x7ffff + 1 - ep->max_packet_size;
}
// TODO: Consider GHWCFG3!
// If we are sending at least one full packet of data on EP !0 IN, then
// compute the number of packets we need to send. If the data we're sending
// completely fills all packets with no remainder, then we'll also need to
// tack on an empty packet to signal the end of the transfer. I thought
// this could be programmed here, but it appears to not work correctly, so
// I've moved sending the ZLP to ep_in_send_done().
if (xfer_size > ep->max_packet_size) {
packet_count = (xfer_size + ep->max_packet_size - 1)
/ ep->max_packet_size;
}
}
}
if (xfer_size > dma_left || dma_left < ep->max_packet_size) {
USB_DEBUG(USB_DEBUG_FATAL, "xfer_size %u, dma_left %u, mps %u",
xfer_size, dma_left, (unsigned) ep->max_packet_size);
BUG(0x7866696e206264); // 'xfin bd'
}
*dma_offset_out = dma_offset;
*hw_xfer_size_out = xfer_size;
*packet_count_out = packet_count;
}
// Execute or continue an IN transaction (EP 0) or IN transfer (EP !0) on the endpoint. This
// function should not be called directly.
//
// The fields transfer_size, transferred, and transfer_data should be initialized before calling
// this function. in_flight is set on return.
static void ep_in_send(struct endpoint_state *ep) {
if (ep->dir_in != 1 || ep->in_flight != 0) {
BUG(0x73656e642031); // 'send 1'
}
if (ep->transferred >= ep->transfer_size && ep->transfer_size != TRANSFER_ZLP) {
USB_DEBUG(USB_DEBUG_XFER, "transfer_size %u, transferred %u",
ep->transfer_size, ep->transferred);
BUG(0x73656e642032); // 'send 2'
}
// Compute the offset into the DMA buffer, the size of the transfer, and the number of
// packets.
uint32_t dma_offset, hw_xfer_size, packet_count;
ep_in_send_compute_xfer(ep, &dma_offset, &hw_xfer_size, &packet_count);
USB_DEBUG(USB_DEBUG_XFER, "EP%u IN xfer %u|%u|%u", ep->n,
dma_offset, hw_xfer_size, packet_count);
// New data is copied from the transfer_data buffer into the DMA buffer only once the DMA
// buffer has been fully sent and is ready to be filled again.
if (dma_offset == 0 && hw_xfer_size > 0) {
uint32_t cache_length;
if (ep->xfer_dma_data == ep->transfer_data) {
// In direct DMA mode, the DMA buffer already contains all the data.
cache_length = ep->transfer_size;
if (cache_length == TRANSFER_ZLP) {
BUG(0x6e6f207a6c70); // 'no zlp'
}
} else {
// In buffered DMA mode, data is copied from the transfer_data buffer into
// the DMA buffer.
memcpy(ep->xfer_dma_data, ep->transfer_data + ep->transferred,
hw_xfer_size);
cache_length = hw_xfer_size;
}
// Make sure the writes hit the DMA buffer before starting DMA.
cache_clean_and_invalidate(ep->xfer_dma_data, cache_length);
}
// Set the registers.
reg_write(rDIEPDMA(ep->n), ep->xfer_dma_phys + dma_offset);
reg_write(rDIEPTSIZ(ep->n), (packet_count << 19) | hw_xfer_size);
reg_or(rDIEPCTL(ep->n), 0x84000000);
// We now have data in flight.
ep->in_flight = hw_xfer_size;
}
// Call this once the hardware signals that a transfer on an IN endpoint initiated with
// ep_in_send_data() is complete (DIEPINT(n).xfercompl). This function will update state and return
// true if all the requested data has been sent.
static bool
ep_in_send_done(struct endpoint_state *ep) {
if (ep->dir_in != 1) {
BUG(0x73656e642033); // 'send 3'
}
USB_DEBUG(USB_DEBUG_XFER, "DIEPTSIZ(%u) = %x", ep->n, reg_read(rDIEPTSIZ(ep->n)));
// Update the amount of data that has been transferred and the amount in flight.
ep->transferred += ep->in_flight;
ep->in_flight = 0;
// If we were sending a ZLP, replace transfer_size.
if (ep->transfer_size == TRANSFER_ZLP) {
ep->transfer_size = 0;
}
// Check if we're done sending all the data.
if (ep->transferred == ep->transfer_size) {
// Handle sending a ZLP after transferring a whole number of full packets.
// Initially this was done by configuring DIEPTSIZ to include the ZLP in the
// initial call to ep_in_send() (thus avoiding another call out to the USB stack),
// but the hardware does not seem to handle this case.
bool need_zlp = (ep->transfer_size > 0 && ep->transfer_size % ep->max_packet_size == 0);
if (!need_zlp) {
USB_DEBUG(USB_DEBUG_XFER, "EP%u IN xfer done", ep->n);
return true;
}
// Prepare to send a ZLP.
ep->transferred = 0;
ep->transfer_size = TRANSFER_ZLP;
}
// There's more data to send.
ep_in_send(ep);
return false;
}
// Send data on an IN endpoint. Call ep_in_send_done() every time DIEPINT(ep->n).xfercompl is
// asserted to check whether the data has been sent and to continue sending data if the transfer is
// only partially complete.
static void
ep_in_send_data(struct endpoint_state *ep, const void *data, uint32_t size) {
if (ep->dir_in != 1 || ep->transfer_size != ep->transferred || ep->in_flight != 0) {
BUG(0x73656e642034); // 'send 4'
}
// Reset the DMA buffer to default.
ep->xfer_dma_data = ep->default_xfer_dma_data;
ep->xfer_dma_size = ep->default_xfer_dma_size;
ep->xfer_dma_phys = ep->default_xfer_dma_phys;
// We store a pointer to the source buffer, so it must remain alive. The source buffer may
// be the xfer_dma_data buffer, in which case we're doing direct DMA.
ep->transfer_data = (uint8_t *) data;
ep->transfer_size = (size == 0 ? TRANSFER_ZLP : size);
ep->transferred = 0;
ep_in_send(ep);
}
// ---- Low-level transfer API for OUT endpoints --------------------------------------------------
// The code for EP 0 OUT is structured a bit differently from that for IN endpoints above. The
// reason for this is that while we have control of exactly what we send, we don't have control of
// exactly what we receive, so there are more edge cases we need to handle. This requires us to
// process one packet at a time in the interrupt handler, rather than firing off a request and
// being notified once it's all done. (The structure of the DOEP* registers for EP 0 also emphasize
// this: they prevent us from receiving more than 1 packet at a time.)
//
// The SecureROM does this by receiving 1 packet at a time, always into the same buffer at the same
// address, and then copying the data to the appropriate destination. That could work here, but it
// would require a different high-level API for handling control transfers, one that would send the
// supplied data to the upper layers one chunk at a time, rather than all at once when the transfer
// is complete. The flexibility of being able to send data piecemeal isn't actually a significant
// advantage for us, because if the transaction is aborted, then all that data should be discarded;
// this means that all the received data must be buffered anyway. (Perhaps in other circumstances,
// where the receiver can somehow compress the data as it is received in chunks, the other design
// might be better.)
//
// Instead, I'll receive and buffer partially completed DATA OUT stages in the DMA buffer.
// Compute the parameters for an OUT transfer.
static void
ep_out_recv_compute_xfer(struct endpoint_state *ep,
uint32_t *dma_offset_out, uint32_t *hw_xfer_size_out, uint32_t *packet_count_out) {
uint32_t dma_offset = 0;
if (ep->xfer_dma_data == ep->transfer_data) {
// In direct DMA mode, data is DMA'd directly to its destination in the DMA buffer
// (which is also the transfer_data buffer).
dma_offset = ep->transferred;
} else {
// In buffered DMA mode, data in the DMA buffer is moved into the transfer_data
// buffer as it is received in ep_out_recv_data_done(), so we always DMA into the
// start of the DMA buffer.
dma_offset = 0;
}
if (dma_offset > ep->xfer_dma_size) {
BUG(0x646d616f6666); // 'dmaoff'
}
uint32_t dma_left = ep->xfer_dma_size - dma_offset;
uint32_t xfer_size = ep->transfer_size - ep->transferred;
uint32_t packet_count = 1;
if (ep->type == 0 || ep->transfer_size == TRANSFER_ZLP) {
// If we are receiving on EP 0 OUT or if we are receiving a ZLP, then set the
// transfer size to a full packet.
xfer_size = ep->max_packet_size;
} else {
// We are receiving at least some data on EP !0 OUT. Cap the transfer size to the
// remaining space available in the DMA buffer.
if (xfer_size > dma_left) {
xfer_size = dma_left;
}
// Cap the transfer size by the width of DIEPTSIZ.xfersize. We round down
// one full packet to ensure that we don't send a partial packet and signal
// the end of the transfer.
if (xfer_size > 0x7ffff) {
xfer_size = 0x7ffff + 1 - ep->max_packet_size;
}
// TODO: Consider GHWCFG3!
// Compute the number of packets needed and round the transfer size up to a packet
// boundary.
packet_count = (xfer_size + ep->max_packet_size - 1) / ep->max_packet_size;
xfer_size = packet_count * ep->max_packet_size;
}
if (xfer_size > dma_left) {
USB_DEBUG(USB_DEBUG_FATAL, "xfer_size %u > dma_left %u", xfer_size, dma_left);
BUG(0x646d616f206264); // 'dmao bd'
}
*dma_offset_out = dma_offset;
*hw_xfer_size_out = xfer_size;
*packet_count_out = packet_count;
}
// For EP 0 OUT:
//
// Execute the SETUP or OUT DATA transaction pending on EP 0 OUT. A SETUP packet will always be
// received into the start of the buffer, so there is no need to reset buffer state after receiving
// a maximally-sized DATA OUT stage.
//
// This function should be called every time we want to actually receive any data on EP 0 OUT,
// including after a USB reset, after an interrupt on EP 0 OUT, and after completing the DATA IN
// stage of a control transfer (so that we can actually receive the STATUS OUT stage).
//
// For EP !0 OUT:
//
// Execute the OUT transfer pending on the endpoint. This function should not be called directly.
//
// The fields transfer_size, transferred, transfer_data, and in_flight should be initialized before
// calling this function.
//
// There are two DMA modes: buffered DMA and direct DMA.
//
// For buffered DMA, the DMA'd data is copied into the transfer_data buffer during
// ep_out_recv_data_done().
static void
ep_out_recv(struct endpoint_state *ep) {
if (ep->dir_in != 0) {
BUG(0x73656e642031); // 'recv 1'
}
if (ep->n == 0 && (ep0_out.xfer_dma_data != ep0_out.default_xfer_dma_data
|| ep0_out.xfer_dma_size != ep0_out.default_xfer_dma_size
|| ep0_out.xfer_dma_phys != ep0_out.default_xfer_dma_phys)) {
BUG(0x72637630206466); // 'rcv0 df'
}
if (ep->in_flight != RECV_DATA) {
// RECV_DATA must be set on non-Control endpoints.
if (ep->type != 0) {
BUG(0x726563762032); // 'recv 2'
}
// This is EP 0 OUT. When expecting a SETUP packet, set transfer_size and
// transferred to 0. transfer_size is not needed, and transferred is 0 because
// nothing precedes a SETUP packet.
ep->transfer_size = 0;
ep->transferred = 0;
}
// Compute the size of the transfer and the number of packets. The transfer size is rounded
// up to a whole number of packets. Thus, the DMA buffer size must be a multiple of the
// packet size. (Note that the DMA buffer size may not be a power of two in direct DMA
// mode.)
uint32_t dma_offset, hw_xfer_size, packet_count;
ep_out_recv_compute_xfer(ep, &dma_offset, &hw_xfer_size, &packet_count);
USB_DEBUG(USB_DEBUG_XFER, "EP%u OUT xfer %u|%u|%u", ep->n,
dma_offset, hw_xfer_size, packet_count);
// Also invalidate the cache for the DMA buffer before the DMA begins to avoid cached
// writes overwriting DMA'd data.
uint32_t cache_length = hw_xfer_size;
if (hw_xfer_size > 0) {
// In buffered DMA mode, invalidate the part of the cache we'll be receiving into.
if (ep->xfer_dma_data == ep->transfer_data) {
// In direct DMA mode, invalidate the cache for the whole buffer once at
// the start.
cache_length = ep->transfer_size;
if (cache_length == TRANSFER_ZLP) {
cache_length = ep->max_packet_size;
}
}
}
if (!cache_length) cache_length = ep->max_packet_size;
cache_invalidate(ep->xfer_dma_data + dma_offset, cache_length);
// Set the registers.
reg_write(rDOEPDMA(ep->n), ep->xfer_dma_phys + dma_offset);
reg_write(rDOEPTSIZ(ep->n), (packet_count << 19) | hw_xfer_size);
// Only cnak if we're receiving data.
reg_or(rDOEPCTL(ep->n), (ep->in_flight == RECV_DATA ? 0x84000000 : 0x80000000));
}
// When a SETUP packet is received on EP 0 OUT, call this routine to receive a pointer to it. The
// SETUP packet is still in the DMA buffer and should be copied out before being used.
//
// It is fine to call this function after calling ep_out_recv_data() to initiate a DATA OUT stage.
// Any data from an in-progress but incomplete DATA OUT stage is discarded. The endpoint is primed
// to receive a SETUP packet.
//
// This routine is not valid for other endpoints.
static struct setup_packet *
ep_out_recv_setup_done(struct endpoint_state *ep) {
if (ep->dir_in != 0 || ep->type != 0 || ep->in_flight == RECV_DATA) {
BUG(0x726563762033); // 'recv 3'
}
// We need to offset by ep->transferred in case the SETUP packet arrived after some data
// was received by ep_out_recv_data_done().
struct setup_packet *setup = (void *)(ep->xfer_dma_data + ep->transferred);
// Invalidate the cache to discard prefetches.
cache_invalidate(setup, sizeof(*setup));
// By default, expect another SETUP packet at the beginning of the buffer.
ep->transfer_size = 0;
ep->transferred = 0;
ep->in_flight = 0;
// Don't call ep_out_recv() for Control endpoints.
return setup;
}
// Common code for ep_out_recv_data() and ep_out_recv_data_dma().
static void
ep_out_recv_data_common(struct endpoint_state *ep, void *data, uint32_t size) {
// Set the transfer buffer. If data == xfer_dma_data, then we're doing direct DMA.
ep->transfer_data = data;
ep->transfer_size = (size == 0 ? TRANSFER_ZLP : size);
ep->transferred = 0;
ep->in_flight = RECV_DATA;
// Only perform the recv on EP !0 OUT. On EP 0 OUT, the call to ep_out_recv() has been
// moved to the end of the interrupt handler to ensure it is always called exactly once.
if (ep->n != 0) {
ep_out_recv(ep);
} else {
USB_DEBUG(USB_DEBUG_XFER, "EP%u OUT skip recv", ep->n);
}
}
// For EP 0 OUT:
//
// Prime EP 0 OUT to receive OUT DATA transactions as part of a DATA OUT stage of a control
// transfer, rather than the default behavior of receiving a SETUP packet. This function can only
// be called once per control transfer.
//
// ep_out_recv() still needs to be called to actually begin the transfer. Each time an OUT DATA
// transaction is successfully received on the endpoint, call ep_out_recv_data_done() to update
// state and test whether all data has been received.
//
// For EP !0 OUT:
//
// Receive data on an non-Control OUT endpoint. Call ep_out_recv_data_done() every time
// DOEPINT(ep->n).xfercompl is asserted to check whether the data has been received and to continue
// receiving data if the transfer is only partially complete.
static void
ep_out_recv_data(struct endpoint_state *ep, void *data, uint32_t size) {
if (ep->dir_in != 0 || ep->in_flight != 0 || data == NULL) {
BUG(0x73656e642034); // 'recv 4'
}
// Reset the DMA buffer to default.
ep->xfer_dma_data = ep->default_xfer_dma_data;
ep->xfer_dma_size = ep->default_xfer_dma_size;
ep->xfer_dma_phys = ep->default_xfer_dma_phys;
// Set the transfer buffer.
ep_out_recv_data_common(ep, data, size);
}
static void
ep_out_recv_data_dma(struct endpoint_state *ep, void *data, uint32_t dma, uint32_t size) {
if (ep->dir_in != 0 || ep->in_flight != 0 || data == NULL
|| size == 0 || (size % ep->max_packet_size) != 0) {
BUG(0x73656e642035); // 'recv 5'
}
ep->xfer_dma_data = data;
ep->xfer_dma_size = size;
ep->xfer_dma_phys = dma;
// Set the transfer buffer.
ep_out_recv_data_common(ep, data, size);
}
// For EP 0 OUT:
//
// Call this during an OUT DATA transaction for a control transfer once the hardware signals that a
// packet has been successfully received. This will update state and return whether the transfer is
// complete.
//
// This function does not call ep_out_recv() to retrieve more data; that should be done at the end
// of the EP 0 OUT interrupt handler.
//
// For EP !0 OUT:
//
// Call this once the hardware signals that a transfer on an OUT endpoint initiated with
// ep_out_recv_data() is complete (DOEPINT(n).xfercompl). This function will update state and
// return true if the host has finished sending us data. (ep_out_recv() is called automatically to
// resume transferring.)
static bool
ep_out_recv_data_done(struct endpoint_state *ep) {
// We expect to reach here only after ep_out_recv_data() has been called to specify that we
// expect data.
if (ep->dir_in != 0 || ep->in_flight != RECV_DATA) {
BUG(0x726563762036); // 'recv 6'
}
// Read the number of bytes left to transfer. This is different on EP 0 and EP !0.
uint32_t doeptsiz = reg_read(rDOEPTSIZ(ep->n));
uint32_t hw_xfer_left = doeptsiz & (ep->n == 0 ? 0x7f : 0x7ffff);
// Compute the original values of hw_xfer_size and packet_count given to the hardware. We
// need these in order to check whether the transfer is actually complete.
uint32_t dma_offset, hw_xfer_size, packet_count;
ep_out_recv_compute_xfer(ep, &dma_offset, &hw_xfer_size, &packet_count);
// Move the DMA'd data into the transfer_data buffer and update the amount transferred.
uint32_t data_received = hw_xfer_size - hw_xfer_left;
if (data_received > 0) {
if (ep->xfer_dma_data != ep->transfer_data) {
// In buffered mode, we always receive into the start of the DMA buffer.
if (dma_offset != 0) {
BUG(0x72637662756630); // 'rcvbuf0'
}
// We're doing buffered DMA, so we need to copy the data we just received
// out of the DMA buffer into the transfer_data buffer. Invalidate the
// cache to discard prefetches.
cache_invalidate(ep->xfer_dma_data, data_received);
memcpy(ep->transfer_data + ep->transferred, ep->xfer_dma_data,
data_received);
}
ep->transferred += data_received;
}
// If we expected a ZLP, update transfer_size to its correct value. This must be done after
// ep_out_recv_compute_xfer(), which expects TRANSFER_ZLP to be intact. It's safe to
// convert transfer_size at this point because we know this is the end of the transfer, so
// we won't hit ep_out_recv_compute_xfer() again.
if (ep->transfer_size == TRANSFER_ZLP) {
ep->transfer_size = 0;
}
// Both for the DATA OUT stage of control transfers and for OUT non-control transfers, we
// want to only return true here (signaling that the transfer is done) once we've received
// the expected amount of data or once we've received a partial packet (including a ZLP).
// In particular, if the controller stopped after receiving some data even though this
// transfer is incomplete (e.g. because we've reached the maximum packet count per transfer
// supported by the hardware), we should silently resume receiving data here rather than
// report the end of the transfer to our caller.
bool partial_packet = false;
if (ep->type == 0) {
// It's easy to test for a partial packet on EP 0 OUT because we transfer one
// packet at a time, which means that a partial packet or ZLP was transferred iff
// hw_xfer_left != 0.
partial_packet = hw_xfer_left != 0;