refactor!: rewrite almost full library

Now usbd implementation works fine (tested on atmega32u4)
This commit is contained in:
doryan 2024-12-30 21:17:23 +04:00
parent 16812fe119
commit ccb23c8c56
2 changed files with 266 additions and 235 deletions

View File

@ -1,8 +1,8 @@
#![no_std] #![no_std]
use core::cmp::max; use core::{cmp::max, u8};
use avr_device::interrupt::free; use avr_device::{asm::delay_cycles, interrupt::free};
use usb_device::{ use usb_device::{
bus::{PollResult, UsbBus}, bus::{PollResult, UsbBus},
endpoint::{EndpointAddress, EndpointType}, endpoint::{EndpointAddress, EndpointType},
@ -12,7 +12,7 @@ use usb_device::{
mod types; mod types;
pub use types::UsbDevice; pub use types::UsbDevice;
use types::{DPRAM_SIZE, ENDPOINTS_ALLOC_LAYOUT}; use types::{DPRAM_SIZE, ENDPOINTS_ALLOC_LAYOUT, ONE_MS_16_MGHZ};
impl<const L: usize> UsbBus for UsbDevice<L> { impl<const L: usize> UsbBus for UsbDevice<L> {
fn alloc_ep( fn alloc_ep(
@ -25,117 +25,127 @@ impl<const L: usize> UsbBus for UsbDevice<L> {
) -> UsbResult<EndpointAddress> { ) -> UsbResult<EndpointAddress> {
// Handle first endpoint. // // Handle first endpoint. //
if ep_addr == Some(EndpointAddress::from_parts(0, UsbDirection::In)) { if ep_addr == Some(EndpointAddress::from_parts(0, UsbDirection::In)) {
return Ok(ep_addr.unwrap()); Ok(ep_addr.unwrap())
}
let address = match ep_addr {
// If current endpoint doesn't allocated, assign ep_addr to variable. //
Some(ep_addr) if !self.ep_table[ep_addr.index()].is_allocated => ep_addr,
// If ep_aadr not provided, or current endpoint is allocated, try to find next free endpoint, otherwise return UsbError. //
None | Some(_) => {
let endpoint = self
.ep_table
.iter()
.enumerate()
.skip(1)
.find(|(i, &ep)| {
!ep.is_allocated && max_packet_size <= ENDPOINTS_ALLOC_LAYOUT[*i]
})
.ok_or(UsbError::EndpointMemoryOverflow)?;
EndpointAddress::from_parts(endpoint.0, ep_dir)
}
};
// Select endpoint info by address index. //
let target_endpoint = &mut self.ep_table[address.index()];
// Endpoint allocation marker. //
if DPRAM_SIZE - self.dpram_already_used <= max_packet_size || max_packet_size >= 512 {
Err(UsbError::EndpointMemoryOverflow)
} else { } else {
let address = match ep_addr {
// If current endpoint doesn't allocated, assign ep_addr to variable. //
Some(addr) if !self.ep_table[addr.index()].is_allocated => addr,
// If ep_aadr not provided, or current endpoint is allocated, try to find next free endpoint, otherwise return UsbError. //
_ => {
let index = self
.ep_table
.iter()
.enumerate()
.skip(1)
.find(|(index, ep)| {
!ep.is_allocated && max_packet_size <= ENDPOINTS_ALLOC_LAYOUT[*index]
})
.ok_or(UsbError::EndpointOverflow)?
.0;
EndpointAddress::from_parts(index, ep_dir)
}
};
// Select endpoint info by address index. //
let target_endpoint = &mut self.ep_table[address.index()];
// Get power of two number of endpoint size. // // Get power of two number of endpoint size. //
let max_packet_size = max(8, max_packet_size.next_power_of_two()); let ep_size = max(8, max_packet_size.next_power_of_two());
// Set endpoint parameters. // // Endpoint allocation marker. //
target_endpoint.set_size(max_packet_size); if DPRAM_SIZE - self.dpram_already_used < ep_size {
target_endpoint.set_dir(ep_dir); Err(UsbError::EndpointMemoryOverflow)
target_endpoint.set_type(ep_type); } else {
target_endpoint.is_allocated = true; // Set endpoint parameters. //
// Add used dpram memory. // target_endpoint.set_dir(ep_dir);
target_endpoint.set_type(ep_type);
target_endpoint.set_size(ep_size)?;
self.dpram_already_used += max_packet_size; // Add used dpram memory. //
Ok(address) target_endpoint.is_allocated = true;
self.dpram_already_used += ep_size;
Ok(address)
}
} }
} }
fn enable(&mut self) { fn enable(&mut self) {
free(|cs| { free(|cs| {
let (pll, usb) = (self.pll.borrow(cs), self.usb.borrow(cs)); let (usb, pll) = (self.usb.borrow(cs), self.pll.borrow(cs));
// Enable USB pads regulators. // // Enable USB pads regulators. //
usb.uhwcon.modify(|_, w| w.uvrege().set_bit()); usb.uhwcon.modify(|_, w| w.uvrege().set_bit());
// PLL configuration //
pll.pllcsr.write(|w| w.pindiv().set_bit());
pll.pllfrq
.write(|w| w.pdiv().mhz96().plltm().factor_15().pllusb().set_bit());
// Enable PLL //
pll.pllcsr.modify(|_, w| w.plle().set_bit());
// Check PLL lock //
while pll.pllcsr.read().plock().bit_is_clear() {}
// Enable USB interface. // // Enable USB interface. //
usb.usbcon usb.usbcon
.modify(|_, w| w.usbe().set_bit().frzclk().set_bit()); .modify(|_, w| w.usbe().set_bit().otgpade().set_bit());
// Configuring PLL. //
pll.pllfrq
.modify(|_, w| w.pdiv().mhz96().plltm().factor_15().pllusb().set_bit());
// Enable PLL. //
pll.pllcsr
.modify(|_, w| w.pindiv().set_bit().plle().set_bit());
while pll.pllcsr.read().plock().bit_is_clear() {}
// Unfreeze clock. // // Unfreeze clock. //
usb.usbcon usb.usbcon
.modify(|_, w| w.frzclk().clear_bit().otgpade().set_bit()); .modify(|_, w| w.frzclk().clear_bit().vbuste().set_bit());
self.allocated_endpoints().for_each(|(i, _)| { // Endpoint configuration //
self.allocated_endpoints().for_each(|(i, _ep)| {
self.configure_endpoint(cs, i).unwrap(); self.configure_endpoint(cs, i).unwrap();
}); });
// Set high speed and attach the USB. //
usb.udcon.modify(|_, w| w.detach().clear_bit());
// Interrupts. // // Interrupts. //
usb.udien usb.udien
.modify(|_, w| w.eorste().set_bit().sofe().set_bit()); .modify(|_, w| w.eorste().set_bit().sofe().set_bit());
// Set high speed and attach the USB. //
usb.udcon
.modify(|_, w| w.lsm().set_bit().detach().clear_bit());
}) })
} }
fn force_reset(&self) -> UsbResult<()> { fn force_reset(&self) -> UsbResult<()> {
free(|cs| { free(|cs| {
let usb = self.usb.borrow(cs); let usbcon = &self.usb.borrow(cs).usbcon;
usbcon.modify(|_, w| w.usbe().set_bit());
});
usb.usbcon.modify(|_, w| w.usbe().clear_bit()); delay_cycles(ONE_MS_16_MGHZ);
usb.usbcon.modify(|_, w| w.usbe().set_bit());
Ok(()) free(|cs| {
}) let usbcon = &self.usb.borrow(cs).usbcon;
usbcon.modify(|_, w| w.usbe().set_bit());
});
Ok(())
} }
fn is_stalled(&self, ep_addr: EndpointAddress) -> bool { fn is_stalled(&self, ep_addr: EndpointAddress) -> bool {
free(|cs| match self.select_endpoint(cs, ep_addr.index()) { free(|cs| match self.select_endpoint(cs, ep_addr.index()) {
Ok(_) => self.usb.borrow(cs).ueconx.read().stallrq().bit_is_clear(), Ok(_) => self.usb.borrow(cs).ueconx.read().stallrq().bit_is_set(),
Err(_) => false, Err(_) => false,
}) })
} }
@ -144,7 +154,8 @@ impl<const L: usize> UsbBus for UsbDevice<L> {
free(|cs| { free(|cs| {
let usb = self.usb.borrow(cs); let usb = self.usb.borrow(cs);
let (usbint, udint, udien) = (usb.usbint.read(), usb.udint.read(), usb.udien.read()); let (udint, udien, usbint) = (usb.udint.read(), usb.udien.read(), usb.usbint.read());
if usbint.vbusti().bit_is_set() { if usbint.vbusti().bit_is_set() {
usb.usbint.write(|w| w.vbusti().clear_bit()); usb.usbint.write(|w| w.vbusti().clear_bit());
if usb.usbsta.read().vbus().bit_is_set() { if usb.usbsta.read().vbus().bit_is_set() {
@ -153,50 +164,54 @@ impl<const L: usize> UsbBus for UsbDevice<L> {
return PollResult::Suspend; return PollResult::Suspend;
} }
} }
if udint.suspi().bit_is_set() && udien.suspe().bit_is_set() { if udint.suspi().bit_is_set() && udien.suspe().bit_is_set() {
return PollResult::Suspend; return PollResult::Suspend;
} }
if udint.wakeupi().bit_is_set() && udien.wakeupe().bit_is_set() { if udint.wakeupi().bit_is_set() && udien.wakeupe().bit_is_set() {
return PollResult::Resume; return PollResult::Resume;
} }
if udint.eorsti().bit_is_set() { if udint.eorsti().bit_is_set() {
return PollResult::Reset; return PollResult::Reset;
} }
if udint.sofi().bit_is_set() { if udint.sofi().bit_is_set() {
usb.udint.write(|w| w.sofi().clear_bit()); usb.udint.write(|w| w.sofi().clear_bit());
} }
// Can only query endpoints while clock is running
// (e.g. not in suspend state)
if usb.usbcon.read().frzclk().bit_is_clear() { if usb.usbcon.read().frzclk().bit_is_clear() {
let (mut ep_out, mut ep_setup, mut ep_in_complete) = (0u8, 0u8, 0u8); let (mut ep_out, mut ep_in_complete, mut ep_setup) = (0u16, 0u16, 0u16);
let pending_ins = self.pending_ins.borrow(cs);
for (index, _ep) in self.allocated_endpoints() { for (ep_index, _ep) in self.allocated_endpoints() {
if self.select_endpoint(cs, index).is_err() { if self.select_endpoint(cs, ep_index).is_err() {
// Endpoint selection has stopped working...
break; break;
} } else {
let ueintx = usb.ueintx.read();
let ueintx = usb.ueintx.read(); if ueintx.rxouti().bit_is_set() {
if ueintx.rxouti().bit_is_set() { ep_out |= 1 << ep_index;
ep_out |= 1 << index; }
} if ueintx.rxstpi().bit_is_set() {
if ueintx.rxstpi().bit_is_set() { ep_setup |= 1 << ep_index;
ep_setup |= 1 << index; }
}
if ueintx.txini().bit_is_set() { if pending_ins.get() & (1 << ep_index) != 0 && ueintx.txini().bit_is_set() {
ep_in_complete |= 1 << index; ep_in_complete |= 1 << ep_index;
pending_ins.set(pending_ins.get() & !(1 << ep_index));
}
} }
} }
if ep_out | ep_setup | ep_in_complete != 0 { if ep_out | ep_in_complete | ep_setup != 0 {
return PollResult::Data { return PollResult::Data {
ep_out: ep_out as u16, ep_out,
ep_in_complete: ep_in_complete as u16, ep_in_complete,
ep_setup: ep_setup as u16, ep_setup,
}; };
} }
} }
PollResult::None PollResult::None
}) })
} }
@ -205,53 +220,53 @@ impl<const L: usize> UsbBus for UsbDevice<L> {
free(|cs| { free(|cs| {
let usb = self.usb.borrow(cs); let usb = self.usb.borrow(cs);
match self.select_endpoint(cs, ep_addr.index()) { if let Err(error) = self.select_endpoint(cs, ep_addr.index()) {
Ok(()) => { Err(error)
let target_endpoint = self.ep_table[ep_addr.index()]; } else {
let ep = &self.ep_table[ep_addr.index()];
if ep.ep_type == 0 {
let ueintx = usb.ueintx.read(); let ueintx = usb.ueintx.read();
if ueintx.rxouti().bit_is_clear() { if ueintx.rxouti().bit_is_clear() && ueintx.rxstpi().bit_is_clear() {
return Err(UsbError::WouldBlock); return Err(UsbError::WouldBlock);
} }
if target_endpoint.ep_type == 0 { let buf_size = self.get_size(cs);
let bytes_count_to_read: usize = (usb.uebchx.read().bits() as usize) << 8 if buf.len() < buf_size {
| (usb.uebclx.read().bits() as usize); return Err(UsbError::BufferOverflow);
if bytes_count_to_read > buf.len() {
return Err(UsbError::BufferOverflow);
}
for slot in &mut buf[..bytes_count_to_read] {
*slot = usb.uedatx.read().bits();
}
usb.ueintx
.write(|w| w.rxouti().clear_bit().rxstpi().clear_bit());
Ok(bytes_count_to_read)
} else {
usb.ueintx.write(|w| w.rxouti().clear_bit());
let mut bytes_read = 0;
for slot in buf {
if usb.ueintx.read().rwal().bit_is_clear() {
break;
}
*slot = usb.uedatx.read().bits();
bytes_read += 1;
}
if usb.ueintx.read().rwal().bit_is_set() {
return Err(UsbError::BufferOverflow);
}
usb.ueintx.write(|w| w.fifocon().clear_bit());
Ok(bytes_read)
} }
for byte in &mut buf[..buf_size] {
*byte = usb.uedatx.read().bits();
}
usb.ueintx
.write(|w| w.rxouti().clear_bit().rxstpi().clear_bit());
Ok(buf_size)
} else {
if usb.ueintx.read().rxouti().bit_is_clear() {
return Err(UsbError::WouldBlock);
}
usb.ueintx.write(|w| w.rxouti().clear_bit());
let mut bytes_read = 0;
for slot in buf {
if usb.ueintx.read().rwal().bit_is_clear() {
break;
}
*slot = usb.uedatx.read().bits();
bytes_read += 1;
}
if usb.ueintx.read().rwal().bit_is_set() {
return Err(UsbError::BufferOverflow);
}
usb.ueintx.write(|w| w.fifocon().clear_bit());
Ok(bytes_read)
} }
Err(err) => Err(err),
} }
}) })
} }
@ -262,30 +277,15 @@ impl<const L: usize> UsbBus for UsbDevice<L> {
usb.udint.modify(|_, w| w.eorsti().clear_bit()); usb.udint.modify(|_, w| w.eorsti().clear_bit());
// Disabling all endpoints before it reset //
self.ep_table
.iter()
.filter(|&&ep| ep.is_allocated)
.enumerate()
.for_each(|(index, _ep)| {
if self.select_endpoint(cs, index).is_ok() {
usb.ueconx.modify(|_, w| w.epen().clear_bit());
}
});
self.allocated_endpoints().for_each(|(i, _)| { self.allocated_endpoints().for_each(|(i, _)| {
self.configure_endpoint(cs, i).unwrap(); self.configure_endpoint(cs, i).unwrap();
}); });
// Reset endpoints //
usb.uerst.modify(|_, w| unsafe { w.bits(u8::MAX >> 1) });
// Clear resume informations. // // Clear resume informations. //
usb.udint usb.udint
.modify(|_, w| w.wakeupi().clear_bit().suspi().clear_bit()); .write(|w| w.wakeupi().clear_bit().suspi().clear_bit());
usb.udien usb.udien
.modify(|_, w| w.wakeupe().clear_bit().suspe().set_bit()); .modify(|_, w| w.wakeupe().clear_bit().suspe().set_bit());
}) })
@ -293,23 +293,21 @@ impl<const L: usize> UsbBus for UsbDevice<L> {
fn resume(&self) { fn resume(&self) {
free(|cs| { free(|cs| {
let usb = self.usb.borrow(cs); let (usb, pll) = (self.usb.borrow(cs), self.pll.borrow(cs));
let pll = self.pll.borrow(cs);
// Enable PLL and wait PLL lock. // // PLL enable //
pll.pllcsr.modify(|_, w| w.plle().set_bit()); pll.pllcsr
.modify(|_, w| w.pindiv().set_bit().plle().set_bit());
while pll.pllcsr.read().plock().bit_is_clear() {} while pll.pllcsr.read().plock().bit_is_clear() {}
// Unfreeze USB clock. // // Resuming //
usb.usbcon.modify(|_, w| w.frzclk().clear_bit()); usb.usbcon.modify(|_, w| w.frzclk().clear_bit());
// Clear resume informations. //
usb.udint usb.udint
.modify(|_, w| w.wakeupi().clear_bit().suspi().clear_bit()); .write(|w| w.wakeupi().clear_bit().suspi().clear_bit());
usb.udien usb.udien
.modify(|_, w| w.wakeupe().clear_bit().suspe().set_bit()); .modify(|_, w| w.wakeupe().clear_bit().suspe().set_bit());
@ -345,16 +343,22 @@ impl<const L: usize> UsbBus for UsbDevice<L> {
fn suspend(&self) { fn suspend(&self) {
free(|cs| { free(|cs| {
let usb = self.usb.borrow(cs); let (usb, pll) = (self.usb.borrow(cs), self.pll.borrow(cs));
let pll = self.pll.borrow(cs);
usb.udint usb.udint
.modify(|_, w| w.suspi().clear_bit().wakeupi().clear_bit()); .write(|w| w.wakeupi().clear_bit().suspi().clear_bit());
// Suspend. //
usb.udien usb.udien
.modify(|_, w| w.suspe().clear_bit().wakeupe().clear_bit()); .modify(|_, w| w.wakeupe().set_bit().suspe().clear_bit());
// Freeze clock. //
usb.usbcon.modify(|_, w| w.frzclk().set_bit()); usb.usbcon.modify(|_, w| w.frzclk().set_bit());
// Disable PLL. //
pll.pllcsr.modify(|_, w| w.plle().clear_bit()); pll.pllcsr.modify(|_, w| w.plle().clear_bit());
}) })
} }
@ -363,49 +367,50 @@ impl<const L: usize> UsbBus for UsbDevice<L> {
free(|cs| { free(|cs| {
let usb = self.usb.borrow(cs); let usb = self.usb.borrow(cs);
match self.select_endpoint(cs, ep_addr.index()) { if let Err(error) = self.select_endpoint(cs, ep_addr.index()) {
Ok(()) => { Err(error)
let target_endpoint = self.ep_table[ep_addr.index()]; } else {
let ep = &self.ep_table[ep_addr.index()];
let ueintx = usb.ueintx.read(); // Endpoint type confitions //
if ueintx.rxouti().bit_is_clear() { if ep.ep_type == 0 {
if usb.ueintx.read().txini().bit_is_clear() {
return Err(UsbError::WouldBlock); return Err(UsbError::WouldBlock);
} }
if target_endpoint.ep_type == 0 { if buf.len() > ep.get_size() {
let bytes_count_to_read: usize = (usb.uebchx.read().bits() as usize) << 8 return Err(UsbError::BufferOverflow);
| (usb.uebclx.read().bits() as usize); }
if bytes_count_to_read > buf.len() { for &byte in buf {
usb.uedatx.write(|w| w.bits(byte));
}
usb.ueintx.write(|w| w.txini().clear_bit());
} else {
if usb.ueintx.read().txini().bit_is_clear() {
return Err(UsbError::WouldBlock);
}
usb.ueintx
.write(|w| w.txini().clear_bit().rxouti().clear_bit());
for &byte in buf {
if usb.ueintx.read().rwal().bit_is_set() {
usb.uedatx.write(|w| w.bits(byte));
} else {
return Err(UsbError::BufferOverflow); return Err(UsbError::BufferOverflow);
} }
buf.iter()
.for_each(|&byte| usb.uedatx.write(|w| w.bits(byte)));
usb.ueintx
.write(|w| w.rxouti().clear_bit().rxstpi().clear_bit());
Ok(bytes_count_to_read)
} else {
usb.ueintx
.write(|w| w.txini().clear_bit().rxouti().clear_bit());
for &byte in buf {
if usb.ueintx.read().rwal().bit_is_set() {
return Err(UsbError::BufferOverflow);
} else {
usb.uedatx.write(|w| w.bits(byte));
}
}
usb.ueintx
.write(|w| w.fifocon().clear_bit().rxouti().clear_bit());
Ok(buf.len())
} }
usb.ueintx
.write(|w| w.txini().clear_bit().fifocon().clear_bit());
} }
Err(err) => Err(err),
let pending_ins = self.pending_ins.borrow(cs);
pending_ins.set(pending_ins.get() | 1 << ep_addr.index());
Ok(buf.len())
} }
}) })
} }

View File

@ -1,12 +1,10 @@
use core::cell::Cell;
use avr_device::{ use avr_device::{
atmega32u4::{PLL, USB_DEVICE}, atmega32u4::{PLL, USB_DEVICE},
interrupt::{CriticalSection, Mutex}, interrupt::{CriticalSection, Mutex},
}; };
use usb_device::{ use usb_device::{bus::UsbBusAllocator, endpoint::EndpointType, UsbDirection, UsbError};
bus::UsbBusAllocator,
endpoint::EndpointType,
UsbDirection, UsbError,
};
#[allow(unused)] #[allow(unused)]
#[derive(Default, Copy, Clone)] #[derive(Default, Copy, Clone)]
@ -15,20 +13,16 @@ pub(crate) struct USBEndpoint {
pub(crate) size: u8, pub(crate) size: u8,
pub(crate) ep_type: u8, pub(crate) ep_type: u8,
pub(crate) ep_dir: bool, pub(crate) ep_dir: bool,
pub(crate) banks: u8,
} }
impl USBEndpoint { impl USBEndpoint {
#[inline] #[inline]
pub(crate) fn set_type(&mut self, ep_type: EndpointType) { pub(crate) fn set_type(&mut self, ep_type: EndpointType) {
self.ep_type = match ep_type { self.ep_type = match ep_type {
EndpointType::Control => 0, // 0 = 0b00 EndpointType::Control => 0, // 0b00
EndpointType::Isochronous { EndpointType::Isochronous { .. } => 1, // 0b01
synchronization: _, EndpointType::Bulk => 2, // 0b10
usage: _, EndpointType::Interrupt => 3, // 0b11
} => 1, // 1 = 0b01
EndpointType::Bulk => 2, // 2 = 0b10
EndpointType::Interrupt => 3, // 3 = 0b11
}; };
} }
@ -41,16 +35,35 @@ impl USBEndpoint {
} }
#[inline] #[inline]
pub(crate) fn set_size(&mut self, size: u16) { pub(crate) fn get_size(&self) -> usize {
self.size = match size { match self.size {
8 => 0b000, 0 /* 0b000 */ => 8,
16 => 0b001, 1 /* 0b001 */ => 16,
32 => 0b010, 2 /* 0b010 */ => 32,
64 => 0b011, 3 /* 0b011 */ => 64,
128 => 0b100, 4 /* 0b100 */ => 128,
256 => 0b101, 5 /* 0b101 */ => 256,
512 => 0b110, 6 /* 0b110 */ => 512,
_ => unreachable!(), _ => unreachable!(), // unsupported, check ATMEGA32u4 docs
}
}
#[inline]
pub(crate) fn set_size(&mut self, size: u16) -> Result<(), UsbError> {
if size > 512 {
Err(UsbError::EndpointMemoryOverflow)
} else {
self.size = match size {
8 => 0, // 0b000
16 => 1, // 0b001
32 => 2, // 0b010
64 => 3, // 0b011
128 => 4, // 0b100
256 => 5, // 0b101
512 => 6, // 0b110
_ => unreachable!(), // unsupported, check ATMEGA32u4 docs
};
Ok(())
} }
} }
} }
@ -59,21 +72,30 @@ pub struct UsbDevice<const L: usize> {
pub(crate) pll: Mutex<PLL>, pub(crate) pll: Mutex<PLL>,
pub(crate) usb: Mutex<USB_DEVICE>, pub(crate) usb: Mutex<USB_DEVICE>,
pub(crate) ep_table: [USBEndpoint; L], pub(crate) ep_table: [USBEndpoint; L],
pub(crate) pending_ins: Mutex<Cell<u8>>,
pub(crate) dpram_already_used: u16, pub(crate) dpram_already_used: u16,
} }
pub(crate) const MAX_ENDPOINTS: usize = 7;
pub(crate) const DPRAM_SIZE: u16 = 832; pub(crate) const DPRAM_SIZE: u16 = 832;
pub(crate) const ENDPOINTS_ALLOC_LAYOUT: [u16; 7] = [64, 256, 64, 64, 64, 64, 64]; pub(crate) const ENDPOINTS_ALLOC_LAYOUT: [u16; MAX_ENDPOINTS] = [64, 256, 64, 64, 64, 64, 64];
pub(crate) const ONE_MS_16_MGHZ: u32 = 16000;
impl<const L: usize> UsbDevice<L> { impl<const L: usize> UsbDevice<L> {
#[inline]
pub(crate) fn get_size(&self, cs: CriticalSection<'_>) -> usize {
let usb = self.usb.borrow(cs);
(((usb.uebchx.read().bits() as u16) << 8) | (usb.uebclx.read().bits() as u16)).into()
}
#[inline] #[inline]
pub fn new(pll: PLL, usb: USB_DEVICE) -> UsbBusAllocator<Self> { pub fn new(pll: PLL, usb: USB_DEVICE) -> UsbBusAllocator<Self> {
let (pll, usb) = (Mutex::new(pll), Mutex::new(usb));
let ep_table: [USBEndpoint; L] = [Default::default(); L];
UsbBusAllocator::new(Self { UsbBusAllocator::new(Self {
pll, pll: Mutex::new(pll),
usb, usb: Mutex::new(usb),
ep_table, ep_table: [Default::default(); L],
pending_ins: Mutex::new(Cell::new(0u8)),
dpram_already_used: 0, dpram_already_used: 0,
}) })
} }
@ -94,13 +116,17 @@ impl<const L: usize> UsbDevice<L> {
let usb = self.usb.borrow(cs); let usb = self.usb.borrow(cs);
let endpoint_index = endpoint_index as u8; let endpoint_index = endpoint_index as u8;
if endpoint_index > 6 { if endpoint_index >= 7 {
return Err(UsbError::InvalidEndpoint); return Err(UsbError::InvalidEndpoint);
} }
if usb.usbcon.read().frzclk().bit_is_set() {
return Err(UsbError::InvalidState);
}
usb.uenum.write(|w| w.bits(endpoint_index)); usb.uenum.write(|w| w.bits(endpoint_index));
if usb.uenum.read().bits() != endpoint_index { if usb.uenum.read().bits() & 7 /* 0b111 */ != endpoint_index {
return Err(UsbError::InvalidEndpoint); return Err(UsbError::InvalidEndpoint);
} }
@ -112,18 +138,15 @@ impl<const L: usize> UsbDevice<L> {
cs: CriticalSection<'_>, cs: CriticalSection<'_>,
endpoint_index: usize, endpoint_index: usize,
) -> Result<(), UsbError> { ) -> Result<(), UsbError> {
let usb = self.usb.borrow(cs);
let current_endpoint = self.ep_table[endpoint_index];
match self.select_endpoint(cs, endpoint_index) { match self.select_endpoint(cs, endpoint_index) {
Ok(_) => { Ok(_) => {
let usb = self.usb.borrow(cs);
let current_endpoint = self.ep_table[endpoint_index];
// Clear interrupt. //
usb.udint.modify(|_, w| w.eorsti().clear_bit());
// Enable endpoint. // // Enable endpoint. //
usb.ueconx.modify(|_, w| w.epen().set_bit()); usb.ueconx.modify(|_, w| w.epen().set_bit());
usb.uecfg1x.modify(|_, w| w.alloc().clear_bit());
// Set markered endpoint parameters to uecfg0x/1x register. // // Set markered endpoint parameters to uecfg0x/1x register. //
@ -136,16 +159,19 @@ impl<const L: usize> UsbDevice<L> {
usb.uecfg1x.modify(|_, w| { usb.uecfg1x.modify(|_, w| {
w.epbk() w.epbk()
.bits(current_endpoint.banks) .bits(0)
.epsize() .epsize()
.bits(current_endpoint.size) .bits(current_endpoint.size)
.alloc() .alloc()
.bit(current_endpoint.is_allocated) .set_bit()
}); });
if !usb.uesta0x.read().cfgok().bit() { if usb.uesta0x.read().cfgok().bit_is_clear() {
Err(UsbError::EndpointOverflow) Err(UsbError::EndpointMemoryOverflow)
} else { } else {
usb.ueienx
.modify(|_, w| w.rxoute().set_bit().rxstpe().set_bit());
Ok(()) Ok(())
} }
} }