atsamd_hal/peripherals/usb/d11/
bus.rs

1// This crate uses standard host-centric USB terminology for transfer
2// directions. Therefore an OUT transfer refers to a host-to-device transfer,
3// and an IN transfer refers to a device-to-host transfer. This is mainly a
4// concern for implementing new USB peripheral drivers and USB classes, and
5// people doing that should be familiar with the USB standard. http://ww1.microchip.com/downloads/en/DeviceDoc/60001507E.pdf
6// http://ww1.microchip.com/downloads/en/AppNotes/Atmel-42261-SAM-D21-USB_Application-Note_AT06475.pdf
7
8use super::Descriptors;
9use crate::calibration::{usb_transn_cal, usb_transp_cal, usb_trim_cal};
10use crate::clock;
11use crate::gpio::{AlternateG, AnyPin, Pin, PA24, PA25};
12use crate::pac::usb::Device;
13use crate::pac::{Pm, Usb};
14use crate::usb::devicedesc::DeviceDescBank;
15use atsamd_hal_macros::{hal_cfg, hal_macro_helper};
16use core::cell::{Ref, RefCell, RefMut};
17use core::marker::PhantomData;
18use core::mem;
19use cortex_m::singleton;
20use critical_section::{with as disable_interrupts, Mutex};
21use usb_device::bus::PollResult;
22use usb_device::endpoint::{EndpointAddress, EndpointType};
23use usb_device::{Result as UsbResult, UsbDirection, UsbError};
24
25/// EndpointTypeBits represents valid values for the EPTYPE fields in
26/// the EPCFGn registers.
27#[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
28pub enum EndpointTypeBits {
29    #[default]
30    Disabled = 0,
31    Control = 1,
32    Isochronous = 2,
33    Bulk = 3,
34    Interrupt = 4,
35    #[allow(unused)]
36    DualBank = 5,
37}
38
39impl From<EndpointType> for EndpointTypeBits {
40    fn from(ep_type: EndpointType) -> EndpointTypeBits {
41        match ep_type {
42            EndpointType::Control => EndpointTypeBits::Control,
43            EndpointType::Isochronous { .. } => EndpointTypeBits::Isochronous,
44            EndpointType::Bulk => EndpointTypeBits::Bulk,
45            EndpointType::Interrupt => EndpointTypeBits::Interrupt,
46        }
47    }
48}
49
50/// EPConfig tracks the desired configuration for one side of an endpoint.
51#[derive(Default, Clone, Copy)]
52struct EPConfig {
53    ep_type: EndpointTypeBits,
54    allocated_size: u16,
55    max_packet_size: u16,
56    addr: usize,
57}
58
59impl EPConfig {
60    fn new(
61        ep_type: EndpointType,
62        allocated_size: u16,
63        max_packet_size: u16,
64        buffer_addr: *mut u8,
65    ) -> Self {
66        Self {
67            ep_type: ep_type.into(),
68            allocated_size,
69            max_packet_size,
70            addr: buffer_addr as usize,
71        }
72    }
73}
74
75// EndpointInfo represents the desired configuration for an endpoint pair.
76#[derive(Default)]
77struct EndpointInfo {
78    bank0: EPConfig,
79    bank1: EPConfig,
80}
81
82impl EndpointInfo {
83    fn new() -> Self {
84        Default::default()
85    }
86}
87
88/// AllEndpoints tracks the desired configuration of all endpoints managed
89/// by the USB peripheral.
90struct AllEndpoints {
91    endpoints: [EndpointInfo; 8],
92}
93
94impl AllEndpoints {
95    fn new() -> Self {
96        Self {
97            endpoints: [
98                EndpointInfo::new(),
99                EndpointInfo::new(),
100                EndpointInfo::new(),
101                EndpointInfo::new(),
102                EndpointInfo::new(),
103                EndpointInfo::new(),
104                EndpointInfo::new(),
105                EndpointInfo::new(),
106            ],
107        }
108    }
109
110    fn find_free_endpoint(&self, dir: UsbDirection) -> UsbResult<usize> {
111        // start with 1 because 0 is reserved for Control
112        for idx in 1..8 {
113            let ep_type = match dir {
114                UsbDirection::Out => self.endpoints[idx].bank0.ep_type,
115                UsbDirection::In => self.endpoints[idx].bank1.ep_type,
116            };
117            if ep_type == EndpointTypeBits::Disabled {
118                return Ok(idx);
119            }
120        }
121        Err(UsbError::EndpointOverflow)
122    }
123
124    #[allow(clippy::too_many_arguments)]
125    fn allocate_endpoint(
126        &mut self,
127        dir: UsbDirection,
128        idx: usize,
129        ep_type: EndpointType,
130        allocated_size: u16,
131        max_packet_size: u16,
132        _interval: u8,
133        buffer_addr: *mut u8,
134    ) -> UsbResult<EndpointAddress> {
135        let bank = match dir {
136            UsbDirection::Out => &mut self.endpoints[idx].bank0,
137            UsbDirection::In => &mut self.endpoints[idx].bank1,
138        };
139        if bank.ep_type != EndpointTypeBits::Disabled {
140            return Err(UsbError::EndpointOverflow);
141        }
142
143        *bank = EPConfig::new(ep_type, allocated_size, max_packet_size, buffer_addr);
144
145        Ok(EndpointAddress::from_parts(idx, dir))
146    }
147}
148
149// FIXME: replace with more general heap?
150const BUFFER_SIZE: usize = 2048;
151fn buffer() -> &'static mut [u8; BUFFER_SIZE] {
152    singleton!(: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE] ).unwrap()
153}
154
155struct BufferAllocator {
156    buffers: &'static mut [u8; BUFFER_SIZE],
157    next_buf: u16,
158}
159
160impl BufferAllocator {
161    fn new() -> Self {
162        Self {
163            next_buf: 0,
164            buffers: buffer(),
165        }
166    }
167
168    fn allocate_buffer(&mut self, size: u16) -> UsbResult<*mut u8> {
169        debug_assert!(size & 1 == 0);
170
171        let start_addr = &mut self.buffers[self.next_buf as usize] as *mut u8;
172        let buf_end = unsafe { start_addr.add(BUFFER_SIZE) };
173
174        // The address must be 32-bit aligned, so allow for that here
175        // by offsetting by an appropriate alignment.
176        let offset = start_addr.align_offset(mem::align_of::<u32>());
177        let start_addr = unsafe { start_addr.add(offset) };
178
179        if start_addr >= buf_end {
180            return Err(UsbError::EndpointMemoryOverflow);
181        }
182
183        let end_addr = unsafe { start_addr.offset(size as isize) };
184        if end_addr > buf_end {
185            return Err(UsbError::EndpointMemoryOverflow);
186        }
187
188        self.next_buf = unsafe { end_addr.sub(self.buffers.as_ptr() as usize) as u16 };
189
190        Ok(start_addr)
191    }
192}
193
194struct Inner {
195    desc: RefCell<Descriptors>,
196    _dm_pad: Pin<PA24, AlternateG>,
197    _dp_pad: Pin<PA25, AlternateG>,
198    endpoints: RefCell<AllEndpoints>,
199    buffers: RefCell<BufferAllocator>,
200}
201
202pub struct UsbBus {
203    inner: Mutex<RefCell<Inner>>,
204}
205
206struct Bank<'a, T> {
207    address: EndpointAddress,
208    usb: &'a Device,
209    desc: RefMut<'a, super::Descriptors>,
210    _phantom: PhantomData<T>,
211    endpoints: Ref<'a, AllEndpoints>,
212}
213
214impl<T> Bank<'_, T> {
215    fn usb(&self) -> &Device {
216        self.usb
217    }
218
219    #[inline]
220    fn index(&self) -> usize {
221        self.address.index()
222    }
223
224    #[inline]
225    fn config(&mut self) -> &EPConfig {
226        let ep = &self.endpoints.endpoints[self.address.index()];
227        if self.address.is_out() {
228            &ep.bank0
229        } else {
230            &ep.bank1
231        }
232    }
233}
234
235/// InBank represents In direction banks, Bank #1
236struct InBank;
237
238/// OutBank represents Out direction banks, Bank #0
239struct OutBank;
240
241impl Bank<'_, InBank> {
242    fn desc_bank(&mut self) -> &mut DeviceDescBank {
243        let idx = self.index();
244        self.desc.bank(idx, 1)
245    }
246
247    /// Returns true if Bank 1 is Ready and thus has data that can be written
248    #[inline]
249    fn is_ready(&self) -> bool {
250        self.usb().epstatus(self.index()).read().bk1rdy().bit()
251    }
252
253    /// Set Bank 1 Ready.
254    /// Ready means that the buffer contains data that can be sent.
255    #[inline]
256    fn set_ready(&self, ready: bool) {
257        if ready {
258            self.usb()
259                .epstatusset(self.index())
260                .write(|w| w.bk1rdy().set_bit());
261        } else {
262            self.usb()
263                .epstatusclr(self.index())
264                .write(|w| w.bk1rdy().set_bit());
265        }
266    }
267
268    /// Acknowledges the signal that the last packet was sent.
269    #[inline]
270    fn clear_transfer_complete(&self) {
271        // Clear bits in epintflag by writing them to 1
272        self.usb()
273            .epintflag(self.index())
274            .write(|w| w.trcpt1().set_bit().trfail1().set_bit());
275    }
276
277    /// Indicates if a transfer is complete or pending.
278    #[inline]
279    fn is_transfer_complete(&self) -> bool {
280        self.usb().epintflag(self.index()).read().trcpt1().bit()
281    }
282
283    /// Writes out endpoint configuration to its in-memory descriptor.
284    fn flush_config(&mut self) {
285        let config = *self.config();
286        {
287            let desc = self.desc_bank();
288            desc.set_address(config.addr as *mut u8);
289            desc.set_endpoint_size(config.max_packet_size);
290            desc.set_multi_packet_size(0);
291            desc.set_byte_count(0);
292        }
293    }
294
295    /// Enables endpoint-specific interrupts.
296    fn setup_ep_interrupts(&mut self) {
297        self.usb()
298            .epintenset(self.index())
299            .write(|w| w.trcpt1().set_bit());
300    }
301
302    /// Prepares to transfer a series of bytes by copying the data into the
303    /// bank1 buffer. The caller must call set_ready() to finalize the
304    /// transfer.
305    pub fn write(&mut self, buf: &[u8]) -> UsbResult<usize> {
306        let size = buf.len().min(self.config().allocated_size as usize);
307        let desc = self.desc_bank();
308
309        unsafe {
310            buf.as_ptr()
311                .copy_to_nonoverlapping(desc.get_address(), size);
312        }
313
314        desc.set_multi_packet_size(0);
315        desc.set_byte_count(size as u16);
316
317        Ok(size)
318    }
319
320    fn is_stalled(&self) -> bool {
321        self.usb().epintflag(self.index()).read().stall1().bit()
322    }
323
324    fn set_stall(&mut self, stall: bool) {
325        if stall {
326            self.usb()
327                .epstatusset(self.index())
328                .write(|w| w.stallrq1().set_bit())
329        } else {
330            self.usb()
331                .epstatusclr(self.index())
332                .write(|w| w.stallrq1().set_bit())
333        }
334    }
335}
336
337impl Bank<'_, OutBank> {
338    fn desc_bank(&mut self) -> &mut DeviceDescBank {
339        let idx = self.index();
340        self.desc.bank(idx, 0)
341    }
342
343    /// Returns true if Bank 0 is Ready and thus has data that can be read.
344    #[inline]
345    fn is_ready(&self) -> bool {
346        self.usb().epstatus(self.index()).read().bk0rdy().bit()
347    }
348
349    /// Set Bank 0 Ready.
350    /// Ready means that the buffer contains data that can be read.
351    #[inline]
352    fn set_ready(&self, ready: bool) {
353        if ready {
354            self.usb()
355                .epstatusset(self.index())
356                .write(|w| w.bk0rdy().set_bit());
357        } else {
358            self.usb()
359                .epstatusclr(self.index())
360                .write(|w| w.bk0rdy().set_bit());
361        }
362    }
363
364    /// Acknowledges the signal that data has been received.
365    #[inline]
366    fn clear_transfer_complete(&self) {
367        // Clear bits in epintflag by writing them to 1
368        self.usb()
369            .epintflag(self.index())
370            .write(|w| w.trcpt0().set_bit().trfail0().set_bit());
371    }
372
373    /// Returns true if a Received Setup interrupt has occurred.
374    /// This indicates that the read buffer holds a SETUP packet.
375    #[inline]
376    fn received_setup_interrupt(&self) -> bool {
377        self.usb().epintflag(self.index()).read().rxstp().bit()
378    }
379
380    /// Acknowledges the signal that a SETUP packet was received
381    /// successfully.
382    #[inline]
383    fn clear_received_setup_interrupt(&self) {
384        // Clear bits in epintflag by writing them to 1
385        self.usb()
386            .epintflag(self.index())
387            .write(|w| w.rxstp().set_bit());
388    }
389
390    /// Writes out endpoint configuration to its in-memory descriptor.
391    fn flush_config(&mut self) {
392        let config = *self.config();
393        {
394            let desc = self.desc_bank();
395            desc.set_address(config.addr as *mut u8);
396            desc.set_endpoint_size(config.max_packet_size);
397            desc.set_multi_packet_size(0);
398            desc.set_byte_count(0);
399        }
400    }
401
402    /// Enables endpoint-specific interrupts.
403    fn setup_ep_interrupts(&mut self) {
404        self.usb()
405            .epintenset(self.index())
406            .write(|w| w.rxstp().set_bit().trcpt0().set_bit());
407    }
408
409    /// Copies data from the bank0 buffer to the provided array. The caller
410    /// must call set_ready to indicate the buffer is free for the next
411    /// transfer.
412    pub fn read(&mut self, buf: &mut [u8]) -> UsbResult<usize> {
413        let desc = self.desc_bank();
414        let size = desc.get_byte_count() as usize;
415
416        if size > buf.len() {
417            return Err(UsbError::BufferOverflow);
418        }
419        unsafe {
420            desc.get_address()
421                .copy_to_nonoverlapping(buf.as_mut_ptr(), size);
422        }
423
424        desc.set_byte_count(0);
425        desc.set_multi_packet_size(0);
426
427        Ok(size)
428    }
429
430    fn is_stalled(&self) -> bool {
431        self.usb().epintflag(self.index()).read().stall0().bit()
432    }
433
434    fn set_stall(&mut self, stall: bool) {
435        if stall {
436            self.usb()
437                .epstatusset(self.index())
438                .write(|w| w.stallrq0().set_bit())
439        } else {
440            self.usb()
441                .epstatusclr(self.index())
442                .write(|w| w.stallrq0().set_bit())
443        }
444    }
445}
446
447impl Inner {
448    fn bank0(&'_ self, ep: EndpointAddress) -> UsbResult<Bank<'_, OutBank>> {
449        if ep.is_in() {
450            return Err(UsbError::InvalidEndpoint);
451        }
452        let endpoints = self.endpoints.borrow();
453
454        if endpoints.endpoints[ep.index()].bank0.ep_type == EndpointTypeBits::Disabled {
455            return Err(UsbError::InvalidEndpoint);
456        }
457        Ok(Bank {
458            address: ep,
459            usb: self.usb(),
460            desc: self.desc.borrow_mut(),
461            endpoints,
462            _phantom: PhantomData,
463        })
464    }
465
466    fn bank1(&'_ self, ep: EndpointAddress) -> UsbResult<Bank<'_, InBank>> {
467        if ep.is_out() {
468            return Err(UsbError::InvalidEndpoint);
469        }
470        let endpoints = self.endpoints.borrow();
471
472        if endpoints.endpoints[ep.index()].bank1.ep_type == EndpointTypeBits::Disabled {
473            return Err(UsbError::InvalidEndpoint);
474        }
475        Ok(Bank {
476            address: ep,
477            usb: self.usb(),
478            desc: self.desc.borrow_mut(),
479            endpoints,
480            _phantom: PhantomData,
481        })
482    }
483}
484
485impl UsbBus {
486    pub fn new(
487        _clock: &clock::UsbClock,
488        pm: &mut Pm,
489        dm_pad: impl AnyPin<Id = PA24>,
490        dp_pad: impl AnyPin<Id = PA25>,
491        _usb: Usb,
492    ) -> Self {
493        pm.apbbmask().modify(|_, w| w.usb_().set_bit());
494
495        let desc = RefCell::new(Descriptors::new());
496
497        let inner = Inner {
498            _dm_pad: dm_pad.into().into_mode::<AlternateG>(),
499            _dp_pad: dp_pad.into().into_mode::<AlternateG>(),
500            desc,
501            buffers: RefCell::new(BufferAllocator::new()),
502            endpoints: RefCell::new(AllEndpoints::new()),
503        };
504
505        Self {
506            inner: Mutex::new(RefCell::new(inner)),
507        }
508    }
509}
510
511impl Inner {
512    #[hal_cfg("usb-d11")]
513    fn usb(&self) -> &Device {
514        unsafe { (*Usb::ptr()).device() }
515    }
516
517    #[hal_cfg("usb-d21")]
518    fn usb(&self) -> &Device {
519        unsafe { (*Usb::ptr()).device() }
520    }
521
522    fn set_stall<EP: Into<EndpointAddress>>(&self, ep: EP, stall: bool) {
523        let ep = ep.into();
524        if ep.is_out() {
525            if let Ok(mut bank) = self.bank0(ep) {
526                bank.set_stall(stall);
527            }
528        } else if let Ok(mut bank) = self.bank1(ep) {
529            bank.set_stall(stall);
530        }
531    }
532}
533
534#[derive(Copy, Clone)]
535enum FlushConfigMode {
536    // Write configuration to all configured endpoints.
537    Full,
538    // Refresh configuration which was reset due to a bus reset.
539    ProtocolReset,
540}
541
542impl Inner {
543    #[hal_macro_helper]
544    fn enable(&mut self) {
545        let usb = self.usb();
546        usb.ctrla().modify(|_, w| w.swrst().set_bit());
547        while usb.syncbusy().read().swrst().bit_is_set() {}
548
549        let addr = self.desc.borrow().address();
550        usb.descadd().write(|w| unsafe { w.descadd().bits(addr) });
551        usb.padcal().modify(|_, w| unsafe {
552            w.transn().bits(usb_transn_cal());
553            w.transp().bits(usb_transp_cal());
554            w.trim().bits(usb_trim_cal())
555        });
556
557        #[hal_cfg("usb-d11")]
558        usb.qosctrl().modify(|_, w| unsafe {
559            w.dqos().bits(0b11);
560            w.cqos().bits(0b11)
561        });
562        #[hal_cfg("usb-d21")]
563        usb.qosctrl().modify(|_, w| unsafe {
564            w.dqos().bits(0b11);
565            w.cqos().bits(0b11)
566        });
567
568        usb.ctrla().modify(|_, w| {
569            w.mode().device();
570            w.runstdby().set_bit()
571        });
572        // full speed
573        usb.ctrlb().modify(|_, w| w.spdconf().fs());
574
575        usb.ctrla().modify(|_, w| w.enable().set_bit());
576        while usb.syncbusy().read().enable().bit_is_set() {}
577
578        // Clear pending.
579        usb.intflag()
580            .write(|w| unsafe { w.bits(usb.intflag().read().bits()) });
581        usb.intenset().write(|w| w.eorst().set_bit());
582
583        // Configure the endpoints before we attach, as hosts may enumerate
584        // before attempting a USB protocol reset.
585        self.flush_eps(FlushConfigMode::Full);
586
587        usb.ctrlb().modify(|_, w| w.detach().clear_bit());
588    }
589
590    /// Enables/disables the Start Of Frame (SOF) interrupt
591    fn sof_interrupt(&self, enable: bool) {
592        if enable {
593            self.usb().intenset().write(|w| w.sof().set_bit());
594        } else {
595            self.usb().intenclr().write(|w| w.sof().set_bit());
596        }
597    }
598
599    /// Configures all endpoints based on prior calls to alloc_ep().
600    fn flush_eps(&self, mode: FlushConfigMode) {
601        for idx in 0..8 {
602            match (mode, idx) {
603                // A flush due to a protocol reset need not reconfigure endpoint 0,
604                // except for enabling its interrupts.
605                (FlushConfigMode::ProtocolReset, 0) => {
606                    self.setup_ep_interrupts(EndpointAddress::from_parts(idx, UsbDirection::Out));
607                    self.setup_ep_interrupts(EndpointAddress::from_parts(idx, UsbDirection::In));
608                }
609                // A full flush configures all provisioned endpoints + enables interrupts.
610                // Endpoints 1-8 have identical behaviour when flushed due to protocol reset.
611                (FlushConfigMode::Full, _) | (FlushConfigMode::ProtocolReset, _) => {
612                    // Write bank configuration & endpoint type.
613                    self.flush_ep(idx);
614                    // Endpoint interrupts are configured after the write to EPTYPE, as it appears
615                    // writes to EPINTEN*[n] do not take effect unless the
616                    // endpoint is already somewhat configured. The datasheet is
617                    // ambiguous here, section 38.8.3.7 (Device Interrupt EndPoint Set n)
618                    // of the SAM D5x/E5x states:
619                    //    "This register is cleared by USB reset or when EPEN[n] is zero"
620                    // EPEN[n] is not a register that exists, nor does it align with any other
621                    // terminology. We assume this means setting EPCFG[n] to a
622                    // non-zero value, but we do interrupt configuration last to
623                    // be sure.
624                    self.setup_ep_interrupts(EndpointAddress::from_parts(idx, UsbDirection::Out));
625                    self.setup_ep_interrupts(EndpointAddress::from_parts(idx, UsbDirection::In));
626                }
627            }
628        }
629    }
630
631    /// flush_ep commits bank descriptor information for the endpoint pair,
632    /// and enables the endpoint according to its type.
633    fn flush_ep(&self, idx: usize) {
634        let cfg = self.usb().epcfg(idx);
635        let info = &self.endpoints.borrow().endpoints[idx];
636        // Write bank descriptors first. We do this so there is no period in
637        // which the endpoint is enabled but has an invalid descriptor.
638        if let Ok(mut bank) = self.bank0(EndpointAddress::from_parts(idx, UsbDirection::Out)) {
639            bank.flush_config();
640        }
641        if let Ok(mut bank) = self.bank1(EndpointAddress::from_parts(idx, UsbDirection::In)) {
642            bank.flush_config();
643        }
644
645        // Set the endpoint type. At this point, the endpoint is enabled.
646        cfg.modify(|_, w| unsafe {
647            w.eptype0()
648                .bits(info.bank0.ep_type as u8)
649                .eptype1()
650                .bits(info.bank1.ep_type as u8)
651        });
652    }
653
654    /// setup_ep_interrupts enables interrupts for the given endpoint address.
655    fn setup_ep_interrupts(&self, ep_addr: EndpointAddress) {
656        if ep_addr.is_out() {
657            if let Ok(mut bank) = self.bank0(ep_addr) {
658                bank.setup_ep_interrupts();
659            }
660        } else if let Ok(mut bank) = self.bank1(ep_addr) {
661            bank.setup_ep_interrupts();
662        }
663    }
664
665    /// protocol_reset is called by the USB HAL when it detects the host has
666    /// performed a USB reset.
667    fn protocol_reset(&self) {
668        self.flush_eps(FlushConfigMode::ProtocolReset);
669    }
670
671    fn suspend(&self) {}
672
673    fn resume(&self) {}
674
675    fn alloc_ep(
676        &mut self,
677        dir: UsbDirection,
678        addr: Option<EndpointAddress>,
679        ep_type: EndpointType,
680        max_packet_size: u16,
681        interval: u8,
682    ) -> UsbResult<EndpointAddress> {
683        // The USB hardware encodes the maximum packet size in 3 bits, so
684        // reserve enough buffer that the hardware won't overwrite it even if
685        // the other side issues an overly-long transfer.
686        let allocated_size = match max_packet_size {
687            1..=8 => 8,
688            9..=16 => 16,
689            17..=32 => 32,
690            33..=64 => 64,
691            65..=128 => 128,
692            129..=256 => 256,
693            257..=512 => 512,
694            513..=1023 => 1024,
695            _ => return Err(UsbError::Unsupported),
696        };
697
698        let buffer = self.buffers.borrow_mut().allocate_buffer(allocated_size)?;
699
700        let mut endpoints = self.endpoints.borrow_mut();
701
702        let idx = match addr {
703            None => endpoints.find_free_endpoint(dir)?,
704            Some(addr) => addr.index(),
705        };
706
707        let addr = endpoints.allocate_endpoint(
708            dir,
709            idx,
710            ep_type,
711            allocated_size,
712            max_packet_size,
713            interval,
714            buffer,
715        )?;
716
717        Ok(addr)
718    }
719
720    fn set_device_address(&self, addr: u8) {
721        self.usb()
722            .dadd()
723            .write(|w| unsafe { w.dadd().bits(addr).adden().set_bit() });
724    }
725
726    fn check_sof_interrupt(&self) -> bool {
727        if self.usb().intflag().read().sof().bit() {
728            self.usb().intflag().write(|w| w.sof().set_bit());
729            return true;
730        }
731        false
732    }
733
734    fn poll(&self) -> PollResult {
735        let intflags = self.usb().intflag().read();
736        if intflags.eorst().bit() {
737            // end of reset interrupt
738            self.usb().intflag().write(|w| w.eorst().set_bit());
739            return PollResult::Reset;
740        }
741        // As the suspend & wakup interrupts/states cannot distinguish between
742        // unconnected & unsuspended, we do not handle them to avoid spurious
743        // transitions.
744
745        let mut ep_out = 0;
746        let mut ep_in_complete = 0;
747        let mut ep_setup = 0;
748
749        let intbits = self.usb().epintsmry().read().bits();
750
751        for ep in 0..8u16 {
752            let mask = 1 << ep;
753
754            let idx = ep as usize;
755
756            if (intbits & mask) != 0 {
757                if let Ok(bank1) = self.bank1(EndpointAddress::from_parts(idx, UsbDirection::In)) {
758                    if bank1.is_transfer_complete() {
759                        bank1.clear_transfer_complete();
760                        ep_in_complete |= mask;
761                    }
762                }
763            }
764
765            // Can't test intbits, because bk0rdy doesn't interrupt
766            if let Ok(bank0) = self.bank0(EndpointAddress::from_parts(idx, UsbDirection::Out)) {
767                if bank0.received_setup_interrupt() {
768                    ep_setup |= mask;
769
770                    // The RXSTP interrupt is not cleared here, because doing so
771                    // would allow the USB hardware to overwrite the received
772                    // data, potentially before it is `read()` - see SAMD21
773                    // datasheet "32.6.2.6 Management of SETUP Transactions".
774                    // Setup events are only relevant for control endpoints, and
775                    // in typical USB devices, endpoint 0 is the only control
776                    // endpoint. The usb-device `poll()` method, which calls
777                    // this `poll()`, will immediately `read()` endpoint 0 when
778                    // its setup bit is set.
779                }
780
781                // Clear the transfer complete and transfer failed interrupt flags
782                // so that execution leaves the USB interrupt until the host makes
783                // another transaction.  The transfer failed flag may have been set
784                // if an OUT transaction wasn't read() from the endpoint by the
785                // Class; the hardware will have NAKed (unless the endpoint is
786                // isochronous) and the host may retry.
787                bank0.clear_transfer_complete();
788
789                // Use the bk0rdy flag via is_ready() to indicate that data has been
790                // received successfully, rather than the interrupting trcpt0 via
791                // is_transfer_ready(), because data may have been received on an
792                // earlier poll() which cleared trcpt0.  bk0rdy is cleared in the
793                // endpoint read().
794                if bank0.is_ready() {
795                    ep_out |= mask;
796                }
797            }
798        }
799
800        if ep_out == 0 && ep_in_complete == 0 && ep_setup == 0 {
801            PollResult::None
802        } else {
803            PollResult::Data {
804                ep_out,
805                ep_in_complete,
806                ep_setup,
807            }
808        }
809    }
810
811    fn write(&self, ep: EndpointAddress, buf: &[u8]) -> UsbResult<usize> {
812        let mut bank = self.bank1(ep)?;
813
814        if bank.is_ready() {
815            // Waiting for the host to pick up the existing data
816            return Err(UsbError::WouldBlock);
817        }
818
819        let size = bank.write(buf);
820
821        bank.clear_transfer_complete();
822        bank.set_ready(true); // ready to be sent
823
824        size
825    }
826
827    fn read(&self, ep: EndpointAddress, buf: &mut [u8]) -> UsbResult<usize> {
828        let mut bank = self.bank0(ep)?;
829        let rxstp = bank.received_setup_interrupt();
830
831        if bank.is_ready() || rxstp {
832            let size = bank.read(buf);
833
834            if rxstp {
835                bank.clear_received_setup_interrupt();
836            }
837
838            bank.clear_transfer_complete();
839            bank.set_ready(false);
840
841            size
842        } else {
843            Err(UsbError::WouldBlock)
844        }
845    }
846
847    fn is_stalled(&self, ep: EndpointAddress) -> bool {
848        if ep.is_out() {
849            self.bank0(ep).unwrap().is_stalled()
850        } else {
851            self.bank1(ep).unwrap().is_stalled()
852        }
853    }
854
855    fn set_stalled(&self, ep: EndpointAddress, stalled: bool) {
856        self.set_stall(ep, stalled);
857    }
858}
859
860impl UsbBus {
861    /// Enables the Start Of Frame (SOF) interrupt
862    pub fn enable_sof_interrupt(&self) {
863        disable_interrupts(|cs| self.inner.borrow(cs).borrow_mut().sof_interrupt(true))
864    }
865
866    /// Disables the Start Of Frame (SOF) interrupt
867    pub fn disable_sof_interrupt(&self) {
868        disable_interrupts(|cs| self.inner.borrow(cs).borrow_mut().sof_interrupt(false))
869    }
870
871    /// Checks, and clears if set, the Start Of Frame (SOF) interrupt flag
872    pub fn check_sof_interrupt(&self) -> bool {
873        disable_interrupts(|cs| self.inner.borrow(cs).borrow_mut().check_sof_interrupt())
874    }
875}
876
877impl usb_device::bus::UsbBus for UsbBus {
878    fn enable(&mut self) {
879        disable_interrupts(|cs| self.inner.borrow(cs).borrow_mut().enable())
880    }
881
882    fn reset(&self) {
883        disable_interrupts(|cs| self.inner.borrow(cs).borrow().protocol_reset())
884    }
885
886    fn suspend(&self) {
887        disable_interrupts(|cs| self.inner.borrow(cs).borrow().suspend())
888    }
889
890    fn resume(&self) {
891        disable_interrupts(|cs| self.inner.borrow(cs).borrow().resume())
892    }
893
894    fn alloc_ep(
895        &mut self,
896        dir: UsbDirection,
897        addr: Option<EndpointAddress>,
898        ep_type: EndpointType,
899        max_packet_size: u16,
900        interval: u8,
901    ) -> UsbResult<EndpointAddress> {
902        disable_interrupts(|cs| {
903            self.inner.borrow(cs).borrow_mut().alloc_ep(
904                dir,
905                addr,
906                ep_type,
907                max_packet_size,
908                interval,
909            )
910        })
911    }
912
913    fn set_device_address(&self, addr: u8) {
914        disable_interrupts(|cs| self.inner.borrow(cs).borrow().set_device_address(addr))
915    }
916
917    fn poll(&self) -> PollResult {
918        disable_interrupts(|cs| self.inner.borrow(cs).borrow().poll())
919    }
920
921    fn write(&self, ep: EndpointAddress, buf: &[u8]) -> UsbResult<usize> {
922        disable_interrupts(|cs| self.inner.borrow(cs).borrow().write(ep, buf))
923    }
924
925    fn read(&self, ep: EndpointAddress, buf: &mut [u8]) -> UsbResult<usize> {
926        disable_interrupts(|cs| self.inner.borrow(cs).borrow().read(ep, buf))
927    }
928
929    fn set_stalled(&self, ep: EndpointAddress, stalled: bool) {
930        disable_interrupts(|cs| self.inner.borrow(cs).borrow().set_stalled(ep, stalled))
931    }
932
933    fn is_stalled(&self, ep: EndpointAddress) -> bool {
934        disable_interrupts(|cs| self.inner.borrow(cs).borrow().is_stalled(ep))
935    }
936}