use super::Descriptors;
use crate::calibration::{usb_transn_cal, usb_transp_cal, usb_trim_cal};
use crate::clock;
use crate::gpio::{AlternateG, AnyPin, Pin, PA24, PA25};
use crate::pac::usb::Device;
use crate::pac::{Pm, Usb};
use crate::usb::devicedesc::DeviceDescBank;
use atsamd_hal_macros::{hal_cfg, hal_macro_helper};
use core::cell::{Ref, RefCell, RefMut};
use core::marker::PhantomData;
use core::mem;
use cortex_m::singleton;
use critical_section::{with as disable_interrupts, Mutex};
use usb_device::bus::PollResult;
use usb_device::endpoint::{EndpointAddress, EndpointType};
use usb_device::{Result as UsbResult, UsbDirection, UsbError};
#[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
pub enum EndpointTypeBits {
#[default]
Disabled = 0,
Control = 1,
Isochronous = 2,
Bulk = 3,
Interrupt = 4,
#[allow(unused)]
DualBank = 5,
}
impl From<EndpointType> for EndpointTypeBits {
fn from(ep_type: EndpointType) -> EndpointTypeBits {
match ep_type {
EndpointType::Control => EndpointTypeBits::Control,
EndpointType::Isochronous { .. } => EndpointTypeBits::Isochronous,
EndpointType::Bulk => EndpointTypeBits::Bulk,
EndpointType::Interrupt => EndpointTypeBits::Interrupt,
}
}
}
#[derive(Default, Clone, Copy)]
struct EPConfig {
ep_type: EndpointTypeBits,
allocated_size: u16,
max_packet_size: u16,
addr: usize,
}
impl EPConfig {
fn new(
ep_type: EndpointType,
allocated_size: u16,
max_packet_size: u16,
buffer_addr: *mut u8,
) -> Self {
Self {
ep_type: ep_type.into(),
allocated_size,
max_packet_size,
addr: buffer_addr as usize,
}
}
}
#[derive(Default)]
struct EndpointInfo {
bank0: EPConfig,
bank1: EPConfig,
}
impl EndpointInfo {
fn new() -> Self {
Default::default()
}
}
struct AllEndpoints {
endpoints: [EndpointInfo; 8],
}
impl AllEndpoints {
fn new() -> Self {
Self {
endpoints: [
EndpointInfo::new(),
EndpointInfo::new(),
EndpointInfo::new(),
EndpointInfo::new(),
EndpointInfo::new(),
EndpointInfo::new(),
EndpointInfo::new(),
EndpointInfo::new(),
],
}
}
fn find_free_endpoint(&self, dir: UsbDirection) -> UsbResult<usize> {
for idx in 1..8 {
let ep_type = match dir {
UsbDirection::Out => self.endpoints[idx].bank0.ep_type,
UsbDirection::In => self.endpoints[idx].bank1.ep_type,
};
if ep_type == EndpointTypeBits::Disabled {
return Ok(idx);
}
}
Err(UsbError::EndpointOverflow)
}
#[allow(clippy::too_many_arguments)]
fn allocate_endpoint(
&mut self,
dir: UsbDirection,
idx: usize,
ep_type: EndpointType,
allocated_size: u16,
max_packet_size: u16,
_interval: u8,
buffer_addr: *mut u8,
) -> UsbResult<EndpointAddress> {
let bank = match dir {
UsbDirection::Out => &mut self.endpoints[idx].bank0,
UsbDirection::In => &mut self.endpoints[idx].bank1,
};
if bank.ep_type != EndpointTypeBits::Disabled {
return Err(UsbError::EndpointOverflow);
}
*bank = EPConfig::new(ep_type, allocated_size, max_packet_size, buffer_addr);
Ok(EndpointAddress::from_parts(idx, dir))
}
}
const BUFFER_SIZE: usize = 2048;
fn buffer() -> &'static mut [u8; BUFFER_SIZE] {
singleton!(: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE] ).unwrap()
}
struct BufferAllocator {
buffers: &'static mut [u8; BUFFER_SIZE],
next_buf: u16,
}
impl BufferAllocator {
fn new() -> Self {
Self {
next_buf: 0,
buffers: buffer(),
}
}
fn allocate_buffer(&mut self, size: u16) -> UsbResult<*mut u8> {
debug_assert!(size & 1 == 0);
let start_addr = &mut self.buffers[self.next_buf as usize] as *mut u8;
let buf_end = unsafe { start_addr.add(BUFFER_SIZE) };
let offset = start_addr.align_offset(mem::align_of::<u32>());
let start_addr = unsafe { start_addr.add(offset) };
if start_addr >= buf_end {
return Err(UsbError::EndpointMemoryOverflow);
}
let end_addr = unsafe { start_addr.offset(size as isize) };
if end_addr > buf_end {
return Err(UsbError::EndpointMemoryOverflow);
}
self.next_buf = unsafe { end_addr.sub(self.buffers.as_ptr() as usize) as u16 };
Ok(start_addr)
}
}
struct Inner {
desc: RefCell<Descriptors>,
_dm_pad: Pin<PA24, AlternateG>,
_dp_pad: Pin<PA25, AlternateG>,
endpoints: RefCell<AllEndpoints>,
buffers: RefCell<BufferAllocator>,
}
pub struct UsbBus {
inner: Mutex<RefCell<Inner>>,
}
struct Bank<'a, T> {
address: EndpointAddress,
usb: &'a Device,
desc: RefMut<'a, super::Descriptors>,
_phantom: PhantomData<T>,
endpoints: Ref<'a, AllEndpoints>,
}
impl<T> Bank<'_, T> {
fn usb(&self) -> &Device {
self.usb
}
#[inline]
fn index(&self) -> usize {
self.address.index()
}
#[inline]
fn config(&mut self) -> &EPConfig {
let ep = &self.endpoints.endpoints[self.address.index()];
if self.address.is_out() {
&ep.bank0
} else {
&ep.bank1
}
}
}
struct InBank;
struct OutBank;
impl Bank<'_, InBank> {
fn desc_bank(&mut self) -> &mut DeviceDescBank {
let idx = self.index();
self.desc.bank(idx, 1)
}
#[inline]
fn is_ready(&self) -> bool {
self.usb().epstatus(self.index()).read().bk1rdy().bit()
}
#[inline]
fn set_ready(&self, ready: bool) {
if ready {
self.usb()
.epstatusset(self.index())
.write(|w| w.bk1rdy().set_bit());
} else {
self.usb()
.epstatusclr(self.index())
.write(|w| w.bk1rdy().set_bit());
}
}
#[inline]
fn clear_transfer_complete(&self) {
self.usb()
.epintflag(self.index())
.write(|w| w.trcpt1().set_bit().trfail1().set_bit());
}
#[inline]
fn is_transfer_complete(&self) -> bool {
self.usb().epintflag(self.index()).read().trcpt1().bit()
}
fn flush_config(&mut self) {
let config = *self.config();
{
let desc = self.desc_bank();
desc.set_address(config.addr as *mut u8);
desc.set_endpoint_size(config.max_packet_size);
desc.set_multi_packet_size(0);
desc.set_byte_count(0);
}
}
fn setup_ep_interrupts(&mut self) {
self.usb()
.epintenset(self.index())
.write(|w| w.trcpt1().set_bit());
}
pub fn write(&mut self, buf: &[u8]) -> UsbResult<usize> {
let size = buf.len().min(self.config().allocated_size as usize);
let desc = self.desc_bank();
unsafe {
buf.as_ptr()
.copy_to_nonoverlapping(desc.get_address(), size);
}
desc.set_multi_packet_size(0);
desc.set_byte_count(size as u16);
Ok(size)
}
fn is_stalled(&self) -> bool {
self.usb().epintflag(self.index()).read().stall1().bit()
}
fn set_stall(&mut self, stall: bool) {
if stall {
self.usb()
.epstatusset(self.index())
.write(|w| w.stallrq1().set_bit())
} else {
self.usb()
.epstatusclr(self.index())
.write(|w| w.stallrq1().set_bit())
}
}
}
impl Bank<'_, OutBank> {
fn desc_bank(&mut self) -> &mut DeviceDescBank {
let idx = self.index();
self.desc.bank(idx, 0)
}
#[inline]
fn is_ready(&self) -> bool {
self.usb().epstatus(self.index()).read().bk0rdy().bit()
}
#[inline]
fn set_ready(&self, ready: bool) {
if ready {
self.usb()
.epstatusset(self.index())
.write(|w| w.bk0rdy().set_bit());
} else {
self.usb()
.epstatusclr(self.index())
.write(|w| w.bk0rdy().set_bit());
}
}
#[inline]
fn clear_transfer_complete(&self) {
self.usb()
.epintflag(self.index())
.write(|w| w.trcpt0().set_bit().trfail0().set_bit());
}
#[inline]
fn received_setup_interrupt(&self) -> bool {
self.usb().epintflag(self.index()).read().rxstp().bit()
}
#[inline]
fn clear_received_setup_interrupt(&self) {
self.usb()
.epintflag(self.index())
.write(|w| w.rxstp().set_bit());
}
fn flush_config(&mut self) {
let config = *self.config();
{
let desc = self.desc_bank();
desc.set_address(config.addr as *mut u8);
desc.set_endpoint_size(config.max_packet_size);
desc.set_multi_packet_size(0);
desc.set_byte_count(0);
}
}
fn setup_ep_interrupts(&mut self) {
self.usb()
.epintenset(self.index())
.write(|w| w.rxstp().set_bit().trcpt0().set_bit());
}
pub fn read(&mut self, buf: &mut [u8]) -> UsbResult<usize> {
let desc = self.desc_bank();
let size = desc.get_byte_count() as usize;
if size > buf.len() {
return Err(UsbError::BufferOverflow);
}
unsafe {
desc.get_address()
.copy_to_nonoverlapping(buf.as_mut_ptr(), size);
}
desc.set_byte_count(0);
desc.set_multi_packet_size(0);
Ok(size)
}
fn is_stalled(&self) -> bool {
self.usb().epintflag(self.index()).read().stall0().bit()
}
fn set_stall(&mut self, stall: bool) {
if stall {
self.usb()
.epstatusset(self.index())
.write(|w| w.stallrq0().set_bit())
} else {
self.usb()
.epstatusclr(self.index())
.write(|w| w.stallrq0().set_bit())
}
}
}
impl Inner {
fn bank0(&'_ self, ep: EndpointAddress) -> UsbResult<Bank<'_, OutBank>> {
if ep.is_in() {
return Err(UsbError::InvalidEndpoint);
}
let endpoints = self.endpoints.borrow();
if endpoints.endpoints[ep.index()].bank0.ep_type == EndpointTypeBits::Disabled {
return Err(UsbError::InvalidEndpoint);
}
Ok(Bank {
address: ep,
usb: self.usb(),
desc: self.desc.borrow_mut(),
endpoints,
_phantom: PhantomData,
})
}
fn bank1(&'_ self, ep: EndpointAddress) -> UsbResult<Bank<'_, InBank>> {
if ep.is_out() {
return Err(UsbError::InvalidEndpoint);
}
let endpoints = self.endpoints.borrow();
if endpoints.endpoints[ep.index()].bank1.ep_type == EndpointTypeBits::Disabled {
return Err(UsbError::InvalidEndpoint);
}
Ok(Bank {
address: ep,
usb: self.usb(),
desc: self.desc.borrow_mut(),
endpoints,
_phantom: PhantomData,
})
}
}
impl UsbBus {
pub fn new(
_clock: &clock::UsbClock,
pm: &mut Pm,
dm_pad: impl AnyPin<Id = PA24>,
dp_pad: impl AnyPin<Id = PA25>,
_usb: Usb,
) -> Self {
pm.apbbmask().modify(|_, w| w.usb_().set_bit());
let desc = RefCell::new(Descriptors::new());
let inner = Inner {
_dm_pad: dm_pad.into().into_mode::<AlternateG>(),
_dp_pad: dp_pad.into().into_mode::<AlternateG>(),
desc,
buffers: RefCell::new(BufferAllocator::new()),
endpoints: RefCell::new(AllEndpoints::new()),
};
Self {
inner: Mutex::new(RefCell::new(inner)),
}
}
}
impl Inner {
#[hal_cfg("usb-d11")]
fn usb(&self) -> &Device {
unsafe { (*Usb::ptr()).device() }
}
#[hal_cfg("usb-d21")]
fn usb(&self) -> &Device {
unsafe { (*Usb::ptr()).device() }
}
fn set_stall<EP: Into<EndpointAddress>>(&self, ep: EP, stall: bool) {
let ep = ep.into();
if ep.is_out() {
if let Ok(mut bank) = self.bank0(ep) {
bank.set_stall(stall);
}
} else if let Ok(mut bank) = self.bank1(ep) {
bank.set_stall(stall);
}
}
}
#[derive(Copy, Clone)]
enum FlushConfigMode {
Full,
ProtocolReset,
}
impl Inner {
#[hal_macro_helper]
fn enable(&mut self) {
let usb = self.usb();
usb.ctrla().modify(|_, w| w.swrst().set_bit());
while usb.syncbusy().read().swrst().bit_is_set() {}
let addr = self.desc.borrow().address();
usb.descadd().write(|w| unsafe { w.descadd().bits(addr) });
usb.padcal().modify(|_, w| unsafe {
w.transn().bits(usb_transn_cal());
w.transp().bits(usb_transp_cal());
w.trim().bits(usb_trim_cal())
});
#[hal_cfg("usb-d11")]
usb.qosctrl().modify(|_, w| unsafe {
w.dqos().bits(0b11);
w.cqos().bits(0b11)
});
#[hal_cfg("usb-d21")]
usb.qosctrl().modify(|_, w| unsafe {
w.dqos().bits(0b11);
w.cqos().bits(0b11)
});
usb.ctrla().modify(|_, w| {
w.mode().device();
w.runstdby().set_bit()
});
usb.ctrlb().modify(|_, w| w.spdconf().fs());
usb.ctrla().modify(|_, w| w.enable().set_bit());
while usb.syncbusy().read().enable().bit_is_set() {}
usb.intflag()
.write(|w| unsafe { w.bits(usb.intflag().read().bits()) });
usb.intenset().write(|w| w.eorst().set_bit());
self.flush_eps(FlushConfigMode::Full);
usb.ctrlb().modify(|_, w| w.detach().clear_bit());
}
fn sof_interrupt(&self, enable: bool) {
if enable {
self.usb().intenset().write(|w| w.sof().set_bit());
} else {
self.usb().intenclr().write(|w| w.sof().set_bit());
}
}
fn flush_eps(&self, mode: FlushConfigMode) {
for idx in 0..8 {
match (mode, idx) {
(FlushConfigMode::ProtocolReset, 0) => {
self.setup_ep_interrupts(EndpointAddress::from_parts(idx, UsbDirection::Out));
self.setup_ep_interrupts(EndpointAddress::from_parts(idx, UsbDirection::In));
}
(FlushConfigMode::Full, _) | (FlushConfigMode::ProtocolReset, _) => {
self.flush_ep(idx);
self.setup_ep_interrupts(EndpointAddress::from_parts(idx, UsbDirection::Out));
self.setup_ep_interrupts(EndpointAddress::from_parts(idx, UsbDirection::In));
}
}
}
}
fn flush_ep(&self, idx: usize) {
let cfg = self.usb().epcfg(idx);
let info = &self.endpoints.borrow().endpoints[idx];
if let Ok(mut bank) = self.bank0(EndpointAddress::from_parts(idx, UsbDirection::Out)) {
bank.flush_config();
}
if let Ok(mut bank) = self.bank1(EndpointAddress::from_parts(idx, UsbDirection::In)) {
bank.flush_config();
}
cfg.modify(|_, w| unsafe {
w.eptype0()
.bits(info.bank0.ep_type as u8)
.eptype1()
.bits(info.bank1.ep_type as u8)
});
}
fn setup_ep_interrupts(&self, ep_addr: EndpointAddress) {
if ep_addr.is_out() {
if let Ok(mut bank) = self.bank0(ep_addr) {
bank.setup_ep_interrupts();
}
} else if let Ok(mut bank) = self.bank1(ep_addr) {
bank.setup_ep_interrupts();
}
}
fn protocol_reset(&self) {
self.flush_eps(FlushConfigMode::ProtocolReset);
}
fn suspend(&self) {}
fn resume(&self) {}
fn alloc_ep(
&mut self,
dir: UsbDirection,
addr: Option<EndpointAddress>,
ep_type: EndpointType,
max_packet_size: u16,
interval: u8,
) -> UsbResult<EndpointAddress> {
let allocated_size = match max_packet_size {
1..=8 => 8,
9..=16 => 16,
17..=32 => 32,
33..=64 => 64,
65..=128 => 128,
129..=256 => 256,
257..=512 => 512,
513..=1023 => 1024,
_ => return Err(UsbError::Unsupported),
};
let buffer = self.buffers.borrow_mut().allocate_buffer(allocated_size)?;
let mut endpoints = self.endpoints.borrow_mut();
let idx = match addr {
None => endpoints.find_free_endpoint(dir)?,
Some(addr) => addr.index(),
};
let addr = endpoints.allocate_endpoint(
dir,
idx,
ep_type,
allocated_size,
max_packet_size,
interval,
buffer,
)?;
Ok(addr)
}
fn set_device_address(&self, addr: u8) {
self.usb()
.dadd()
.write(|w| unsafe { w.dadd().bits(addr).adden().set_bit() });
}
fn check_sof_interrupt(&self) -> bool {
if self.usb().intflag().read().sof().bit() {
self.usb().intflag().write(|w| w.sof().set_bit());
return true;
}
false
}
fn poll(&self) -> PollResult {
let intflags = self.usb().intflag().read();
if intflags.eorst().bit() {
self.usb().intflag().write(|w| w.eorst().set_bit());
return PollResult::Reset;
}
let mut ep_out = 0;
let mut ep_in_complete = 0;
let mut ep_setup = 0;
let intbits = self.usb().epintsmry().read().bits();
for ep in 0..8u16 {
let mask = 1 << ep;
let idx = ep as usize;
if (intbits & mask) != 0 {
if let Ok(bank1) = self.bank1(EndpointAddress::from_parts(idx, UsbDirection::In)) {
if bank1.is_transfer_complete() {
bank1.clear_transfer_complete();
ep_in_complete |= mask;
}
}
}
if let Ok(bank0) = self.bank0(EndpointAddress::from_parts(idx, UsbDirection::Out)) {
if bank0.received_setup_interrupt() {
ep_setup |= mask;
}
bank0.clear_transfer_complete();
if bank0.is_ready() {
ep_out |= mask;
}
}
}
if ep_out == 0 && ep_in_complete == 0 && ep_setup == 0 {
PollResult::None
} else {
PollResult::Data {
ep_out,
ep_in_complete,
ep_setup,
}
}
}
fn write(&self, ep: EndpointAddress, buf: &[u8]) -> UsbResult<usize> {
let mut bank = self.bank1(ep)?;
if bank.is_ready() {
return Err(UsbError::WouldBlock);
}
let size = bank.write(buf);
bank.clear_transfer_complete();
bank.set_ready(true); size
}
fn read(&self, ep: EndpointAddress, buf: &mut [u8]) -> UsbResult<usize> {
let mut bank = self.bank0(ep)?;
let rxstp = bank.received_setup_interrupt();
if bank.is_ready() || rxstp {
let size = bank.read(buf);
if rxstp {
bank.clear_received_setup_interrupt();
}
bank.clear_transfer_complete();
bank.set_ready(false);
size
} else {
Err(UsbError::WouldBlock)
}
}
fn is_stalled(&self, ep: EndpointAddress) -> bool {
if ep.is_out() {
self.bank0(ep).unwrap().is_stalled()
} else {
self.bank1(ep).unwrap().is_stalled()
}
}
fn set_stalled(&self, ep: EndpointAddress, stalled: bool) {
self.set_stall(ep, stalled);
}
}
impl UsbBus {
pub fn enable_sof_interrupt(&self) {
disable_interrupts(|cs| self.inner.borrow(cs).borrow_mut().sof_interrupt(true))
}
pub fn disable_sof_interrupt(&self) {
disable_interrupts(|cs| self.inner.borrow(cs).borrow_mut().sof_interrupt(false))
}
pub fn check_sof_interrupt(&self) -> bool {
disable_interrupts(|cs| self.inner.borrow(cs).borrow_mut().check_sof_interrupt())
}
}
impl usb_device::bus::UsbBus for UsbBus {
fn enable(&mut self) {
disable_interrupts(|cs| self.inner.borrow(cs).borrow_mut().enable())
}
fn reset(&self) {
disable_interrupts(|cs| self.inner.borrow(cs).borrow().protocol_reset())
}
fn suspend(&self) {
disable_interrupts(|cs| self.inner.borrow(cs).borrow().suspend())
}
fn resume(&self) {
disable_interrupts(|cs| self.inner.borrow(cs).borrow().resume())
}
fn alloc_ep(
&mut self,
dir: UsbDirection,
addr: Option<EndpointAddress>,
ep_type: EndpointType,
max_packet_size: u16,
interval: u8,
) -> UsbResult<EndpointAddress> {
disable_interrupts(|cs| {
self.inner.borrow(cs).borrow_mut().alloc_ep(
dir,
addr,
ep_type,
max_packet_size,
interval,
)
})
}
fn set_device_address(&self, addr: u8) {
disable_interrupts(|cs| self.inner.borrow(cs).borrow().set_device_address(addr))
}
fn poll(&self) -> PollResult {
disable_interrupts(|cs| self.inner.borrow(cs).borrow().poll())
}
fn write(&self, ep: EndpointAddress, buf: &[u8]) -> UsbResult<usize> {
disable_interrupts(|cs| self.inner.borrow(cs).borrow().write(ep, buf))
}
fn read(&self, ep: EndpointAddress, buf: &mut [u8]) -> UsbResult<usize> {
disable_interrupts(|cs| self.inner.borrow(cs).borrow().read(ep, buf))
}
fn set_stalled(&self, ep: EndpointAddress, stalled: bool) {
disable_interrupts(|cs| self.inner.borrow(cs).borrow().set_stalled(ep, stalled))
}
fn is_stalled(&self, ep: EndpointAddress) -> bool {
disable_interrupts(|cs| self.inner.borrow(cs).borrow().is_stalled(ep))
}
}