working through the usb endpoint descriptor allocator

This commit is contained in:
bunnie 2022-05-02 22:59:33 +08:00
parent 66892e15d2
commit c12d9cbe8f
5 changed files with 402 additions and 58 deletions

51
Cargo.lock generated
View file

@ -843,6 +843,16 @@ version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457"
[[package]]
name = "embedded-hal"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35949884794ad573cf46071e41c9b60efb0cb311e3ca01f7af807af1debc66ff"
dependencies = [
"nb 0.1.3",
"void",
]
[[package]]
name = "encoding_rs"
version = "0.8.28"
@ -1713,6 +1723,21 @@ dependencies = [
"xous-names",
]
[[package]]
name = "nb"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "801d31da0513b6ec5214e9bf433a77966320625a37860f910be265be6e18d06f"
dependencies = [
"nb 1.0.0",
]
[[package]]
name = "nb"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "546c37ac5d9e56f55e73b677106873d9d9f5190605e41a856503623648488cae"
[[package]]
name = "net"
version = "0.1.0"
@ -3154,6 +3179,12 @@ dependencies = [
"percent-encoding",
]
[[package]]
name = "usb-device"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6be90410d4772074ea49525e2e753b65920b94b57eee21a6ef7b6a6fe6296245"
[[package]]
name = "usb-test"
version = "0.1.0"
@ -3164,13 +3195,27 @@ dependencies = [
"log-server",
"num-derive",
"num-traits",
"rand 0.7.3",
"rand_chacha 0.3.1",
"susres",
"ticktimer-server",
"usb-device",
"usbd-hid-device",
"utralib",
"xous",
"xous-names",
]
[[package]]
name = "usbd-hid-device"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6458a7119d68e106afc404af6b3a641fa03ddeaa98cda9b68a65bf3db6a98dd"
dependencies = [
"embedded-hal",
"usb-device",
]
[[package]]
name = "utralib"
version = "0.1.0"
@ -3196,6 +3241,12 @@ version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5a972e5669d67ba988ce3dc826706fb0a8b01471c088cb0b6110b805cc36aed"
[[package]]
name = "void"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d"
[[package]]
name = "walkdir"
version = "2.3.2"

View file

@ -18,6 +18,13 @@ susres = {path = "../susres"}
keyboard = {path = "../keyboard"}
bitfield = "0.13.2"
usb-device = "0.2.8"
usbd-hid-device = "0.1.1"
[dev-dependencies]
rand = "0.7.3"
rand_chacha = "0.3.1"
[target.'cfg(not(any(windows,unix)))'.dependencies]
utralib = { path = "../../utralib"}

View file

@ -11,3 +11,94 @@ impl UsbTest {
pub fn resume(&self) {
}
}
use keyboard::{RowCol, KeyRawStates, ScanCode, KeyMap};
#[allow(dead_code)]
pub(crate) struct Keyboard {
cid: xous::CID,
map: KeyMap,
rate: u32,
delay: u32,
chord_interval: u32,
pub debug: u32,
}
impl Keyboard {
pub fn new(sid: xous::SID) -> Keyboard {
Keyboard {
cid: xous::connect(sid).unwrap(),
map: KeyMap::Qwerty,
rate: 20,
delay: 200,
chord_interval: 50,
debug: 0,
}
}
pub fn suspend(&self) {
}
pub fn resume(&self) {
}
pub fn set_map(&mut self, map: KeyMap) {
self.map = map;
}
pub fn get_map(&self) -> KeyMap {self.map}
pub fn update(&self) -> KeyRawStates {
KeyRawStates::new()
}
pub fn track_chord(&mut self, _krs: &KeyRawStates) -> Vec<char> {
Vec::new()
}
pub fn track_keys(&mut self, _rs: &KeyRawStates) -> Vec<char> {
Vec::new()
}
pub fn set_repeat(&mut self, rate: u32, delay: u32) {
self.rate = rate;
self.delay = delay;
}
pub fn set_chord_interval(&mut self, delay: u32) {
self.chord_interval = delay;
}
pub fn is_repeating_key(&self) -> bool {
false
}
pub(crate) fn get_repeat_check_interval(&self) -> u32 {
self.rate
}
pub(crate) fn poll(&mut self) {}
}
pub struct SpinalUsbDevice {
}
impl SpinalUsbDevice {
pub fn new(_sid: xous::SID) -> SpinalUsbDevice {
SpinalUsbDevice {}
}
pub fn print_regs(&self) {
}
/// simple but easy to understand allocator for buffers inside the descriptor memory space
pub fn alloc_region(&mut self, requested: usize) -> Option<u32> {
None
}
/// returns `true` if the region was available to be deallocated
pub fn dealloc_region(&mut self, offset: usize) -> bool {
false
}
pub fn connect_device_core(&mut self, _state: bool) {
}
pub fn suspend(&mut self) {
}
pub fn resume(&mut self) {
}
}

View file

@ -2,6 +2,11 @@ use utralib::generated::*;
use crate::*;
use bitfield::bitfield;
use core::ops::{Deref, DerefMut};
use core::mem::size_of;
use usb_device::{class_prelude::*, Result, UsbDirection};
use std::collections::BTreeMap;
const NUM_ENDPOINTS: usize = 16;
bitfield! {
pub struct UdcInterrupts(u32);
@ -18,7 +23,7 @@ bitfield! {
impl Debug;
pub endpointid, set_endpointid: 3, 0;
pub enable_req, set_enable_req: 4;
pub enable_ack, set_enable_ack: 5; // question: can we make this ... read-only?
pub enable_ack, _: 5; // question: can we make this ... read-only?
}
bitfield! {
pub struct UdcConfig(u32);
@ -32,50 +37,7 @@ bitfield! {
bitfield! {
pub struct UdcRamsize(u32);
impl Debug;
pub ramsize, dnu_ramsize: 3, 0;
}
bitfield! {
pub struct UdcEpStatus(u32);
impl Debug;
pub enable, set_enable: 0;
pub force_stall, set_force_stall: 1;
pub force_nack, set_force_nack: 2;
// selects DATA0/DATA1; 0 => DATA0. Also set by the controller automatically
pub data_phase, set_data_phase: 3;
// specifies the offset of the endpoint's descriptor in RAM. 0 => empty, otherwise multply by 16 to get the address
pub head_offset, set_head_offset: 15, 4;
pub isochronous, set_isochronous: 16;
pub max_packet_size, set_max_packet_size: 31, 22;
}
bitfield! {
pub struct UdcDescriptor0(u32);
impl Debug;
// current progress of the transfer, in bytes
pub offset, set_offset: 15, 0;
// 0xF -> in progress, 0x0 -> success
pub code, set_code: 19, 16;
}
bitfield! {
pub struct UdcDescriptor1(u32);
impl Debug;
// offset of the next descriptor in RAM. 0 => none, otherwise multiply by 16 to get the address in bytes
pub next_offset, set_next_offset: 15, 4;
// length of the data field in bytes
pub length, set_length: 31, 16;
}
bitfield! {
pub struct UdcDescriptor2(u32);
impl Debug;
// direction. 0 => OUT, 1 => IN
pub direction, set_direction: 16;
// if set, fires an interrupt when descriptor is completed
pub int_on_done, set_int_on_done: 17;
// From SpinalHDL docs directly: Normally, a descriptor completion only occurs when a USB transfer
// is smaller than the max_packet_size. But, if this field is set,
// then when the descriptor becomes full is also considered a completion event. (offset == length)
pub completion_on_full, set_completion_on_full: 18;
// forces dataphase to DATA1 when the descriptor is complete
pub data1_on_completion, set_data1_on_completion: 19;
pub ramsize, _: 3, 0;
}
/// This is located at 0xFF00 offset from the base of the memory region open for the UDC
@ -114,6 +76,19 @@ impl DerefMut for SpinalUdcRegs {
}
bitfield! {
pub struct UdcEpStatus(u32);
impl Debug;
pub enable, set_enable: 0;
pub force_stall, set_force_stall: 1;
pub force_nack, set_force_nack: 2;
// selects DATA0/DATA1; 0 => DATA0. Also set by the controller automatically
pub data_phase, set_data_phase: 3;
// specifies the offset of the endpoint's descriptor in RAM. 0 => empty, otherwise multply by 16 to get the address
pub head_offset, set_head_offset: 15, 4;
pub isochronous, set_isochronous: 16;
pub max_packet_size, set_max_packet_size: 31, 22;
}
/// This is located at 0x0000-0x0047 inside the UDC region
#[repr(C)]
pub struct SpinalUdcMem {
@ -121,6 +96,36 @@ pub struct SpinalUdcMem {
setup_data: [u8; 8],
}
bitfield! {
pub struct UdcDescriptor0(u32);
impl Debug;
// current progress of the transfer, in bytes
pub offset, set_offset: 15, 0;
// 0xF -> in progress, 0x0 -> success
pub code, set_code: 19, 16;
}
bitfield! {
pub struct UdcDescriptor1(u32);
impl Debug;
// offset of the next descriptor in RAM. 0 => none, otherwise multiply by 16 to get the address in bytes
pub next_offset, set_next_offset: 15, 4;
// length of the data field in bytes
pub length, set_length: 31, 16;
}
bitfield! {
pub struct UdcDescriptor2(u32);
impl Debug;
// direction. 0 => OUT, 1 => IN
pub direction, set_direction: 16;
// if set, fires an interrupt when descriptor is completed
pub int_on_done, set_int_on_done: 17;
// From SpinalHDL docs directly: Normally, a descriptor completion only occurs when a USB transfer
// is smaller than the max_packet_size. But, if this field is set,
// then when the descriptor becomes full is also considered a completion event. (offset == length)
pub completion_on_full, set_completion_on_full: 18;
// forces dataphase to DATA1 when the descriptor is complete
pub data1_on_completion, set_data1_on_completion: 19;
}
/// This structure maps onto a variable length region anywhere inside the UDC region. It is always aligned to a 16-byte offset
#[repr(C)]
pub struct SpinalUdcDescriptorHeader {
@ -139,15 +144,72 @@ pub struct SpinalUdcDescriptor<'a> {
data: &'a [u8],
}
pub struct UsbTest {
/// this is a set of pointers that are dynamically bound to a given endpoint
/// on demand
pub struct SpinalUdcEndpoint {
ep_status: &'static mut UdcEpStatus,
_interval: u8,
}
pub struct SpinalUsbDevice {
pub(crate) conn: CID,
gpio_csr: utralib::CSR<u32>,
usb: xous::MemoryRange,
regs: &'static mut SpinalUdcRegs,
// 1:1 mapping of endpoint structures to offsets in the memory space for the actual ep storage
eps: [Option<SpinalUdcEndpoint>; NUM_ENDPOINTS],
// structure to track space allocations within the memory space
allocs: BTreeMap<usize, usize>, // key is offset, value is len
}
impl UsbBus for SpinalUsbDevice {
fn alloc_ep(
&mut self,
ep_dir: UsbDirection,
ep_addr: Option<EndpointAddress>,
ep_type: EndpointType,
max_packet_size: u16,
interval: u8,
) -> Result<EndpointAddress> {
// if ep_addr is specified, create a 1-unit range else a range through the entire space
for index in ep_addr.map(|a| a.index()..a.index() + 1).unwrap_or(1..NUM_ENDPOINTS) {
if self.eps[index].is_some() {
continue
}
// only if there is memory that can accommodate the max_packet_size
if let Some(offset) = self.alloc_region(max_packet_size as _) {
let ep = SpinalUdcEndpoint {
// Safety: the offset of the endpoint storage bank is defined as 0x0 + 4*index from the base of the
// usb memory area. Mapping UdcEpStatus here is safe assuming the structure has been correctly defined.
ep_status: unsafe {
(self.usb.as_mut_ptr().add(index * size_of::<UdcEpStatus>()) as *mut UdcEpStatus).as_mut().unwrap()
},
_interval: interval,
};
match ep_type {
EndpointType::Isochronous => ep.ep_status.set_isochronous(true),
_ => ep.ep_status.set_isochronous(false),
}
log::info!("setting ep{}@{:x?} max_packet_size {}", index, ptr, max_packet_size);
ep.ep_status.set_head_offset(offset);
ep.ep_status.set_max_packet_size(max_packet_size as u16);
ep.ep_status.set_enable(true); // set the enable as the last op
self.eps[index] = Some(ep);
return Ok(EndpointAddress::from_parts(index as u8, ep_dir))
} else {
return Err(UsbError::EndpointMemoryOverflow);
}
}
// nothing matched, so there must be an error
Err(match ep_addr {
Some(_) => UsbError::InvalidEndpoint,
None => UsbError::EndpointOverflow,
})
}
}
impl UsbTest {
pub fn new(sid: xous::SID) -> UsbTest {
impl SpinalUsbDevice {
pub fn new(sid: xous::SID) -> SpinalUsbDevice {
let gpio_base = xous::syscall::map_memory(
xous::MemoryAddress::new(utra::gpio::HW_GPIO_BASE),
None,
@ -164,7 +226,7 @@ impl UsbTest {
)
.expect("couldn't map USB device memory range");
let mut usbtest = UsbTest {
let mut usbdev = SpinalUsbDevice {
gpio_csr: CSR::new(gpio_base.as_mut_ptr() as *mut u32),
conn: xous::connect(sid).unwrap(),
usb,
@ -173,13 +235,31 @@ impl UsbTest {
// been correctly defined.
regs: unsafe {
(usb.as_mut_ptr().add(0xFF00) as *mut SpinalUdcRegs).as_mut().unwrap()
}
},
eps: [
// can't derive Copy on this, and also can't make a Default.
// But # of eps is pretty damn static even though notionally we
// use a NUM_ENDPOINTS to represent the value for readability, so, write it out long-form.
None, None, None, None,
None, None, None, None,
None, None, None, None,
None, None, None, None,
],
allocs: BTreeMap::new(),
};
usbtest
usbdev
}
pub fn print_regs(&self) {
log::info!("control regs: {:x?}", self.regs);
}
/// simple but easy to understand allocator for buffers inside the descriptor memory space
pub fn alloc_region(&mut self, requested: u32) -> Option<u32> {
alloc_inner(&mut self.allocs, requested)
}
/// returns `true` if the region was available to be deallocated
pub fn dealloc_region(&mut self, offset: u32) -> bool {
dealloc_inner(&mut self.allocs, offset)
}
pub fn connect_device_core(&mut self, state: bool) {
if state {

View file

@ -4,25 +4,26 @@
mod api;
use api::*;
#[cfg(any(target_os = "none", target_os = "xous"))]
mod kbd;
#[cfg(any(target_os = "none", target_os = "xous"))]
use kbd::*;
use num_traits::*;
use xous::{CID, msg_scalar_unpack, Message, send_message};
#[cfg(any(target_os = "none", target_os = "xous"))]
mod hw;
#[cfg(any(target_os = "none", target_os = "xous"))]
use hw::*;
#[cfg(not(any(target_os = "none", target_os = "xous")))]
mod hosted;
#[cfg(not(any(target_os = "none", target_os = "xous")))]
use hosted::*;
use num_traits::*;
use xous::{CID, msg_scalar_unpack, Message, send_message};
use std::collections::BTreeMap;
#[xous::xous_main]
fn xmain() -> ! {
use crate::UsbTest;
use crate::SpinalUsbDevice;
log_server::init_wait().unwrap();
log::set_max_level(log::LevelFilter::Info);
@ -32,7 +33,7 @@ fn xmain() -> ! {
let usbtest_sid = xns.register_name(api::SERVER_NAME_USBTEST, None).expect("can't register server");
log::trace!("registered with NS -- {:?}", usbtest_sid);
let mut usbtest = UsbTest::new(usbtest_sid);
let mut usbtest = SpinalUsbDevice::new(usbtest_sid);
let mut kbd = Keyboard::new(usbtest_sid);
log::trace!("ready to accept requests");
@ -161,3 +162,117 @@ fn xmain() -> ! {
log::trace!("quitting");
xous::terminate_process(0)
}
pub(crate) const START_OFFSET: u32 = 0x0048;
pub(crate) const END_OFFSET: u32 = 0xFF00;
pub(crate) fn alloc_inner(allocs: &mut BTreeMap<u32, u32>, requested: u32) -> Option<u32> {
if requested == 0 {
return None;
}
let mut alloc_offset = START_OFFSET;
for (&offset, &length) in allocs.iter() {
// println!("aoff: {}, cur: {}+{}", alloc_offset, offset, length);
assert!(offset >= alloc_offset, "allocated regions overlap");
if offset > alloc_offset {
if offset - alloc_offset >= requested {
// there's a hole in the list, insert the element here
break;
}
}
alloc_offset = offset + length;
}
if alloc_offset + requested <= END_OFFSET {
allocs.insert(alloc_offset, requested);
Some(alloc_offset)
} else {
None
}
}
pub(crate) fn dealloc_inner(allocs: &mut BTreeMap<u32, u32>, offset: u32) -> bool {
allocs.remove(&offset).is_some()
}
// run with `cargo test -- --nocapture --test-threads=1`:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_alloc() {
use rand_chacha::ChaCha8Rng;
use rand_chacha::rand_core::SeedableRng;
use rand_chacha::rand_core::RngCore;
let mut rng = ChaCha8Rng::seed_from_u64(0);
let mut allocs = BTreeMap::<u32, u32>::new();
assert_eq!(alloc_inner(&mut allocs, 128), Some(START_OFFSET));
assert_eq!(alloc_inner(&mut allocs, 64), Some(START_OFFSET + 128));
assert_eq!(alloc_inner(&mut allocs, 256), Some(START_OFFSET + 128 + 64));
assert_eq!(alloc_inner(&mut allocs, 128), Some(START_OFFSET + 128 + 64 + 256));
assert_eq!(alloc_inner(&mut allocs, 128), Some(START_OFFSET + 128 + 64 + 256 + 128));
assert_eq!(alloc_inner(&mut allocs, 128), Some(START_OFFSET + 128 + 64 + 256 + 128 + 128));
assert_eq!(alloc_inner(&mut allocs, 0xFF00), None);
// create two holes and fill first hole, interleaved
assert_eq!(dealloc_inner(&mut allocs, START_OFFSET + 128 + 64), true);
let mut last_alloc = 0;
// consistency check and print out
for (&offset, &len) in allocs.iter() {
assert!(offset >= last_alloc, "new offset is inside last allocation!");
println!("{}-{}", offset, offset+len);
last_alloc = offset + len;
}
assert_eq!(alloc_inner(&mut allocs, 128), Some(START_OFFSET + 128 + 64));
assert_eq!(dealloc_inner(&mut allocs, START_OFFSET + 128 + 64 + 256 + 128), true);
assert_eq!(alloc_inner(&mut allocs, 128), Some(START_OFFSET + 128 + 64 + 128));
// alloc something that doesn't fit at all
assert_eq!(alloc_inner(&mut allocs, 256), Some(START_OFFSET + 128 + 64 + 256 + 128 + 128 + 128));
// fill second hole
assert_eq!(alloc_inner(&mut allocs, 128), Some(START_OFFSET + 128 + 64 + 256 + 128));
// final tail alloc
assert_eq!(alloc_inner(&mut allocs, 64), Some(START_OFFSET + 128 + 64 + 256 + 128 + 128 + 128 + 256));
println!("after structured test:");
let mut last_alloc = 0;
// consistency check and print out
for (&offset, &len) in allocs.iter() {
assert!(offset >= last_alloc, "new offset is inside last allocation!");
println!("{}-{}({})", offset, offset+len, len);
last_alloc = offset + len;
}
// random alloc/dealloc and check for overlapping regions
let mut tracker = Vec::<u32>::new();
for _ in 0..10240 {
if rng.next_u32() % 2 == 0 {
if tracker.len() > 0 {
println!("tracker: {:?}", tracker);
let index = tracker.remove((rng.next_u32() % tracker.len() as u32) as usize);
println!("removing: {} of {}", index, tracker.len());
assert_eq!(dealloc_inner(&mut allocs, index), true);
}
} else {
let req = rng.next_u32() % 256;
if let Some(offset) = alloc_inner(&mut allocs, req) {
println!("tracker: {:?}", tracker);
println!("alloc: {}+{}", offset, req);
tracker.push(offset);
}
}
}
let mut last_alloc = 0;
// consistency check and print out
println!("after random test:");
for (&offset, &len) in allocs.iter() {
assert!(offset >= last_alloc, "new offset is inside last allocation!");
println!("{}-{}({})", offset, offset+len, len);
last_alloc = offset + len;
}
}
}