-
Notifications
You must be signed in to change notification settings - Fork 654
/
lib.rs
1336 lines (1143 loc) · 43.7 KB
/
lib.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
#![cfg_attr(not(test), no_std)]
#![allow(async_fn_in_trait)]
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
// This must go FIRST so that all the other modules see its macros.
mod fmt;
use core::cell::UnsafeCell;
use core::future::poll_fn;
use core::marker::PhantomData;
use core::sync::atomic::{AtomicBool, AtomicU16, Ordering};
use core::task::Poll;
use embassy_sync::waitqueue::AtomicWaker;
use embassy_usb_driver::{
Bus as _, Direction, EndpointAddress, EndpointAllocError, EndpointError, EndpointIn, EndpointInfo, EndpointOut,
EndpointType, Event, Unsupported,
};
pub mod otg_v1;
use otg_v1::{regs, vals, Otg};
/// Handle interrupts.
pub unsafe fn on_interrupt<const MAX_EP_COUNT: usize>(
r: Otg,
state: &State<MAX_EP_COUNT>,
ep_count: usize,
quirk_setup_late_cnak: bool,
) {
let ints = r.gintsts().read();
if ints.wkupint() || ints.usbsusp() || ints.usbrst() || ints.enumdne() || ints.otgint() || ints.srqint() {
// Mask interrupts and notify `Bus` to process them
r.gintmsk().write(|_| {});
state.bus_waker.wake();
}
// Handle RX
while r.gintsts().read().rxflvl() {
let status = r.grxstsp().read();
trace!("=== status {:08x}", status.0);
let ep_num = status.epnum() as usize;
let len = status.bcnt() as usize;
assert!(ep_num < ep_count);
match status.pktstsd() {
vals::Pktstsd::SETUP_DATA_RX => {
trace!("SETUP_DATA_RX");
assert!(len == 8, "invalid SETUP packet length={}", len);
assert!(ep_num == 0, "invalid SETUP packet endpoint={}", ep_num);
// flushing TX if something stuck in control endpoint
if r.dieptsiz(ep_num).read().pktcnt() != 0 {
r.grstctl().modify(|w| {
w.set_txfnum(ep_num as _);
w.set_txfflsh(true);
});
while r.grstctl().read().txfflsh() {}
}
if state.cp_state.setup_ready.load(Ordering::Relaxed) == false {
// SAFETY: exclusive access ensured by atomic bool
let data = unsafe { &mut *state.cp_state.setup_data.get() };
data[0..4].copy_from_slice(&r.fifo(0).read().0.to_ne_bytes());
data[4..8].copy_from_slice(&r.fifo(0).read().0.to_ne_bytes());
state.cp_state.setup_ready.store(true, Ordering::Release);
state.ep_states[0].out_waker.wake();
} else {
error!("received SETUP before previous finished processing");
// discard FIFO
r.fifo(0).read();
r.fifo(0).read();
}
}
vals::Pktstsd::OUT_DATA_RX => {
trace!("OUT_DATA_RX ep={} len={}", ep_num, len);
if state.ep_states[ep_num].out_size.load(Ordering::Acquire) == EP_OUT_BUFFER_EMPTY {
// SAFETY: Buffer size is allocated to be equal to endpoint's maximum packet size
// We trust the peripheral to not exceed its configured MPSIZ
let buf =
unsafe { core::slice::from_raw_parts_mut(*state.ep_states[ep_num].out_buffer.get(), len) };
for chunk in buf.chunks_mut(4) {
// RX FIFO is shared so always read from fifo(0)
let data = r.fifo(0).read().0;
chunk.copy_from_slice(&data.to_ne_bytes()[0..chunk.len()]);
}
state.ep_states[ep_num].out_size.store(len as u16, Ordering::Release);
state.ep_states[ep_num].out_waker.wake();
} else {
error!("ep_out buffer overflow index={}", ep_num);
// discard FIFO data
let len_words = (len + 3) / 4;
for _ in 0..len_words {
r.fifo(0).read().data();
}
}
}
vals::Pktstsd::OUT_DATA_DONE => {
trace!("OUT_DATA_DONE ep={}", ep_num);
}
vals::Pktstsd::SETUP_DATA_DONE => {
trace!("SETUP_DATA_DONE ep={}", ep_num);
if quirk_setup_late_cnak {
// Clear NAK to indicate we are ready to receive more data
r.doepctl(ep_num).modify(|w| w.set_cnak(true));
}
}
x => trace!("unknown PKTSTS: {}", x.to_bits()),
}
}
// IN endpoint interrupt
if ints.iepint() {
let mut ep_mask = r.daint().read().iepint();
let mut ep_num = 0;
// Iterate over endpoints while there are non-zero bits in the mask
while ep_mask != 0 {
if ep_mask & 1 != 0 {
let ep_ints = r.diepint(ep_num).read();
// clear all
r.diepint(ep_num).write_value(ep_ints);
// TXFE is cleared in DIEPEMPMSK
if ep_ints.txfe() {
critical_section::with(|_| {
r.diepempmsk().modify(|w| {
w.set_ineptxfem(w.ineptxfem() & !(1 << ep_num));
});
});
}
state.ep_states[ep_num].in_waker.wake();
trace!("in ep={} irq val={:08x}", ep_num, ep_ints.0);
}
ep_mask >>= 1;
ep_num += 1;
}
}
// not needed? reception handled in rxflvl
// OUT endpoint interrupt
// if ints.oepint() {
// let mut ep_mask = r.daint().read().oepint();
// let mut ep_num = 0;
// while ep_mask != 0 {
// if ep_mask & 1 != 0 {
// let ep_ints = r.doepint(ep_num).read();
// // clear all
// r.doepint(ep_num).write_value(ep_ints);
// state.ep_out_wakers[ep_num].wake();
// trace!("out ep={} irq val={:08x}", ep_num, ep_ints.0);
// }
// ep_mask >>= 1;
// ep_num += 1;
// }
// }
}
/// USB PHY type
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum PhyType {
/// Internal Full-Speed PHY
///
/// Available on most High-Speed peripherals.
InternalFullSpeed,
/// Internal High-Speed PHY
///
/// Available on a few STM32 chips.
InternalHighSpeed,
/// External ULPI High-Speed PHY
ExternalHighSpeed,
}
impl PhyType {
/// Get whether this PHY is any of the internal types.
pub fn internal(&self) -> bool {
match self {
PhyType::InternalFullSpeed | PhyType::InternalHighSpeed => true,
PhyType::ExternalHighSpeed => false,
}
}
/// Get whether this PHY is any of the high-speed types.
pub fn high_speed(&self) -> bool {
match self {
PhyType::InternalFullSpeed => false,
PhyType::ExternalHighSpeed | PhyType::InternalHighSpeed => true,
}
}
fn to_dspd(&self) -> vals::Dspd {
match self {
PhyType::InternalFullSpeed => vals::Dspd::FULL_SPEED_INTERNAL,
PhyType::InternalHighSpeed => vals::Dspd::HIGH_SPEED,
PhyType::ExternalHighSpeed => vals::Dspd::HIGH_SPEED,
}
}
}
/// Indicates that [State::ep_out_buffers] is empty.
const EP_OUT_BUFFER_EMPTY: u16 = u16::MAX;
struct EpState {
in_waker: AtomicWaker,
out_waker: AtomicWaker,
/// RX FIFO is shared so extra buffers are needed to dequeue all data without waiting on each endpoint.
/// Buffers are ready when associated [State::ep_out_size] != [EP_OUT_BUFFER_EMPTY].
out_buffer: UnsafeCell<*mut u8>,
out_size: AtomicU16,
}
// SAFETY: The EndpointAllocator ensures that the buffer points to valid memory exclusive for each endpoint and is
// large enough to hold the maximum packet size. Access to the buffer is synchronized between the USB interrupt and the
// EndpointOut impl using the out_size atomic variable.
unsafe impl Send for EpState {}
unsafe impl Sync for EpState {}
struct ControlPipeSetupState {
/// Holds received SETUP packets. Available if [Ep0State::setup_ready] is true.
setup_data: UnsafeCell<[u8; 8]>,
setup_ready: AtomicBool,
}
/// USB OTG driver state.
pub struct State<const EP_COUNT: usize> {
cp_state: ControlPipeSetupState,
ep_states: [EpState; EP_COUNT],
bus_waker: AtomicWaker,
}
unsafe impl<const EP_COUNT: usize> Send for State<EP_COUNT> {}
unsafe impl<const EP_COUNT: usize> Sync for State<EP_COUNT> {}
impl<const EP_COUNT: usize> State<EP_COUNT> {
/// Create a new State.
pub const fn new() -> Self {
const NEW_AW: AtomicWaker = AtomicWaker::new();
const NEW_BUF: UnsafeCell<*mut u8> = UnsafeCell::new(0 as _);
const NEW_SIZE: AtomicU16 = AtomicU16::new(EP_OUT_BUFFER_EMPTY);
const NEW_EP_STATE: EpState = EpState {
in_waker: NEW_AW,
out_waker: NEW_AW,
out_buffer: NEW_BUF,
out_size: NEW_SIZE,
};
Self {
cp_state: ControlPipeSetupState {
setup_data: UnsafeCell::new([0u8; 8]),
setup_ready: AtomicBool::new(false),
},
ep_states: [NEW_EP_STATE; EP_COUNT],
bus_waker: NEW_AW,
}
}
}
#[derive(Debug, Clone, Copy)]
struct EndpointData {
ep_type: EndpointType,
max_packet_size: u16,
fifo_size_words: u16,
}
/// USB driver config.
#[non_exhaustive]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Config {
/// Enable VBUS detection.
///
/// The USB spec requires USB devices monitor for USB cable plug/unplug and react accordingly.
/// This is done by checking whether there is 5V on the VBUS pin or not.
///
/// If your device is bus-powered (powers itself from the USB host via VBUS), then this is optional.
/// (If there's no power in VBUS your device would be off anyway, so it's fine to always assume
/// there's power in VBUS, i.e. the USB cable is always plugged in.)
///
/// If your device is self-powered (i.e. it gets power from a source other than the USB cable, and
/// therefore can stay powered through USB cable plug/unplug) then you MUST set this to true.
///
/// If you set this to true, you must connect VBUS to PA9 for FS, PB13 for HS, possibly with a
/// voltage divider. See ST application note AN4879 and the reference manual for more details.
pub vbus_detection: bool,
/// Enable transceiver delay.
///
/// Some ULPI PHYs like the Microchip USB334x series require a delay between the ULPI register write that initiates
/// the HS Chirp and the subsequent transmit command, otherwise the HS Chirp does not get executed and the deivce
/// enumerates in FS mode. Some USB Link IP like those in the STM32H7 series support adding this delay to work with
/// the affected PHYs.
pub xcvrdly: bool,
}
impl Default for Config {
fn default() -> Self {
Self {
vbus_detection: false,
xcvrdly: false,
}
}
}
/// USB OTG driver.
pub struct Driver<'d, const MAX_EP_COUNT: usize> {
config: Config,
ep_in: [Option<EndpointData>; MAX_EP_COUNT],
ep_out: [Option<EndpointData>; MAX_EP_COUNT],
ep_out_buffer: &'d mut [u8],
ep_out_buffer_offset: usize,
instance: OtgInstance<'d, MAX_EP_COUNT>,
}
impl<'d, const MAX_EP_COUNT: usize> Driver<'d, MAX_EP_COUNT> {
/// Initializes the USB OTG peripheral.
///
/// # Arguments
///
/// * `ep_out_buffer` - An internal buffer used to temporarily store received packets.
/// Must be large enough to fit all OUT endpoint max packet sizes.
/// Endpoint allocation will fail if it is too small.
/// * `instance` - The USB OTG peripheral instance and its configuration.
/// * `config` - The USB driver configuration.
pub fn new(ep_out_buffer: &'d mut [u8], instance: OtgInstance<'d, MAX_EP_COUNT>, config: Config) -> Self {
Self {
config,
ep_in: [None; MAX_EP_COUNT],
ep_out: [None; MAX_EP_COUNT],
ep_out_buffer,
ep_out_buffer_offset: 0,
instance,
}
}
/// Returns the total amount of words (u32) allocated in dedicated FIFO.
fn allocated_fifo_words(&self) -> u16 {
self.instance.extra_rx_fifo_words + ep_fifo_size(&self.ep_out) + ep_fifo_size(&self.ep_in)
}
/// Creates an [`Endpoint`] with the given parameters.
fn alloc_endpoint<D: Dir>(
&mut self,
ep_type: EndpointType,
max_packet_size: u16,
interval_ms: u8,
) -> Result<Endpoint<'d, D>, EndpointAllocError> {
trace!(
"allocating type={:?} mps={:?} interval_ms={}, dir={:?}",
ep_type,
max_packet_size,
interval_ms,
D::dir()
);
if D::dir() == Direction::Out {
if self.ep_out_buffer_offset + max_packet_size as usize >= self.ep_out_buffer.len() {
error!("Not enough endpoint out buffer capacity");
return Err(EndpointAllocError);
}
};
let fifo_size_words = match D::dir() {
Direction::Out => (max_packet_size + 3) / 4,
// INEPTXFD requires minimum size of 16 words
Direction::In => u16::max((max_packet_size + 3) / 4, 16),
};
if fifo_size_words + self.allocated_fifo_words() > self.instance.fifo_depth_words {
error!("Not enough FIFO capacity");
return Err(EndpointAllocError);
}
let eps = match D::dir() {
Direction::Out => &mut self.ep_out,
Direction::In => &mut self.ep_in,
};
// Find free endpoint slot
let slot = eps.iter_mut().enumerate().find(|(i, ep)| {
if *i == 0 && ep_type != EndpointType::Control {
// reserved for control pipe
false
} else {
ep.is_none()
}
});
let index = match slot {
Some((index, ep)) => {
*ep = Some(EndpointData {
ep_type,
max_packet_size,
fifo_size_words,
});
index
}
None => {
error!("No free endpoints available");
return Err(EndpointAllocError);
}
};
trace!(" index={}", index);
let state = &self.instance.state.ep_states[index];
if D::dir() == Direction::Out {
// Buffer capacity check was done above, now allocation cannot fail
unsafe {
*state.out_buffer.get() = self.ep_out_buffer.as_mut_ptr().offset(self.ep_out_buffer_offset as _);
}
self.ep_out_buffer_offset += max_packet_size as usize;
}
Ok(Endpoint {
_phantom: PhantomData,
regs: self.instance.regs,
state,
info: EndpointInfo {
addr: EndpointAddress::from_parts(index, D::dir()),
ep_type,
max_packet_size,
interval_ms,
},
})
}
}
impl<'d, const MAX_EP_COUNT: usize> embassy_usb_driver::Driver<'d> for Driver<'d, MAX_EP_COUNT> {
type EndpointOut = Endpoint<'d, Out>;
type EndpointIn = Endpoint<'d, In>;
type ControlPipe = ControlPipe<'d>;
type Bus = Bus<'d, MAX_EP_COUNT>;
fn alloc_endpoint_in(
&mut self,
ep_type: EndpointType,
max_packet_size: u16,
interval_ms: u8,
) -> Result<Self::EndpointIn, EndpointAllocError> {
self.alloc_endpoint(ep_type, max_packet_size, interval_ms)
}
fn alloc_endpoint_out(
&mut self,
ep_type: EndpointType,
max_packet_size: u16,
interval_ms: u8,
) -> Result<Self::EndpointOut, EndpointAllocError> {
self.alloc_endpoint(ep_type, max_packet_size, interval_ms)
}
fn start(mut self, control_max_packet_size: u16) -> (Self::Bus, Self::ControlPipe) {
let ep_out = self
.alloc_endpoint(EndpointType::Control, control_max_packet_size, 0)
.unwrap();
let ep_in = self
.alloc_endpoint(EndpointType::Control, control_max_packet_size, 0)
.unwrap();
assert_eq!(ep_out.info.addr.index(), 0);
assert_eq!(ep_in.info.addr.index(), 0);
trace!("start");
let regs = self.instance.regs;
let quirk_setup_late_cnak = self.instance.quirk_setup_late_cnak;
let cp_setup_state = &self.instance.state.cp_state;
(
Bus {
config: self.config,
ep_in: self.ep_in,
ep_out: self.ep_out,
inited: false,
instance: self.instance,
},
ControlPipe {
max_packet_size: control_max_packet_size,
setup_state: cp_setup_state,
ep_out,
ep_in,
regs,
quirk_setup_late_cnak,
},
)
}
}
/// USB bus.
pub struct Bus<'d, const MAX_EP_COUNT: usize> {
config: Config,
ep_in: [Option<EndpointData>; MAX_EP_COUNT],
ep_out: [Option<EndpointData>; MAX_EP_COUNT],
instance: OtgInstance<'d, MAX_EP_COUNT>,
inited: bool,
}
impl<'d, const MAX_EP_COUNT: usize> Bus<'d, MAX_EP_COUNT> {
fn restore_irqs(&mut self) {
self.instance.regs.gintmsk().write(|w| {
w.set_usbrst(true);
w.set_enumdnem(true);
w.set_usbsuspm(true);
w.set_wuim(true);
w.set_iepint(true);
w.set_oepint(true);
w.set_rxflvlm(true);
w.set_srqim(true);
w.set_otgint(true);
});
}
/// Returns the PHY type.
pub fn phy_type(&self) -> PhyType {
self.instance.phy_type
}
/// Configures the PHY as a device.
pub fn configure_as_device(&mut self) {
let r = self.instance.regs;
let phy_type = self.instance.phy_type;
r.gusbcfg().write(|w| {
// Force device mode
w.set_fdmod(true);
// Enable internal full-speed PHY
w.set_physel(phy_type.internal() && !phy_type.high_speed());
});
}
/// Applies configuration specific to
/// Core ID 0x0000_1100 and 0x0000_1200
pub fn config_v1(&mut self) {
let r = self.instance.regs;
let phy_type = self.instance.phy_type;
assert!(phy_type != PhyType::InternalHighSpeed);
r.gccfg_v1().modify(|w| {
// Enable internal full-speed PHY, logic is inverted
w.set_pwrdwn(phy_type.internal());
});
// F429-like chips have the GCCFG.NOVBUSSENS bit
r.gccfg_v1().modify(|w| {
w.set_novbussens(!self.config.vbus_detection);
w.set_vbusasen(false);
w.set_vbusbsen(self.config.vbus_detection);
w.set_sofouten(false);
});
}
/// Applies configuration specific to
/// Core ID 0x0000_2000, 0x0000_2100, 0x0000_2300, 0x0000_3000 and 0x0000_3100
pub fn config_v2v3(&mut self) {
let r = self.instance.regs;
let phy_type = self.instance.phy_type;
// F446-like chips have the GCCFG.VBDEN bit with the opposite meaning
r.gccfg_v2().modify(|w| {
// Enable internal full-speed PHY, logic is inverted
w.set_pwrdwn(phy_type.internal() && !phy_type.high_speed());
w.set_phyhsen(phy_type.internal() && phy_type.high_speed());
});
r.gccfg_v2().modify(|w| {
w.set_vbden(self.config.vbus_detection);
});
// Force B-peripheral session
r.gotgctl().modify(|w| {
w.set_bvaloen(!self.config.vbus_detection);
w.set_bvaloval(true);
});
}
fn init(&mut self) {
let r = self.instance.regs;
let phy_type = self.instance.phy_type;
// Soft disconnect.
r.dctl().write(|w| w.set_sdis(true));
// Set speed.
r.dcfg().write(|w| {
w.set_pfivl(vals::Pfivl::FRAME_INTERVAL_80);
w.set_dspd(phy_type.to_dspd());
if self.config.xcvrdly {
w.set_xcvrdly(true);
}
});
// Unmask transfer complete EP interrupt
r.diepmsk().write(|w| {
w.set_xfrcm(true);
});
// Unmask and clear core interrupts
self.restore_irqs();
r.gintsts().write_value(regs::Gintsts(0xFFFF_FFFF));
// Unmask global interrupt
r.gahbcfg().write(|w| {
w.set_gint(true); // unmask global interrupt
});
// Connect
r.dctl().write(|w| w.set_sdis(false));
}
fn init_fifo(&mut self) {
trace!("init_fifo");
let regs = self.instance.regs;
// ERRATA NOTE: Don't interrupt FIFOs being written to. The interrupt
// handler COULD interrupt us here and do FIFO operations, so ensure
// the interrupt does not occur.
critical_section::with(|_| {
// Configure RX fifo size. All endpoints share the same FIFO area.
let rx_fifo_size_words = self.instance.extra_rx_fifo_words + ep_fifo_size(&self.ep_out);
trace!("configuring rx fifo size={}", rx_fifo_size_words);
regs.grxfsiz().modify(|w| w.set_rxfd(rx_fifo_size_words));
// Configure TX (USB in direction) fifo size for each endpoint
let mut fifo_top = rx_fifo_size_words;
for i in 0..self.instance.endpoint_count {
if let Some(ep) = self.ep_in[i] {
trace!(
"configuring tx fifo ep={}, offset={}, size={}",
i,
fifo_top,
ep.fifo_size_words
);
let dieptxf = if i == 0 { regs.dieptxf0() } else { regs.dieptxf(i - 1) };
dieptxf.write(|w| {
w.set_fd(ep.fifo_size_words);
w.set_sa(fifo_top);
});
fifo_top += ep.fifo_size_words;
}
}
assert!(
fifo_top <= self.instance.fifo_depth_words,
"FIFO allocations exceeded maximum capacity"
);
// Flush fifos
regs.grstctl().write(|w| {
w.set_rxfflsh(true);
w.set_txfflsh(true);
w.set_txfnum(0x10);
});
});
loop {
let x = regs.grstctl().read();
if !x.rxfflsh() && !x.txfflsh() {
break;
}
}
}
fn configure_endpoints(&mut self) {
trace!("configure_endpoints");
let regs = self.instance.regs;
// Configure IN endpoints
for (index, ep) in self.ep_in.iter().enumerate() {
if let Some(ep) = ep {
critical_section::with(|_| {
regs.diepctl(index).write(|w| {
if index == 0 {
w.set_mpsiz(ep0_mpsiz(ep.max_packet_size));
} else {
w.set_mpsiz(ep.max_packet_size);
w.set_eptyp(to_eptyp(ep.ep_type));
w.set_sd0pid_sevnfrm(true);
w.set_txfnum(index as _);
w.set_snak(true);
}
});
});
}
}
// Configure OUT endpoints
for (index, ep) in self.ep_out.iter().enumerate() {
if let Some(ep) = ep {
critical_section::with(|_| {
regs.doepctl(index).write(|w| {
if index == 0 {
w.set_mpsiz(ep0_mpsiz(ep.max_packet_size));
} else {
w.set_mpsiz(ep.max_packet_size);
w.set_eptyp(to_eptyp(ep.ep_type));
w.set_sd0pid_sevnfrm(true);
}
});
regs.doeptsiz(index).modify(|w| {
w.set_xfrsiz(ep.max_packet_size as _);
if index == 0 {
w.set_rxdpid_stupcnt(1);
} else {
w.set_pktcnt(1);
}
});
});
}
}
// Enable IRQs for allocated endpoints
regs.daintmsk().modify(|w| {
w.set_iepm(ep_irq_mask(&self.ep_in));
// OUT interrupts not used, handled in RXFLVL
// w.set_oepm(ep_irq_mask(&self.ep_out));
});
}
fn disable_all_endpoints(&mut self) {
for i in 0..self.instance.endpoint_count {
self.endpoint_set_enabled(EndpointAddress::from_parts(i, Direction::In), false);
self.endpoint_set_enabled(EndpointAddress::from_parts(i, Direction::Out), false);
}
}
}
impl<'d, const MAX_EP_COUNT: usize> embassy_usb_driver::Bus for Bus<'d, MAX_EP_COUNT> {
async fn poll(&mut self) -> Event {
poll_fn(move |cx| {
if !self.inited {
self.init();
self.inited = true;
// If no vbus detection, just return a single PowerDetected event at startup.
if !self.config.vbus_detection {
return Poll::Ready(Event::PowerDetected);
}
}
let regs = self.instance.regs;
self.instance.state.bus_waker.register(cx.waker());
let ints = regs.gintsts().read();
if ints.srqint() {
trace!("vbus detected");
regs.gintsts().write(|w| w.set_srqint(true)); // clear
self.restore_irqs();
if self.config.vbus_detection {
return Poll::Ready(Event::PowerDetected);
}
}
if ints.otgint() {
let otgints = regs.gotgint().read();
regs.gotgint().write_value(otgints); // clear all
self.restore_irqs();
if otgints.sedet() {
trace!("vbus removed");
if self.config.vbus_detection {
self.disable_all_endpoints();
return Poll::Ready(Event::PowerRemoved);
}
}
}
if ints.usbrst() {
trace!("reset");
self.init_fifo();
self.configure_endpoints();
// Reset address
critical_section::with(|_| {
regs.dcfg().modify(|w| {
w.set_dad(0);
});
});
regs.gintsts().write(|w| w.set_usbrst(true)); // clear
self.restore_irqs();
}
if ints.enumdne() {
trace!("enumdne");
let speed = regs.dsts().read().enumspd();
let trdt = (self.instance.calculate_trdt_fn)(speed);
trace!(" speed={} trdt={}", speed.to_bits(), trdt);
regs.gusbcfg().modify(|w| w.set_trdt(trdt));
regs.gintsts().write(|w| w.set_enumdne(true)); // clear
self.restore_irqs();
return Poll::Ready(Event::Reset);
}
if ints.usbsusp() {
trace!("suspend");
regs.gintsts().write(|w| w.set_usbsusp(true)); // clear
self.restore_irqs();
return Poll::Ready(Event::Suspend);
}
if ints.wkupint() {
trace!("resume");
regs.gintsts().write(|w| w.set_wkupint(true)); // clear
self.restore_irqs();
return Poll::Ready(Event::Resume);
}
Poll::Pending
})
.await
}
fn endpoint_set_stalled(&mut self, ep_addr: EndpointAddress, stalled: bool) {
trace!("endpoint_set_stalled ep={:?} en={}", ep_addr, stalled);
assert!(
ep_addr.index() < self.instance.endpoint_count,
"endpoint_set_stalled index {} out of range",
ep_addr.index()
);
let regs = self.instance.regs;
let state = self.instance.state;
match ep_addr.direction() {
Direction::Out => {
critical_section::with(|_| {
regs.doepctl(ep_addr.index()).modify(|w| {
w.set_stall(stalled);
});
});
state.ep_states[ep_addr.index()].out_waker.wake();
}
Direction::In => {
critical_section::with(|_| {
regs.diepctl(ep_addr.index()).modify(|w| {
w.set_stall(stalled);
});
});
state.ep_states[ep_addr.index()].in_waker.wake();
}
}
}
fn endpoint_is_stalled(&mut self, ep_addr: EndpointAddress) -> bool {
assert!(
ep_addr.index() < self.instance.endpoint_count,
"endpoint_is_stalled index {} out of range",
ep_addr.index()
);
let regs = self.instance.regs;
match ep_addr.direction() {
Direction::Out => regs.doepctl(ep_addr.index()).read().stall(),
Direction::In => regs.diepctl(ep_addr.index()).read().stall(),
}
}
fn endpoint_set_enabled(&mut self, ep_addr: EndpointAddress, enabled: bool) {
trace!("endpoint_set_enabled ep={:?} en={}", ep_addr, enabled);
assert!(
ep_addr.index() < self.instance.endpoint_count,
"endpoint_set_enabled index {} out of range",
ep_addr.index()
);
let regs = self.instance.regs;
let state = self.instance.state;
match ep_addr.direction() {
Direction::Out => {
critical_section::with(|_| {
// cancel transfer if active
if !enabled && regs.doepctl(ep_addr.index()).read().epena() {
regs.doepctl(ep_addr.index()).modify(|w| {
w.set_snak(true);
w.set_epdis(true);
})
}
regs.doepctl(ep_addr.index()).modify(|w| {
w.set_usbaep(enabled);
});
// Flush tx fifo
regs.grstctl().write(|w| {
w.set_txfflsh(true);
w.set_txfnum(ep_addr.index() as _);
});
loop {
let x = regs.grstctl().read();
if !x.txfflsh() {
break;
}
}
});
// Wake `Endpoint::wait_enabled()`
state.ep_states[ep_addr.index()].out_waker.wake();
}
Direction::In => {
critical_section::with(|_| {
// cancel transfer if active
if !enabled && regs.diepctl(ep_addr.index()).read().epena() {
regs.diepctl(ep_addr.index()).modify(|w| {
w.set_snak(true); // set NAK
w.set_epdis(true);
})
}
regs.diepctl(ep_addr.index()).modify(|w| {
w.set_usbaep(enabled);
w.set_cnak(enabled); // clear NAK that might've been set by SNAK above.
})
});
// Wake `Endpoint::wait_enabled()`
state.ep_states[ep_addr.index()].in_waker.wake();
}
}
}
async fn enable(&mut self) {
trace!("enable");
// TODO: enable the peripheral once enable/disable semantics are cleared up in embassy-usb
}
async fn disable(&mut self) {
trace!("disable");
// TODO: disable the peripheral once enable/disable semantics are cleared up in embassy-usb
//Bus::disable(self);
}
async fn remote_wakeup(&mut self) -> Result<(), Unsupported> {
Err(Unsupported)
}
}
/// USB endpoint direction.
trait Dir {
/// Returns the direction value.
fn dir() -> Direction;
}
/// Marker type for the "IN" direction.
pub enum In {}
impl Dir for In {
fn dir() -> Direction {
Direction::In
}
}
/// Marker type for the "OUT" direction.
pub enum Out {}
impl Dir for Out {
fn dir() -> Direction {
Direction::Out
}
}
/// USB endpoint.
pub struct Endpoint<'d, D> {
_phantom: PhantomData<D>,
regs: Otg,
info: EndpointInfo,
state: &'d EpState,
}
impl<'d> embassy_usb_driver::Endpoint for Endpoint<'d, In> {
fn info(&self) -> &EndpointInfo {
&self.info
}
async fn wait_enabled(&mut self) {
poll_fn(|cx| {
let ep_index = self.info.addr.index();