sam4l/usbc/
mod.rs

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.

//! SAM4L USB controller

pub mod debug;

#[allow(unused_imports)]
use self::debug::{HexBuf, UdintFlags, UeconFlags, UestaFlags};
use crate::pm;
use crate::pm::{disable_clock, enable_clock, Clock, HSBClock, PBBClock};
use crate::scif;
use core::cell::Cell;
use core::ptr;
use core::slice;
use kernel::debug as debugln;
use kernel::hil;
use kernel::hil::usb::TransferType;
use kernel::utilities::cells::{OptionalCell, VolatileCell};
use kernel::utilities::registers::interfaces::{ReadWriteable, Readable, Writeable};
use kernel::utilities::registers::{
    register_bitfields, FieldValue, InMemoryRegister, LocalRegisterCopy, ReadOnly, ReadWrite,
    WriteOnly,
};
use kernel::utilities::StaticRef;

// The following macros provide some diagnostics and panics(!)
// while this module is experimental and should eventually be removed or
// replaced with better error handling.

macro_rules! client_warn {
    [ $( $arg:expr ),+ ] => {
        debugln!($( $arg ),+)
    };
}

macro_rules! client_err {
    [ $( $arg:expr ),+ ] => {
        panic!($( $arg ),+)
    };
}

macro_rules! debug1 {
    [ $( $arg:expr ),+ ] => {
        {} // debugln!($( $arg ),+)
    };
}

macro_rules! internal_err {
    [ $( $arg:expr ),+ ] => {
        panic!($( $arg ),+)
    };
}

#[repr(C)]
struct UsbcRegisters {
    udcon: ReadWrite<u32, DeviceControl::Register>,
    udint: ReadOnly<u32, DeviceInterrupt::Register>,
    udintclr: WriteOnly<u32, DeviceInterrupt::Register>,
    udintset: WriteOnly<u32, DeviceInterrupt::Register>,
    udinte: ReadOnly<u32, DeviceInterrupt::Register>,
    udinteclr: WriteOnly<u32, DeviceInterrupt::Register>,
    udinteset: WriteOnly<u32, DeviceInterrupt::Register>,
    uerst: ReadWrite<u32>,
    udfnum: ReadOnly<u32>,
    _reserved0: [u8; 0xdc], // 220 bytes
    // Note that the SAM4L supports only 8 endpoints, but the registers
    // are laid out such that there is room for 12.
    // 0x100
    uecfg: [ReadWrite<u32, EndpointConfig::Register>; 12],
    uesta: [ReadOnly<u32, EndpointStatus::Register>; 12],
    uestaclr: [WriteOnly<u32, EndpointStatus::Register>; 12],
    uestaset: [WriteOnly<u32, EndpointStatus::Register>; 12],
    uecon: [ReadOnly<u32, EndpointControl::Register>; 12],
    ueconset: [WriteOnly<u32, EndpointControl::Register>; 12],
    ueconclr: [WriteOnly<u32, EndpointControl::Register>; 12],
    _reserved1: [u8; 0x1b0], // 432 bytes
    // 0x400 = 1024
    uhcon: ReadWrite<u32>,
    uhint: ReadOnly<u32>,
    uhintclr: WriteOnly<u32>,
    uhintset: WriteOnly<u32>,
    uhinte: ReadOnly<u32>,
    uhinteclr: WriteOnly<u32>,
    uhinteset: WriteOnly<u32>,
    uprst: ReadWrite<u32>,
    uhfnum: ReadWrite<u32>,
    uhsofc: ReadWrite<u32>,
    _reserved2: [u8; 0xd8], // 216 bytes
    // 0x500 = 1280
    upcfg: [ReadWrite<u32>; 12],
    upsta: [ReadOnly<u32>; 12],
    upstaclr: [WriteOnly<u32>; 12],
    upstaset: [WriteOnly<u32>; 12],
    upcon: [ReadOnly<u32>; 12],
    upconset: [WriteOnly<u32>; 12],
    upconclr: [WriteOnly<u32>; 12],
    upinrq: [ReadWrite<u32>; 12],
    _reserved3: [u8; 0x180], // 384 bytes
    // 0x800 = 2048
    usbcon: ReadWrite<u32, Control::Register>,
    usbsta: ReadOnly<u32, Status::Register>,
    usbstaclr: WriteOnly<u32>,
    usbstaset: WriteOnly<u32>,
    _reserved4: [u8; 8],
    // 0x818
    uvers: ReadOnly<u32>,
    ufeatures: ReadOnly<u32>,
    uaddrsize: ReadOnly<u32>,
    uname1: ReadOnly<u32>,
    uname2: ReadOnly<u32>,
    usbfsm: ReadOnly<u32>,
    udesc: ReadWrite<u32>,
}

register_bitfields![u32,
    Control [
        UIMOD OFFSET(25) NUMBITS(1) [
            HostMode = 0,
            DeviceMode = 1
        ],
        USBE OFFSET(15) NUMBITS(1) [],
        FRZCLK OFFSET(14) NUMBITS(1) []
    ],
    Status [
        SUSPEND OFFSET(16) NUMBITS(1) [],
        CLKUSABLE OFFSET(14) NUMBITS(1) [],
        SPEED OFFSET(12) NUMBITS(2) [
            SpeedFull = 0b00,
            SpeedLow = 0b10
        ],
        VBUSRQ OFFSET(9) NUMBITS(1) []
    ],
    DeviceControl [
        GNAK OFFSET(17) NUMBITS(1) [],
        LS OFFSET(12) NUMBITS(1) [
            FullSpeed = 0,
            LowSpeed = 1
        ],
        RMWKUP OFFSET(9) NUMBITS(1) [],
        DETACH OFFSET(8) NUMBITS(1) [],
        ADDEN OFFSET(7) NUMBITS(1) [],
        UADD OFFSET(0) NUMBITS(7) []
    ],
    DeviceInterrupt [
        EPINT OFFSET(12) NUMBITS(8),
        UPRSM OFFSET(6) NUMBITS(1),
        EORSM OFFSET(5) NUMBITS(1),
        WAKEUP OFFSET(4) NUMBITS(1),
        EORST OFFSET(3) NUMBITS(1),
        SOF OFFSET(2) NUMBITS(1),
        SUSP OFFSET(0) NUMBITS(1)
    ],
    EndpointConfig [
        REPNB OFFSET(16) NUMBITS(4) [
            NotRedirected = 0
        ],
        EPTYPE OFFSET(11) NUMBITS(2) [
            Control = 0,
            Isochronous = 1,
            Bulk = 2,
            Interrupt = 3
        ],
        EPDIR OFFSET(8) NUMBITS(1) [
            Out = 0,
            In = 1
        ],
        EPSIZE OFFSET(4) NUMBITS(3) [
            Bytes8 = 0,
            Bytes16 = 1,
            Bytes32 = 2,
            Bytes64 = 3,
            Bytes128 = 4,
            Bytes256 = 5,
            Bytes512 = 6,
            Bytes1024 = 7
        ],
        EPBK OFFSET(2) NUMBITS(1) [
            Single = 0,
            Double = 1
        ]
    ],
    EndpointStatus [
        CTRLDIR OFFSET(17) NUMBITS(1) [
            Out = 0,
            In = 1
        ],
        CURRBK OFFSET(14) NUMBITS(2) [
            Bank0 = 0,
            Bank1 = 1
        ],
        NBUSYBK OFFSET(12) NUMBITS(2) [],
        RAMACER OFFSET(11) NUMBITS(1) [],
        DTSEQ OFFSET(8) NUMBITS(2) [
            Data0 = 0,
            Data1 = 1
        ],
        STALLED OFFSET(6) NUMBITS(1) [],
        CRCERR OFFSET(6) NUMBITS(1) [],
        NAKIN OFFSET(4) NUMBITS(1) [],
        NAKOUT OFFSET(3) NUMBITS(1) [],
        ERRORF OFFSET(2) NUMBITS(1) [],
        RXSTP OFFSET(2) NUMBITS(1) [],
        RXOUT OFFSET(1) NUMBITS(1) [],
        TXIN OFFSET(0) NUMBITS(1) []
    ],
    EndpointControl [
        BUSY1E 25,
        BUSY0E 24,
        STALLRQ 19,
        RSTDT 18,
        FIFOCON 14,
        KILLBK 13,
        NBUSYBKE 12,
        RAMACERE 11,
        NREPLY 8,
        STALLEDE 6,
        CRCERRE 6,
        NAKINE 4,
        NAKOUTE 3,
        RXSTPE 2,
        ERRORFE 2,
        RXOUTE 1,
        TXINE 0
    ]
];

const USBC_BASE: StaticRef<UsbcRegisters> =
    unsafe { StaticRef::new(0x400A5000 as *const UsbcRegisters) };

#[inline]
fn usbc_regs() -> &'static UsbcRegisters {
    &USBC_BASE
}

// Datastructures for tracking USB controller state

pub const N_ENDPOINTS: usize = 8;

// This ensures the `descriptors` field is laid out first
#[repr(C)]
// This provides the required alignment for the `descriptors` field
#[repr(align(8))]
pub struct Usbc<'a> {
    descriptors: [Endpoint; N_ENDPOINTS],
    state: OptionalCell<State>,
    requests: [Cell<Requests>; N_ENDPOINTS],
    client: OptionalCell<&'a dyn hil::usb::Client<'a>>,
    pm: &'a pm::PowerManager,
}

#[derive(Copy, Clone, Default, Debug)]
pub struct Requests {
    pub resume_in: bool,
    pub resume_out: bool,
}

impl Requests {
    pub const fn new() -> Self {
        Requests {
            resume_in: false,
            resume_out: false,
        }
    }
}

#[derive(Copy, Clone, Debug)]
pub enum State {
    // Controller disabled
    Reset,

    // Controller enabled, detached from bus
    // (We may go to this state when the Host
    // controller suspends the bus.)
    Idle(Mode),

    // Controller enabled, attached to bus
    Active(Mode),
}

#[derive(Copy, Clone, Debug)]
pub enum Mode {
    Host,
    Device {
        speed: Speed,
        config: DeviceConfig,
        state: DeviceState,
    },
}

type EndpointConfigValue = LocalRegisterCopy<u32, EndpointConfig::Register>;
type EndpointStatusValue = LocalRegisterCopy<u32, EndpointStatus::Register>;

#[derive(Copy, Clone, Debug, Default)]
pub struct DeviceConfig {
    pub endpoint_configs: [Option<EndpointConfigValue>; N_ENDPOINTS],
}

#[derive(Copy, Clone, Debug, Default)]
pub struct DeviceState {
    pub endpoint_states: [EndpointState; N_ENDPOINTS],
}

#[derive(Copy, Clone, Debug, Default)]
pub enum EndpointState {
    #[default]
    Disabled,
    Ctrl(CtrlState),
    BulkIn(BulkInState),
    BulkOut(BulkOutState),
}

#[derive(Copy, Clone, PartialEq, Debug)]
pub enum CtrlState {
    Init,
    ReadIn,
    ReadStatus,
    WriteOut,
    WriteStatus,
    WriteStatusWait,
    InDelay,
}

#[derive(Copy, Clone, PartialEq, Debug)]
pub enum BulkInState {
    Init,
    Delay,
}

#[derive(Copy, Clone, PartialEq, Debug)]
pub enum BulkOutState {
    Init,
    Delay,
}

#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Speed {
    Full,
    Low,
}

pub enum BankIndex {
    Bank0,
    Bank1,
}

impl From<BankIndex> for usize {
    fn from(bi: BankIndex) -> usize {
        match bi {
            BankIndex::Bank0 => 0,
            BankIndex::Bank1 => 1,
        }
    }
}

pub struct EndpointIndex(u8);

impl EndpointIndex {
    pub fn new(index: usize) -> EndpointIndex {
        EndpointIndex(index as u8 & 0xf)
    }

    pub fn to_u32(self) -> u32 {
        self.0 as u32
    }
}

impl From<EndpointIndex> for usize {
    fn from(ei: EndpointIndex) -> usize {
        ei.0 as usize
    }
}

pub type Endpoint = [Bank; 2];

pub const fn new_endpoint() -> Endpoint {
    [Bank::new(), Bank::new()]
}

#[repr(C)]
pub struct Bank {
    addr: VolatileCell<*mut u8>,

    // The following fields are not actually registers
    // (they may be placed anywhere in memory),
    // but the register interface provides the volatile
    // read/writes and bitfields that we need.
    pub packet_size: InMemoryRegister<u32, PacketSize::Register>,
    pub control_status: InMemoryRegister<u32, ControlStatus::Register>,

    _reserved: u32,
}

impl Bank {
    pub const fn new() -> Bank {
        Bank {
            addr: VolatileCell::new(ptr::null_mut()),
            packet_size: InMemoryRegister::new(0),
            control_status: InMemoryRegister::new(0),
            _reserved: 0,
        }
    }

    pub fn set_addr(&self, addr: *mut u8) {
        self.addr.set(addr);
    }
}

register_bitfields![u32,
    PacketSize [
        AUTO_ZLP OFFSET(31) NUMBITS(1) [
            No = 0,
            Yes = 1
        ],
        MULTI_PACKET_SIZE OFFSET(16) NUMBITS(15) [],
        BYTE_COUNT OFFSET(0) NUMBITS(15) []
    ],
    ControlStatus [
        UNDERF 18,
        OVERF 17,
        CRCERR 16,
        STALLRQ_NEXT 0
    ]
];

impl<'a> Usbc<'a> {
    pub const fn new(pm: &'a pm::PowerManager) -> Self {
        Usbc {
            client: OptionalCell::empty(),
            state: OptionalCell::new(State::Reset),
            descriptors: [
                new_endpoint(),
                new_endpoint(),
                new_endpoint(),
                new_endpoint(),
                new_endpoint(),
                new_endpoint(),
                new_endpoint(),
                new_endpoint(),
            ],
            requests: [
                Cell::new(Requests::new()),
                Cell::new(Requests::new()),
                Cell::new(Requests::new()),
                Cell::new(Requests::new()),
                Cell::new(Requests::new()),
                Cell::new(Requests::new()),
                Cell::new(Requests::new()),
                Cell::new(Requests::new()),
            ],
            pm,
        }
    }

    fn map_state<F, R>(&self, closure: F) -> R
    where
        F: FnOnce(&mut State) -> R,
    {
        let mut state = self.state.take().unwrap(); // Unwrap fail = map_state: state value is in use
        let result = closure(&mut state);
        self.state.set(state);
        result
    }

    fn get_state(&self) -> State {
        self.state.unwrap_or_panic() // Unwrap fail = get_state: state value is in use
    }

    fn set_state(&self, state: State) {
        self.state.set(state);
    }

    /// Provide a buffer for transfers in and out of the given endpoint
    /// (The controller need not be enabled before calling this method.)
    fn endpoint_bank_set_buffer(
        &self,
        endpoint: EndpointIndex,
        bank: BankIndex,
        buf: &[VolatileCell<u8>],
    ) {
        let e: usize = From::from(endpoint);
        let b: usize = From::from(bank);
        let p = buf.as_ptr() as *mut u8;

        debug1!("Set Endpoint{}/Bank{} addr={:8?}", e, b, p);
        self.descriptors[e][b].set_addr(p);
        self.descriptors[e][b].packet_size.write(
            PacketSize::BYTE_COUNT.val(0)
                + PacketSize::MULTI_PACKET_SIZE.val(0)
                + PacketSize::AUTO_ZLP::No,
        );
    }

    /// Enable the controller's clocks and interrupt and transition to Idle state
    fn enable(&self, mode: Mode) {
        match self.get_state() {
            State::Reset => {
                // Are the USBC clocks enabled at reset?
                //   10.7.4 says no, but 17.5.3 says yes
                // Also, "Being in Idle state does not require the USB clocks to
                //   be activated" (17.6.2)
                enable_clock(Clock::HSB(HSBClock::USBC));
                enable_clock(Clock::PBB(PBBClock::USBC));

                // If we got to this state via disable() instead of chip reset,
                // the values USBCON.FRZCLK, USBCON.UIMOD, UDCON.LS have *not* been
                // reset to their default values.

                if let Mode::Device { speed, .. } = mode {
                    usbc_regs().udcon.modify(match speed {
                        Speed::Full => DeviceControl::LS::FullSpeed,
                        Speed::Low => DeviceControl::LS::LowSpeed,
                    });
                }

                // Enable in device mode
                usbc_regs().usbcon.modify(Control::UIMOD::DeviceMode);
                usbc_regs().usbcon.modify(Control::FRZCLK::CLEAR);
                usbc_regs().usbcon.modify(Control::USBE::SET);

                // Set the pointer to the endpoint descriptors
                usbc_regs()
                    .udesc
                    .set(core::ptr::addr_of!(self.descriptors) as u32);

                // Clear pending device global interrupts
                usbc_regs().udintclr.write(
                    DeviceInterrupt::SUSP::SET
                        + DeviceInterrupt::SOF::SET
                        + DeviceInterrupt::EORST::SET
                        + DeviceInterrupt::EORSM::SET
                        + DeviceInterrupt::UPRSM::SET,
                );

                // Enable device global interrupts
                // Note: SOF has been omitted as it is not presently used,
                // Note: SUSP has been omitted as SUSPEND/WAKEUP is not yet
                //   implemented.
                // Note: SOF and SUSP may nevertheless be enabled here
                //   without harm, but it makes debugging easier to omit them.
                usbc_regs().udinteset.write(
                    DeviceInterrupt::EORST::SET
                        + DeviceInterrupt::EORSM::SET
                        + DeviceInterrupt::UPRSM::SET,
                );

                debug1!("Enabled");

                self.set_state(State::Idle(mode));
            }
            _ => internal_err!("Already enabled"),
        }
    }

    /// Disable the controller, its interrupt, and its clocks
    fn _disable(&self) {
        // Detach if necessary
        if let State::Active(_) = self.get_state() {
            self.detach();
        }

        // Disable USBC and its clocks
        match self.get_state() {
            State::Idle(..) => {
                usbc_regs().usbcon.modify(Control::USBE::CLEAR);

                disable_clock(Clock::PBB(PBBClock::USBC));
                disable_clock(Clock::HSB(HSBClock::USBC));

                self.set_state(State::Reset);
            }
            _ => internal_err!("Disable called from wrong state"),
        }
    }

    /// Attach to the USB bus after enabling USB bus clock
    fn attach(&self) {
        match self.get_state() {
            State::Idle(mode) => {
                if self.pm.get_system_frequency() != 48000000 {
                    internal_err!("The system clock does not support USB");
                }

                // XX: not clear that this always results in a usable USB clock
                scif::generic_clock_enable(scif::GenericClock::GCLK7, scif::ClockSource::CLK_HSB);

                while !usbc_regs().usbsta.is_set(Status::CLKUSABLE) {}

                usbc_regs().udcon.modify(DeviceControl::DETACH::CLEAR);

                debug1!("Attached");

                self.set_state(State::Active(mode));
            }
            _ => internal_err!("Attach called in wrong state"),
        }
    }

    /// Detach from the USB bus.  Also disable USB bus clock to save energy.
    fn detach(&self) {
        match self.get_state() {
            State::Active(mode) => {
                usbc_regs().udcon.modify(DeviceControl::DETACH::SET);

                scif::generic_clock_disable(scif::GenericClock::GCLK7);

                self.set_state(State::Idle(mode));
            }
            _ => debug1!("Already detached"),
        }
    }

    /// Configure and enable an endpoint
    fn endpoint_enable(&self, endpoint: usize, endpoint_config: EndpointConfigValue) {
        self.endpoint_record_config(endpoint, endpoint_config);
        self.endpoint_write_config(endpoint, endpoint_config);

        // Enable the endpoint (meaning the controller will respond to requests
        // to this endpoint)
        usbc_regs()
            .uerst
            .set(usbc_regs().uerst.get() | (1 << endpoint));

        self.endpoint_init(endpoint, endpoint_config);

        // Set EPnINTE, enabling interrupts for this endpoint
        usbc_regs().udinteset.set(1 << (12 + endpoint));

        debug1!("Enabled endpoint {}", endpoint);
    }

    fn endpoint_record_config(&self, endpoint: usize, endpoint_config: EndpointConfigValue) {
        // Record config in case of later bus reset
        self.map_state(|state| match *state {
            State::Reset => {
                client_err!("Not enabled");
            }
            State::Idle(Mode::Device { ref mut config, .. }) => {
                // The endpoint will be active when we next attach
                config.endpoint_configs[endpoint] = Some(endpoint_config);
            }
            State::Active(Mode::Device { ref mut config, .. }) => {
                // The endpoint will be active immediately
                config.endpoint_configs[endpoint] = Some(endpoint_config);
            }
            _ => client_err!("Not in Device mode"),
        });
    }

    fn endpoint_write_config(&self, endpoint: usize, config: EndpointConfigValue) {
        // This must be performed after each bus reset

        // Configure the endpoint
        usbc_regs().uecfg[endpoint].set(From::from(config));

        debug1!("Configured endpoint {}", endpoint);
    }

    fn endpoint_init(&self, endpoint: usize, config: EndpointConfigValue) {
        self.map_state(|state| match *state {
            State::Idle(Mode::Device { ref mut state, .. }) => {
                self.endpoint_init_with_device_state(state, endpoint, config);
            }
            State::Active(Mode::Device { ref mut state, .. }) => {
                self.endpoint_init_with_device_state(state, endpoint, config);
            }
            _ => internal_err!("Not reached"),
        });
    }

    fn endpoint_init_with_device_state(
        &self,
        state: &mut DeviceState,
        endpoint: usize,
        config: EndpointConfigValue,
    ) {
        // This must be performed after each bus reset (see 17.6.2.2)

        endpoint_enable_interrupts(
            endpoint,
            EndpointControl::RAMACERE::SET + EndpointControl::STALLEDE::SET,
        );

        if config.matches_all(EndpointConfig::EPTYPE::Control) {
            endpoint_enable_interrupts(endpoint, EndpointControl::RXSTPE::SET);
            state.endpoint_states[endpoint] = EndpointState::Ctrl(CtrlState::Init);
        } else if config.matches_all(EndpointConfig::EPTYPE::Bulk + EndpointConfig::EPDIR::In) {
            endpoint_enable_interrupts(endpoint, EndpointControl::TXINE::SET);
            state.endpoint_states[endpoint] = EndpointState::BulkIn(BulkInState::Init);
        } else if config.matches_all(EndpointConfig::EPTYPE::Bulk + EndpointConfig::EPDIR::Out) {
            endpoint_enable_interrupts(endpoint, EndpointControl::RXOUTE::SET);
            state.endpoint_states[endpoint] = EndpointState::BulkOut(BulkOutState::Init);
        } else {
            // Other endpoint types unimplemented
        }

        debug1!("Initialized endpoint {}", endpoint);
    }

    fn endpoint_resume_in(&self, endpoint: usize) {
        self.map_state(|state| match *state {
            State::Active(Mode::Device { ref mut state, .. }) => {
                let endpoint_state = &mut state.endpoint_states[endpoint];
                match *endpoint_state {
                    EndpointState::BulkIn(BulkInState::Delay) => {
                        // Return to Init state
                        endpoint_enable_interrupts(endpoint, EndpointControl::TXINE::SET);
                        *endpoint_state = EndpointState::BulkIn(BulkInState::Init);
                    }
                    // XXX: Add support for EndpointState::Interrupt*
                    _ => debugln!("Ignoring superfluous resume_in"),
                }
            }
            _ => debugln!("Ignoring inappropriate resume_in"),
        });
    }

    fn endpoint_resume_out(&self, endpoint: usize) {
        self.map_state(|state| match *state {
            State::Active(Mode::Device { ref mut state, .. }) => {
                let endpoint_state = &mut state.endpoint_states[endpoint];
                match *endpoint_state {
                    EndpointState::BulkOut(BulkOutState::Delay) => {
                        // Return to Init state
                        endpoint_enable_interrupts(endpoint, EndpointControl::RXOUTE::SET);
                        *endpoint_state = EndpointState::BulkOut(BulkOutState::Init);
                    }
                    // XXX: Add support for EndpointState::Interrupt*
                    _ => debugln!("Ignoring superfluous resume_out"),
                }
            }
            _ => debugln!("Ignoring inappropriate resume_out"),
        });
    }

    fn handle_requests(&self) {
        for endpoint in 0..N_ENDPOINTS {
            let mut requests = self.requests[endpoint].get();

            if requests.resume_in {
                self.endpoint_resume_in(endpoint);
                requests.resume_in = false;
            }
            if requests.resume_out {
                self.endpoint_resume_out(endpoint);
                requests.resume_out = false;
            }

            self.requests[endpoint].set(requests);
        }
    }

    /// Handle an interrupt from the USBC
    pub fn handle_interrupt(&self) {
        self.map_state(|state| match *state {
            State::Reset => internal_err!("Received interrupt in Reset"),
            State::Idle(_) => {
                // We might process WAKEUP here
                debug1!("Received interrupt in Idle");
            }
            State::Active(ref mut mode) => match *mode {
                Mode::Device {
                    speed,
                    ref config,
                    ref mut state,
                } => self.handle_device_interrupt(speed, config, state),
                Mode::Host => internal_err!("Host mode unimplemented"),
            },
        });

        // Client callbacks invoked above may have generated state-changing requests
        self.handle_requests();
    }

    /// Handle an interrupt while in device mode
    fn handle_device_interrupt(
        &self,
        speed: Speed,
        device_config: &DeviceConfig,
        device_state: &mut DeviceState,
    ) {
        let udint = usbc_regs().udint.extract();

        debug1!("--> UDINT={:?}", UdintFlags(udint.get()));

        if udint.is_set(DeviceInterrupt::EORST) {
            // Bus reset
            debug1!("USB Bus Reset");

            // Reconfigure what has been reset in the USBC
            usbc_regs().udcon.modify(match speed {
                Speed::Full => DeviceControl::LS::FullSpeed,
                Speed::Low => DeviceControl::LS::LowSpeed,
            });

            // Reset our record of the device state
            *device_state = DeviceState::default();

            // Reconfigure and initialize endpoints
            for i in 0..N_ENDPOINTS {
                if let Some(endpoint_config) = device_config.endpoint_configs[i] {
                    self.endpoint_write_config(i, endpoint_config);
                    self.endpoint_init_with_device_state(device_state, i, endpoint_config);
                }
            }

            // Alert the client
            self.client.map(|client| {
                client.bus_reset();
            });

            // Acknowledge the interrupt
            usbc_regs().udintclr.write(DeviceInterrupt::EORST::SET);

            // Wait for the next interrupt before doing anything else
            return;
        }

        if udint.is_set(DeviceInterrupt::SUSP) {
            // The transceiver has been suspended due to the bus being idle for 3ms.
            // This condition is over when WAKEUP is set.

            // "To further reduce power consumption it is recommended to freeze the USB
            // clock by writing a one to the Freeze USB Clock (FRZCLK) bit in USBCON when
            // the USB bus is in suspend mode.
            //
            // To recover from the suspend mode, the user shall wait for the Wakeup
            // (WAKEUP) interrupt bit, which is set when a non-idle event is detected, and
            // then write a zero to FRZCLK.
            //
            // As the WAKEUP interrupt bit in UDINT is set when a non-idle event is
            // detected, it can occur regardless of whether the controller is in the
            // suspend mode or not."

            // Subscribe to WAKEUP
            usbc_regs().udinteset.write(DeviceInterrupt::WAKEUP::SET);

            // Acknowledge the "suspend" event
            usbc_regs().udintclr.write(DeviceInterrupt::SUSP::SET);
        }

        if udint.is_set(DeviceInterrupt::WAKEUP) {
            // XX: If we were suspended: Unfreeze the clock (and unsleep the MCU)

            // Unsubscribe from WAKEUP
            usbc_regs().udinteclr.write(DeviceInterrupt::WAKEUP::SET);

            // Acknowledge the interrupt
            usbc_regs().udintclr.write(DeviceInterrupt::WAKEUP::SET);

            // Continue processing, as WAKEUP is usually set
        }

        if udint.is_set(DeviceInterrupt::SOF) {
            // Acknowledge Start of frame
            usbc_regs().udintclr.write(DeviceInterrupt::SOF::SET);
        }

        if udint.is_set(DeviceInterrupt::EORSM) {
            // Controller received End of Resume
            debug1!("UDINT EORSM");
        }

        if udint.is_set(DeviceInterrupt::UPRSM) {
            // Controller sent Upstream Resume
            debug1!("UDINT UPRSM");
        }

        // Process per-endpoint interrupt flags
        for endpoint in 0..N_ENDPOINTS {
            if udint.get() & (1 << (12 + endpoint)) == 0 {
                // No interrupts for this endpoint
                continue;
            }

            self.handle_endpoint_interrupt(endpoint, &mut device_state.endpoint_states[endpoint]);
        }
    }

    fn handle_endpoint_interrupt(&self, endpoint: usize, endpoint_state: &mut EndpointState) {
        let status = usbc_regs().uesta[endpoint].extract();
        debug1!("  UESTA{}={:?}", endpoint, UestaFlags(status.get()));

        if status.is_set(EndpointStatus::STALLED) {
            debug1!("\tep{}: STALLED/CRCERR", endpoint);

            // Acknowledge
            usbc_regs().uestaclr[endpoint].write(EndpointStatus::STALLED::SET);
        }

        if status.is_set(EndpointStatus::RAMACER) {
            debug1!("\tep{}: RAMACER", endpoint);

            // Acknowledge
            usbc_regs().uestaclr[endpoint].write(EndpointStatus::RAMACER::SET);
        }

        match *endpoint_state {
            EndpointState::Ctrl(ref mut ctrl_state) => {
                self.handle_ctrl_endpoint_interrupt(endpoint, ctrl_state, status)
            }
            EndpointState::BulkIn(ref mut bulk_in_state) => {
                self.handle_bulk_in_endpoint_interrupt(endpoint, bulk_in_state, status)
            }
            EndpointState::BulkOut(ref mut bulk_out_state) => {
                self.handle_bulk_out_endpoint_interrupt(endpoint, bulk_out_state, status)
            }
            EndpointState::Disabled => {
                debug1!("Ignoring interrupt for disabled endpoint {}", endpoint);
            }
        }
    }

    fn handle_ctrl_endpoint_interrupt(
        &self,
        endpoint: usize,
        ctrl_state: &mut CtrlState,
        status: EndpointStatusValue,
    ) {
        let mut again = true;
        while again {
            again = false;
            // `again` may be set to true below when it would be
            // advantageous to process more flags without waiting for
            // another interrupt.

            debug1!(
                "  ep{}: Ctrl({:?})  UECON={:?}",
                endpoint,
                *ctrl_state,
                UeconFlags(usbc_regs().uecon[endpoint].get())
            );

            match *ctrl_state {
                CtrlState::Init => {
                    if status.is_set(EndpointStatus::RXSTP) {
                        // We received a SETUP transaction

                        debug1!("\tep{}: RXSTP", endpoint);
                        // self.debug_show_d0();

                        let bank = 0;
                        let packet_bytes = self.descriptors[endpoint][bank]
                            .packet_size
                            .read(PacketSize::BYTE_COUNT);
                        let result = if packet_bytes == 8 {
                            self.client.map(|c| c.ctrl_setup(endpoint))
                        } else {
                            Some(hil::usb::CtrlSetupResult::ErrBadLength)
                        };

                        match result {
                            Some(hil::usb::CtrlSetupResult::Ok)
                            | Some(hil::usb::CtrlSetupResult::OkSetAddress) => {
                                // Unsubscribe from SETUP interrupts
                                endpoint_disable_interrupts(endpoint, EndpointControl::RXSTPE::SET);

                                if status.matches_all(EndpointStatus::CTRLDIR::In) {
                                    // The following Data stage will be IN

                                    // Wait until bank is clear to send (TXIN).
                                    // Also wait for NAKOUT to signal end of IN
                                    // stage (the datasheet incorrectly says
                                    // NAKIN).
                                    usbc_regs().uestaclr[endpoint]
                                        .write(EndpointStatus::NAKOUT::SET);
                                    endpoint_enable_interrupts(
                                        endpoint,
                                        EndpointControl::TXINE::SET + EndpointControl::NAKOUTE::SET,
                                    );
                                    *ctrl_state = CtrlState::ReadIn;
                                } else {
                                    // The following Data stage will be OUT

                                    // Wait for OUT packets (RXOUT).  Also wait
                                    // for NAKIN to signal end of OUT stage.
                                    usbc_regs().uestaclr[endpoint]
                                        .write(EndpointStatus::NAKIN::SET);
                                    endpoint_enable_interrupts(
                                        endpoint,
                                        EndpointControl::RXOUTE::SET + EndpointControl::NAKINE::SET,
                                    );
                                    *ctrl_state = CtrlState::WriteOut;
                                }
                            }
                            failure => {
                                // Respond with STALL to any following
                                // transactions in this request
                                usbc_regs().ueconset[endpoint].write(EndpointControl::STALLRQ::SET);

                                match failure {
                                    None => debug1!("\tep{}: No client to handle Setup", endpoint),
                                    Some(_err) => {
                                        debug1!("\tep{}: Client err on Setup: {:?}", endpoint, _err)
                                    }
                                }

                                // Remain in Init state for next SETUP
                            }
                        }

                        // Acknowledge SETUP interrupt
                        usbc_regs().uestaclr[endpoint].write(EndpointStatus::RXSTP::SET);
                    }
                }
                CtrlState::ReadIn => {
                    // TODO: Handle Abort as described in 17.6.2.15
                    // (for Control and Isochronous only)

                    if status.is_set(EndpointStatus::NAKOUT) {
                        // The host has completed the IN stage by sending an OUT token

                        endpoint_disable_interrupts(
                            endpoint,
                            EndpointControl::TXINE::SET + EndpointControl::NAKOUTE::SET,
                        );

                        debug1!("\tep{}: NAKOUT", endpoint);
                        self.client.map(|c| c.ctrl_status(endpoint));

                        // Await end of Status stage
                        endpoint_enable_interrupts(endpoint, EndpointControl::RXOUTE::SET);

                        // Acknowledge
                        usbc_regs().uestaclr[endpoint].write(EndpointStatus::NAKOUT::SET);

                        *ctrl_state = CtrlState::ReadStatus;

                        // Run handler again in case the RXOUT has already arrived
                        again = true;
                    } else if status.is_set(EndpointStatus::TXIN) {
                        // The data bank is ready to receive another IN payload
                        debug1!("\tep{}: TXIN", endpoint);

                        let result = self.client.map(|c| {
                            // Allow client to write a packet payload to buffer
                            c.ctrl_in(endpoint)
                        });
                        match result {
                            Some(hil::usb::CtrlInResult::Packet(
                                packet_bytes,
                                transfer_complete,
                            )) => {
                                // Check if the entire buffer is full, and
                                // handle that case slightly differently. Note,
                                // this depends on the length of the buffer
                                // used. Right now, that is 64 bytes.
                                let packet_size = if packet_bytes == 64 && transfer_complete {
                                    // Send a complete final packet, and request
                                    // that the controller also send a zero-length
                                    // packet to signal the end of transfer
                                    PacketSize::BYTE_COUNT.val(64) + PacketSize::AUTO_ZLP::Yes
                                } else {
                                    // Send either a complete but not-final
                                    // packet, or a short and final packet (which
                                    // itself signals end of transfer)
                                    PacketSize::BYTE_COUNT.val(packet_bytes as u32)
                                };
                                let bank = 0;
                                self.descriptors[endpoint][bank]
                                    .packet_size
                                    .write(packet_size);

                                debug1!(
                                    "\tep{}: Send CTRL IN packet ({} bytes)",
                                    endpoint,
                                    packet_bytes
                                );
                                // self.debug_show_d0();

                                if transfer_complete {
                                    // IN data completely sent.  Unsubscribe from TXIN.
                                    // (Continue awaiting NAKOUT to indicate end of Data stage)
                                    endpoint_disable_interrupts(
                                        endpoint,
                                        EndpointControl::TXINE::SET,
                                    );
                                } else {
                                    // Continue waiting for next TXIN
                                }

                                // Clear TXIN to signal to the controller that the IN payload is
                                // ready to send
                                usbc_regs().uestaclr[endpoint].write(EndpointStatus::TXIN::SET);
                            }
                            Some(hil::usb::CtrlInResult::Delay) => {
                                endpoint_disable_interrupts(endpoint, EndpointControl::TXINE::SET);

                                debug1!("*** Client NAK");

                                // XXX set busy bits?

                                *ctrl_state = CtrlState::InDelay;
                            }
                            _ => {
                                // Respond with STALL to any following IN/OUT transactions
                                usbc_regs().ueconset[endpoint].write(EndpointControl::STALLRQ::SET);

                                debug1!("\tep{}: Client IN err => STALL", endpoint);

                                // Wait for next SETUP
                                endpoint_disable_interrupts(
                                    endpoint,
                                    EndpointControl::NAKOUTE::SET,
                                );
                                endpoint_enable_interrupts(endpoint, EndpointControl::RXSTPE::SET);
                                *ctrl_state = CtrlState::Init;
                            }
                        }
                    }
                }
                CtrlState::ReadStatus => {
                    if status.is_set(EndpointStatus::RXOUT) {
                        // Host has completed Status stage by sending an OUT packet

                        debug1!("\tep{}: RXOUT: End of Control Read transaction", endpoint);

                        // Wait for next SETUP
                        endpoint_disable_interrupts(endpoint, EndpointControl::RXOUTE::SET);
                        endpoint_enable_interrupts(endpoint, EndpointControl::RXSTPE::SET);
                        *ctrl_state = CtrlState::Init;

                        // Acknowledge
                        usbc_regs().uestaclr[endpoint].write(EndpointStatus::RXOUT::SET);

                        self.client.map(|c| c.ctrl_status_complete(endpoint));
                    }
                }
                CtrlState::WriteOut => {
                    if status.is_set(EndpointStatus::RXOUT) {
                        // Received data

                        debug1!("\tep{}: RXOUT: Received Control Write data", endpoint);
                        // self.debug_show_d0();

                        // Pass the data to the client and see how it reacts
                        let bank = 0;
                        let result = self.client.map(|c| {
                            c.ctrl_out(
                                endpoint,
                                self.descriptors[endpoint][bank]
                                    .packet_size
                                    .read(PacketSize::BYTE_COUNT),
                            )
                        });
                        match result {
                            Some(hil::usb::CtrlOutResult::Ok) => {
                                // Acknowledge
                                usbc_regs().uestaclr[endpoint].write(EndpointStatus::RXOUT::SET);
                            }
                            Some(hil::usb::CtrlOutResult::Delay) => {
                                // Don't acknowledge; hardware will have to send NAK

                                // Unsubscribe from RXOUT until client says it is ready
                                // (But there is not yet any interface for that)
                                endpoint_disable_interrupts(endpoint, EndpointControl::RXOUTE::SET);
                            }
                            _ => {
                                // Respond with STALL to any following transactions
                                // in this request
                                usbc_regs().ueconset[endpoint].write(EndpointControl::STALLRQ::SET);

                                debug1!("\tep{}: Client OUT err => STALL", endpoint);

                                // Wait for next SETUP
                                endpoint_disable_interrupts(
                                    endpoint,
                                    EndpointControl::RXOUTE::SET + EndpointControl::NAKINE::SET,
                                );
                                endpoint_enable_interrupts(endpoint, EndpointControl::RXSTPE::SET);
                                *ctrl_state = CtrlState::Init;
                            }
                        }
                    }
                    if status.is_set(EndpointStatus::NAKIN) {
                        // The host has completed the Data stage by sending an IN token
                        debug1!("\tep{}: NAKIN: Control Write -> Status stage", endpoint);

                        // Acknowledge
                        usbc_regs().uestaclr[endpoint].write(EndpointStatus::NAKIN::SET);

                        // Wait for bank to be free so we can write ZLP to acknowledge transfer
                        endpoint_disable_interrupts(
                            endpoint,
                            EndpointControl::RXOUTE::SET + EndpointControl::NAKINE::SET,
                        );
                        endpoint_enable_interrupts(endpoint, EndpointControl::TXINE::SET);
                        *ctrl_state = CtrlState::WriteStatus;

                        // Can probably send the ZLP immediately
                        again = true;
                    }
                }
                CtrlState::WriteStatus => {
                    if status.is_set(EndpointStatus::TXIN) {
                        debug1!(
                            "\tep{}: TXIN for Control Write Status (will send ZLP)",
                            endpoint
                        );

                        self.client.map(|c| c.ctrl_status(endpoint));

                        // Send zero-length packet to acknowledge transaction
                        let bank = 0;
                        self.descriptors[endpoint][bank]
                            .packet_size
                            .write(PacketSize::BYTE_COUNT.val(0));

                        // Signal to the controller that the IN payload is ready to send
                        usbc_regs().uestaclr[endpoint].write(EndpointStatus::TXIN::SET);

                        // Wait for TXIN again to confirm that IN payload has been sent
                        *ctrl_state = CtrlState::WriteStatusWait;
                    }
                }
                CtrlState::WriteStatusWait => {
                    if status.is_set(EndpointStatus::TXIN) {
                        debug1!("\tep{}: TXIN: Control Write Status Complete", endpoint);

                        // Wait for next SETUP
                        endpoint_disable_interrupts(endpoint, EndpointControl::TXINE::SET);
                        endpoint_enable_interrupts(endpoint, EndpointControl::RXSTPE::SET);
                        *ctrl_state = CtrlState::Init;

                        // for SetAddress, client must enable address after STATUS stage
                        self.client.map(|c| c.ctrl_status_complete(endpoint));
                    }
                }
                CtrlState::InDelay => internal_err!("Not reached"),
            }

            // Uncomment the following line to run the above while loop only once per interrupt,
            // which can make debugging easier.
            //
            // again = false;
        }
    }

    fn handle_bulk_out_endpoint_interrupt(
        &self,
        endpoint: usize,
        bulk_out_state: &mut BulkOutState,
        status: EndpointStatusValue,
    ) {
        match *bulk_out_state {
            BulkOutState::Init => {
                if status.is_set(EndpointStatus::RXOUT) {
                    // We got an OUT request from the host

                    debug1!("\tep{}: RXOUT", endpoint);

                    if !usbc_regs().uecon[endpoint].is_set(EndpointControl::FIFOCON) {
                        debugln!("Got RXOUT but not FIFOCON");
                        return;
                    }
                    // A bank is full of an OUT packet

                    let bank = 0;
                    let packet_bytes = self.descriptors[endpoint][bank]
                        .packet_size
                        .read(PacketSize::BYTE_COUNT);

                    let result = self.client.map(|c| {
                        // Allow client to consume the packet
                        c.packet_out(TransferType::Bulk, endpoint, packet_bytes)
                    });
                    match result {
                        Some(hil::usb::OutResult::Ok) => {
                            // Acknowledge
                            usbc_regs().uestaclr[endpoint].write(EndpointStatus::RXOUT::SET);

                            // Clear FIFOCON to signal that the packet was consumed
                            usbc_regs().ueconclr[endpoint].write(EndpointControl::FIFOCON::SET);

                            debug1!(
                                "\tep{}: Recv BULK OUT packet ({} bytes)",
                                endpoint,
                                packet_bytes
                            );

                            // Remain in Init state
                        }
                        Some(hil::usb::OutResult::Delay) => {
                            // The client is not ready to consume data; wait for resume

                            endpoint_disable_interrupts(endpoint, EndpointControl::RXOUTE::SET);

                            *bulk_out_state = BulkOutState::Delay;
                        }
                        _ => {
                            debug1!("\tep{}: Client OUT err => STALL", endpoint);

                            // Respond with STALL to any following IN/OUT transactions
                            usbc_regs().ueconset[endpoint].write(EndpointControl::STALLRQ::SET);

                            // XXX: interrupts?

                            // Remain in Init state?
                        }
                    }
                }
            }
            BulkOutState::Delay => internal_err!("Not reached"),
        }
    }

    fn handle_bulk_in_endpoint_interrupt(
        &self,
        endpoint: usize,
        bulk_in_state: &mut BulkInState,
        status: EndpointStatusValue,
    ) {
        match *bulk_in_state {
            BulkInState::Init => {
                if status.is_set(EndpointStatus::TXIN) {
                    // We got an IN request from the host

                    debug1!("\tep{}: TXIN", endpoint);

                    if !usbc_regs().uecon[endpoint].is_set(EndpointControl::FIFOCON) {
                        debugln!("Got TXIN but not FIFOCON");
                        return;
                    }
                    // A bank is free to write an IN packet

                    let result = self.client.map(|c| {
                        // Allow client to write a packet payload to the buffer
                        c.packet_in(TransferType::Bulk, endpoint)
                    });
                    match result {
                        Some(hil::usb::InResult::Packet(packet_bytes)) => {
                            // Acknowledge
                            usbc_regs().uestaclr[endpoint].write(EndpointStatus::TXIN::SET);

                            // Tell the controller the size of the packet
                            let bank = 0;
                            self.descriptors[endpoint][bank]
                                .packet_size
                                .write(PacketSize::BYTE_COUNT.val(packet_bytes as u32));

                            // Clear FIFOCON to signal data ready to send
                            usbc_regs().ueconclr[endpoint].write(EndpointControl::FIFOCON::SET);

                            debug1!(
                                "\tep{}: Send BULK IN packet ({} bytes)",
                                endpoint,
                                packet_bytes
                            );

                            // Remain in Init state
                        }
                        Some(hil::usb::InResult::Delay) => {
                            // The client is not ready to send data; wait for resume

                            endpoint_disable_interrupts(endpoint, EndpointControl::TXINE::SET);

                            *bulk_in_state = BulkInState::Delay;
                        }
                        _ => {
                            debug1!("\tep{}: Client IN err => STALL", endpoint);

                            // Respond with STALL to any following IN/OUT transactions
                            usbc_regs().ueconset[endpoint].write(EndpointControl::STALLRQ::SET);

                            // XXX: interrupts?

                            // Remain in Init state?
                        }
                    }
                }
            }
            BulkInState::Delay => {
                // Endpoint interrupts should be handled already or disabled
                internal_err!("Not reached");
            }
        }
    }

    #[allow(dead_code)]
    fn debug_show_d0(&self) {
        for bi in 0..1 {
            let b = &self.descriptors[0][bi];
            let addr = b.addr.get();
            let _buf = if addr.is_null() {
                None
            } else {
                unsafe {
                    Some(slice::from_raw_parts(
                        addr,
                        b.packet_size.read(PacketSize::BYTE_COUNT) as usize,
                    ))
                }
            };

            debug1!(
                "B_0_{} \
                 \n     {:?}\
                 \n     {:?}\
                 \n     {:?}",
                bi, // core::ptr::addr_of!(b.addr), b.addr.get(),
                b.packet_size.get(),
                b.control_status.get(),
                _buf.map(HexBuf)
            );
        }
    }

    pub fn mode(&self) -> Option<Mode> {
        match self.get_state() {
            State::Idle(mode) => Some(mode),
            State::Active(mode) => Some(mode),
            _ => None,
        }
    }

    pub fn speed(&self) -> Option<Speed> {
        match self.mode() {
            Some(mode) => {
                match mode {
                    Mode::Device { speed, .. } => Some(speed),
                    Mode::Host => {
                        None // XX USBSTA.SPEED
                    }
                }
            }
            _ => None,
        }
    }

    // TODO: Remote wakeup (Device -> Host, after receiving DEVICE_REMOTE_WAKEUP)
}

#[inline]
fn endpoint_disable_interrupts(endpoint: usize, mask: FieldValue<u32, EndpointControl::Register>) {
    usbc_regs().ueconclr[endpoint].write(mask);
}

#[inline]
fn endpoint_enable_interrupts(endpoint: usize, mask: FieldValue<u32, EndpointControl::Register>) {
    usbc_regs().ueconset[endpoint].write(mask);
}

impl<'a> hil::usb::UsbController<'a> for Usbc<'a> {
    fn set_client(&self, client: &'a dyn hil::usb::Client<'a>) {
        self.client.set(client);
    }

    fn endpoint_set_ctrl_buffer(&self, buf: &'a [VolatileCell<u8>]) {
        if buf.len() < 8 {
            client_err!("Bad endpoint buffer size");
        }

        self.endpoint_bank_set_buffer(EndpointIndex::new(0), BankIndex::Bank0, buf);
    }

    fn endpoint_set_in_buffer(&self, endpoint: usize, buf: &'a [VolatileCell<u8>]) {
        if buf.len() < 8 {
            client_err!("Bad endpoint buffer size");
        }

        self.endpoint_bank_set_buffer(EndpointIndex::new(endpoint), BankIndex::Bank0, buf);
    }

    fn endpoint_set_out_buffer(&self, endpoint: usize, buf: &'a [VolatileCell<u8>]) {
        if buf.len() < 8 {
            client_err!("Bad endpoint buffer size");
        }

        // XXX: when implementing in_out endpoints, this should probably set a different slice than endpoint_set_in_buffer.
        self.endpoint_bank_set_buffer(EndpointIndex::new(endpoint), BankIndex::Bank0, buf);
    }

    fn enable_as_device(&self, speed: hil::usb::DeviceSpeed) {
        let speed = match speed {
            hil::usb::DeviceSpeed::Full => Speed::Full,
            hil::usb::DeviceSpeed::Low => Speed::Low,
        };

        match self.get_state() {
            State::Reset => self.enable(Mode::Device {
                speed,
                config: DeviceConfig::default(),
                state: DeviceState::default(),
            }),
            _ => client_err!("Already enabled"),
        }
    }

    fn attach(&self) {
        match self.get_state() {
            State::Reset => client_warn!("Not enabled"),
            State::Active(_) => client_warn!("Already attached"),
            State::Idle(_) => self.attach(),
        }
    }

    fn detach(&self) {
        match self.get_state() {
            State::Reset => client_warn!("Not enabled"),
            State::Idle(_) => client_warn!("Not attached"),
            State::Active(_) => self.detach(),
        }
    }

    fn set_address(&self, addr: u16) {
        usbc_regs()
            .udcon
            .modify(DeviceControl::UADD.val(addr as u32));

        debug1!("Set Address = {}", addr);
    }

    fn enable_address(&self) {
        usbc_regs().udcon.modify(DeviceControl::ADDEN::SET);

        debug1!(
            "Enable Address = {}",
            usbc_regs().udcon.read(DeviceControl::UADD)
        );
    }

    fn endpoint_in_enable(&self, transfer_type: TransferType, endpoint: usize) {
        let endpoint_cfg = match transfer_type {
            TransferType::Control => {
                panic!("There is no IN control endpoint");
            }
            TransferType::Bulk => LocalRegisterCopy::new(From::from(
                EndpointConfig::EPTYPE::Bulk
                    + EndpointConfig::EPDIR::In
                    + EndpointConfig::EPSIZE::Bytes8
                    + EndpointConfig::EPBK::Single,
            )),
            TransferType::Interrupt | TransferType::Isochronous => unimplemented!(),
        };

        self.endpoint_enable(endpoint, endpoint_cfg)
    }

    fn endpoint_out_enable(&self, transfer_type: TransferType, endpoint: usize) {
        let endpoint_cfg = match transfer_type {
            TransferType::Control => LocalRegisterCopy::new(From::from(
                EndpointConfig::EPTYPE::Control
                    + EndpointConfig::EPDIR::Out
                    + EndpointConfig::EPSIZE::Bytes8
                    + EndpointConfig::EPBK::Single,
            )),
            TransferType::Bulk => LocalRegisterCopy::new(From::from(
                EndpointConfig::EPTYPE::Bulk
                    + EndpointConfig::EPDIR::Out
                    + EndpointConfig::EPSIZE::Bytes8
                    + EndpointConfig::EPBK::Single,
            )),
            TransferType::Interrupt | TransferType::Isochronous => unimplemented!(),
        };

        self.endpoint_enable(endpoint, endpoint_cfg)
    }

    fn endpoint_in_out_enable(&self, _transfer_type: TransferType, _endpoint: usize) {
        unimplemented!()
    }

    fn endpoint_resume_in(&self, endpoint: usize) {
        let mut requests = self.requests[endpoint].get();
        requests.resume_in = true;
        self.requests[endpoint].set(requests);

        // Immediately handle the request to resume the endpoint.
        self.handle_requests();
    }

    fn endpoint_resume_out(&self, endpoint: usize) {
        let mut requests = self.requests[endpoint].get();
        requests.resume_out = true;
        self.requests[endpoint].set(requests);

        // Immediately handle the request to resume the endpoint.
        self.handle_requests();
    }
}