refactor of usb hardware drivers

- write only u32s to registers
- make everything volatile
This commit is contained in:
bunnie 2022-05-09 10:04:59 +08:00
parent 8310d64de9
commit 047b9e539d
4 changed files with 2239 additions and 268 deletions

View file

@ -19,8 +19,10 @@ keyboard = {path = "../keyboard"}
bitfield = "0.13.2"
vcell = "0.1.3"
usb-device = "0.2.8"
usbd-human-interface-device = "0.1.1"
#usb-device = "0.2.8"
usb-device = {path = "../../../usb-device"}
#usbd-human-interface-device = "0.1.1"
usbd-human-interface-device = {path = "../../../usbd-human-interface-device"}
embedded-time = "0.12.1" # required by the keyboard interface
[dev-dependencies]

View file

@ -3,10 +3,8 @@ use usb_device::bus::PollResult;
use utralib::generated::*;
use crate::*;
use bitfield::bitfield;
use core::ops::{Deref, DerefMut};
use core::mem::size_of;
use core::slice;
use core::sync::atomic::{AtomicPtr, Ordering, AtomicBool};
use core::sync::atomic::{AtomicPtr, Ordering, AtomicU32};
use std::sync::{Arc, Mutex};
use usb_device::{class_prelude::*, Result, UsbDirection};
use std::collections::BTreeMap;
@ -32,12 +30,12 @@ const NUM_ENDPOINTS: usize = 16;
bitfield! {
pub struct UdcInterrupts(u32);
impl Debug;
pub endpoint, clear_endpoint: 15, 0;
pub reset, clear_reset: 16;
pub ep0_setup, clear_ep0_setup: 17;
pub suspend, clear_suspend: 18;
pub resume, clear_resume: 19;
pub disconnect, clear_disconnect: 20;
pub endpoint, set_endpoint: 15, 0;
pub reset, set_reset: 16;
pub ep0_setup, set_ep0_setup: 17;
pub suspend, set_suspend: 18;
pub resume, set_resume: 19;
pub disconnect, set_disconnect: 20;
}
bitfield! {
pub struct UdcHalt(u32);
@ -62,40 +60,96 @@ bitfield! {
}
/// This is located at 0xFF00 offset from the base of the memory region open for the UDC
#[repr(C)]
#[derive(Debug)]
pub struct SpinalUdcRegs {
regs: AtomicPtr<u32>,
}
const FRAME_OFFSET: usize = 0;
const ADDRESS_OFFSET: usize = 4;
const INT_OFFSET: usize = 8;
const HALT_OFFSET: usize = 12;
const CONFIG_OFFSET: usize = 16;
const RAMSIZE_OFFSET: usize = 20;
#[allow(dead_code)]
impl SpinalUdcRegs {
pub fn new(ptr: *mut u32) -> SpinalUdcRegs {
SpinalUdcRegs {
regs: AtomicPtr::new(ptr)
}
}
pub fn clone(&self) -> SpinalUdcRegs {
SpinalUdcRegs {
regs: AtomicPtr::new(self.regs.load(Ordering::SeqCst))
}
}
/// current USB frame ID
frame: u32,
pub fn frame_id(&self) -> u32 {
unsafe {
self.regs.load(Ordering::SeqCst).add(FRAME_OFFSET / size_of::<u32>()).read_volatile()
}
}
/// currently active address for tokens. cleared by USB reset
address: u32,
pub fn address(&self) -> u32 {
unsafe {
self.regs.load(Ordering::SeqCst).add(ADDRESS_OFFSET / size_of::<u32>()).read_volatile()
}
}
pub fn set_address(&self, addr: u32) {
unsafe {
self.regs.load(Ordering::SeqCst).add(ADDRESS_OFFSET / size_of::<u32>()).write_volatile(addr);
}
}
/// interrupt flags
interrupts: UdcInterrupts,
pub fn interrupts(&self) -> UdcInterrupts {
unsafe {
UdcInterrupts(self.regs.load(Ordering::SeqCst).add(INT_OFFSET / size_of::<u32>()).read_volatile())
}
}
pub fn clear_some_interrupts(&self, ints: UdcInterrupts) {
unsafe {
self.regs.load(Ordering::SeqCst).add(INT_OFFSET / size_of::<u32>()).write_volatile(ints.0);
}
}
pub fn clear_all_interrupts(&self) {
unsafe {
self.regs.load(Ordering::SeqCst).add(INT_OFFSET / size_of::<u32>()).write_volatile(0xffff_ffff);
}
}
/// halt - use this to pause an endpoint to give the CPU a mutex on r/w access to its registers
halt: UdcHalt,
pub fn halt(&self) -> UdcHalt {
unsafe {
UdcHalt(self.regs.load(Ordering::SeqCst).add(HALT_OFFSET / size_of::<u32>()).read_volatile())
}
}
pub fn set_halt(&self, halt: UdcHalt) {
unsafe {
self.regs.load(Ordering::SeqCst).add(HALT_OFFSET / size_of::<u32>()).write_volatile(halt.0)
}
}
/// config
config: UdcConfig,
pub fn config(&self) -> UdcConfig {
unsafe {
UdcConfig(self.regs.load(Ordering::SeqCst).add(CONFIG_OFFSET / size_of::<u32>()).read_volatile())
}
}
pub fn set_config(&self, cfg: UdcConfig) {
unsafe {
self.regs.load(Ordering::SeqCst).add(CONFIG_OFFSET / size_of::<u32>()).write_volatile(cfg.0)
}
}
/// the ram starting at 0 has a size of 1 << ramsize. Only the lower 4 bits are valid, but the field takes up a u32
ramsize: UdcRamsize,
}
impl Deref for SpinalUdcRegs {
type Target = [u8];
fn deref(&self) -> &[u8] {
/// the returned value is the properly computed bytes as read out by the hardware field (no further maths needed)
pub fn ramsize(&self) -> u32 {
unsafe {
core::slice::from_raw_parts(self as *const SpinalUdcRegs as *const u8, core::mem::size_of::<SpinalUdcRegs>())
as &[u8]
self.regs.load(Ordering::SeqCst).add(RAMSIZE_OFFSET / size_of::<u32>()).read_volatile()
}
/*
1 << (unsafe {
self.regs.load(Ordering::SeqCst).add(RAMSIZE_OFFSET / size_of::<u32>()).read_volatile()
} & 0xF)
*/
}
}
impl DerefMut for SpinalUdcRegs {
fn deref_mut(&mut self) -> &mut [u8] {
unsafe {
core::slice::from_raw_parts_mut(self as *mut SpinalUdcRegs as *mut u8, core::mem::size_of::<SpinalUdcRegs>())
as &mut [u8]
}
}
}
bitfield! {
pub struct UdcEpStatus(u32);
@ -111,17 +165,6 @@ bitfield! {
pub max_packet_size, set_max_packet_size: 31, 22;
}
const DESC_OUT: bool = false;
const DESC_IN: bool = true;
/// This is located at 0x0000-0x0047 inside the UDC region
/// This is mostly documentation, it's not actually instantiated
#[allow(dead_code)]
#[repr(C)]
pub struct SpinalUdcMem {
endpoints: [UdcEpStatus; 16],
setup_data: [u8; 8],
}
bitfield! {
pub struct UdcDesc0(u32);
impl Debug;
@ -153,92 +196,98 @@ bitfield! {
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 {
d0: UdcDesc0,
d1: UdcDesc1,
d2: UdcDesc2,
pub struct SpinalUdcDescriptor {
base: AtomicPtr::<u32>,
}
/// This structure is a set of references to a UDC descriptor in RAM. It's tricky to
/// construct correctly, as it requires interpreting some bit fields returned by the
/// UDC to map where the header goes and then determine the length of the data. The
/// data slice's length cannot be known at compile time, because it varies with the size
/// of the USB packet. However, the data should always be located at an address immediately
/// following the header's location.
pub struct SpinalUdcDescriptor<'a> {
header: &'a SpinalUdcDescriptorHeader,
data: &'a [u8],
#[allow(dead_code)]
impl SpinalUdcDescriptor {
pub fn new(base: *mut u32) -> SpinalUdcDescriptor {
SpinalUdcDescriptor { base: AtomicPtr::new(base) }
}
fn read(&self, offset: usize) -> u32 {
unsafe{self.base.load(Ordering::SeqCst).add(offset).read_volatile()}
}
fn write(&self, offset: usize, data: u32) {
unsafe{self.base.load(Ordering::SeqCst).add(offset).write_volatile(data)}
}
pub fn offset(&self) -> usize {
UdcDesc0(self.read(0)).offset() as usize
}
pub fn in_progress(&self) -> bool {
UdcDesc0(self.read(0)).code() == 0xF
}
pub fn next_offset(&self) -> usize {
UdcDesc1(self.read(1)).next_offset() as usize
}
pub fn length(&self) -> usize {
UdcDesc1(self.read(1)).length() as usize
}
pub fn direction(&self) -> UsbDirection {
if UdcDesc2(self.read(2)).direction() {
UsbDirection::In
} else {
UsbDirection::Out
}
}
pub fn int_on_done(&self) -> bool {
UdcDesc2(self.read(2)).int_on_done()
}
pub fn completion_on_full(&self) -> bool {
UdcDesc2(self.read(2)).completion_on_full()
}
pub fn data1_on_completion(&self) -> bool {
UdcDesc2(self.read(2)).data1_on_completion()
}
pub fn set_desc0(&self, offset: usize) {
let mut d0 = UdcDesc0(0);
d0.set_offset(offset as _);
d0.set_code(0xF); // automatically set in_progress
self.write(0, d0.0);
}
pub fn set_desc1(&self, next_offset: usize, length: usize) {
let mut d1 = UdcDesc1(0);
d1.set_length(length as _);
d1.set_next_offset(next_offset as _);
self.write(1, d1.0);
}
pub fn set_desc2(&self, direction: UsbDirection, int_on_done: bool, completion_on_full: bool, data1_on_completion: bool) {
let mut d2 = UdcDesc2(0);
match direction {
UsbDirection::In => d2.set_direction(true),
UsbDirection::Out => d2.set_direction(false),
}
d2.set_int_on_done(int_on_done);
d2.set_completion_on_full(completion_on_full);
d2.set_data1_on_completion(data1_on_completion);
self.write(2, d2.0);
}
pub fn write_data(&self, offset_word: usize, data: u32) {
unsafe {
self.base.load(Ordering::SeqCst).add(3 + offset_word).write_volatile(data)
}
}
pub fn read_data(&self, offset_word: usize) -> u32 {
unsafe {
self.base.load(Ordering::SeqCst).add(3 + offset_word).read_volatile()
}
}
}
/// 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,
}
fn handle_usb(_irq_no: usize, arg: *mut usize) {
let usb = unsafe { &mut *(arg as *mut SpinalUsbDevice) };
let pending = usb.csr.r(utra::usbdev::EV_PENDING);
let regs = unsafe{usb.regs.load(Ordering::SeqCst).as_mut().unwrap()};
// report if we got a double-int condition or not
if usb.was_checked.load(Ordering::SeqCst) {
usb.int_err.store(false, Ordering::SeqCst)
} else {
usb.int_err.store(true, Ordering::SeqCst)
}
usb.was_checked.store(false, Ordering::SeqCst);
usb.poll_result =
if regs.interrupts.disconnect() {
regs.interrupts.clear_disconnect(true);
PollResult::Reset
} else if regs.interrupts.resume() {
regs.interrupts.clear_reset(true);
PollResult::Resume
} else if regs.interrupts.reset() {
regs.interrupts.clear_reset(true);
PollResult::Reset
} else if regs.interrupts.suspend() {
regs.interrupts.clear_suspend(true);
PollResult::Suspend
} else if regs.interrupts.endpoint() != 0 || regs.interrupts.ep0_setup() {
let ep_setup = if regs.interrupts.ep0_setup() {
regs.interrupts.clear_ep0_setup(true);
1
} else {0};
let mut ep_in_complete = ep_setup; // mirror the value here
let mut ep_out = 0;
// all of them will be handled here, so, clear the interrupts as needed
let ep_code = regs.interrupts.endpoint() as u16;
regs.interrupts.clear_endpoint(ep_code as u32); // clear the interrupt bitmask
let mut bit = 1;
for maybe_ep in usb.eps.lock().unwrap().iter() {
if bit & ep_code != 0 {
if let Some(ep) = maybe_ep {
// form a descriptor from the memory range assigned to the EP
let base = usb.usb.as_ptr();
let descriptor = unsafe {
(base.add(ep.ep_status.head_offset() as usize * 16) as *const SpinalUdcDescriptorHeader).as_ref().unwrap()
};
if descriptor.d2.direction() == DESC_OUT {
ep_out |= bit;
} else {
ep_in_complete |= bit;
}
usb.ints.store(
usb.regs.interrupts().0,
Ordering::SeqCst
);
let mut cfg = UdcConfig(0);
cfg.set_disable_ints(true); // to be enabled only when all the interrupts are handled
usb.regs.set_config(cfg);
// *** I *think* we want to halt the EP at this point so we can get the data wthout the memory being scribbled?
} else {
log::warn!("got packet on uninitialized endpoint: bitmask 0x{:x}", bit);
}
}
bit <<= 1;
}
PollResult::Data { ep_out, ep_in_complete, ep_setup }
} else {
PollResult::None
};
usb.regs.clear_all_interrupts();
// also: do we halt the cores??
xous::try_send_message(usb.conn,
xous::Message::new_scalar(Opcode::UsbIrqHandler.to_usize().unwrap(), 0, 0, 0, 0)).ok();
@ -247,14 +296,44 @@ fn handle_usb(_irq_no: usize, arg: *mut usize) {
pub struct SpinalUsbMgmt {
csr: AtomicCsr<u32>, // consider using VolatileCell and/or refactory AtomicCsr so it is non-mutable
usb: AtomicPtr<u8>,
eps: AtomicPtr<UdcEpStatus>,
srmem: ManagedMem<{ utralib::generated::HW_USBDEV_MEM_LEN / core::mem::size_of::<u32>() }>,
regs: AtomicPtr<SpinalUdcRegs>,
int_err: Arc::<AtomicBool>,
was_checked: Arc::<AtomicBool>,
regs: SpinalUdcRegs,
}
impl SpinalUsbMgmt {
pub fn print_regs(&self) {
log::info!("control regs: {:x?}", self.regs);
for i in 0..8 {
let offset = 0xff00 + i * 4;
log::info!(
"{:x}: 0x{:x}",
offset,
unsafe{(self.usb.load(Ordering::SeqCst).add(offset) as *mut u32).read_volatile()},
);
}
//unsafe{self.usb.load(Ordering::SeqCst).add(0xff10 / size_of::<u32>()).write_volatile(0x4)};
for i in 0..16 {
let ep_status = self.status_from_index(i);
log::info!("ep{}_status: {:?}", i, ep_status);
if ep_status.head_offset() != 0 {
let desc = self.descriptor_from_status(&ep_status);
log::info!("offset: {}, in_progress: {}, length: {}", desc.offset(), desc.in_progress(), desc.length());
}
if i == 0 {
let setup_data_base = unsafe{self.usb.load(Ordering::SeqCst).add(0x40) as *mut u32};
log::info!("setup area: {:x?}{:x?}",
unsafe{setup_data_base.add(0).read_volatile()}.to_le_bytes(),
unsafe{setup_data_base.add(1).read_volatile()}.to_le_bytes()
);
}
}
log::info!("frame id: {}", self.regs.frame_id());
log::info!("usb addr: {}", self.regs.address());
log::info!("ints: {:x?}", self.regs.interrupts());
log::info!("halt: 0x{:x?}", self.regs.halt());
log::info!("config: 0x{:x?}", self.regs.config());
log::info!("ramsize: {}", self.regs.ramsize());
}
pub fn connect_device_core(&mut self, state: bool) {
log::info!("previous state: {}", self.csr.rf(utra::usbdev::USBSELECT_USBSELECT));
@ -277,21 +356,32 @@ impl SpinalUsbMgmt {
self.csr.wo(utra::usbdev::EV_PENDING, p); // clear in case it's pending for some reason
self.csr.wfo(utra::usbdev::EV_ENABLE_USB, 1);
}
pub fn descriptor_from_status(&self, ep_status: &UdcEpStatus) -> SpinalUdcDescriptor {
SpinalUdcDescriptor::new(
unsafe{ self.usb.load(Ordering::SeqCst).add(
ep_status.head_offset() as usize * 16
) as *mut u32}
)
}
pub fn status_from_index(&self, index: usize) -> UdcEpStatus {
unsafe {
self.eps.load(Ordering::SeqCst).add(index).read_volatile()
}
}
}
pub struct SpinalUsbDevice {
pub(crate) conn: CID,
usb: xous::MemoryRange,
csr_addr: u32,
csr: AtomicCsr<u32>, // consider using VolatileCell and/or refactory AtomicCsr so it is non-mutable
regs: AtomicPtr<SpinalUdcRegs>,
regs: SpinalUdcRegs,
// 1:1 mapping of endpoint structures to offsets in the memory space for the actual ep storage
eps: Arc::<Mutex::<[Option<SpinalUdcEndpoint>; NUM_ENDPOINTS]>>,
// data must be committed to this in a single write, and not composed dynamcally using this as scratch space
eps: AtomicPtr<UdcEpStatus>,
// structure to track space allocations within the memory space
allocs: Arc::<Mutex::<BTreeMap<u32, u32>>>, // key is offset, value is len
ints: AtomicU32,
tt: ticktimer_server::Ticktimer,
poll_result: PollResult,
int_err: Arc::<AtomicBool>,
was_checked: Arc::<AtomicBool>,
}
impl SpinalUsbDevice {
pub fn new(sid: xous::SID) -> SpinalUsbDevice {
@ -319,23 +409,13 @@ impl SpinalUsbDevice {
// Safety: the offset of the register bank is defined as 0xFF00 from the base of the
// usb memory area. Mapping SpinalUdcRegs here is safe assuming the structure has
// been correctly defined.
regs: AtomicPtr::new(unsafe {
(usb.as_mut_ptr().add(0xFF00) as *mut SpinalUdcRegs).as_mut().unwrap()
regs: SpinalUdcRegs::new(unsafe{usb.as_mut_ptr().add(0xFF00) as *mut u32}),
eps: AtomicPtr::new(unsafe {
(usb.as_mut_ptr().add(0x00) as *mut UdcEpStatus).as_mut().unwrap()
}),
eps: Arc::new(Mutex::new([
// 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: Arc::new(Mutex::new(BTreeMap::new())),
ints: AtomicU32::new(0),
tt: ticktimer_server::Ticktimer::new().unwrap(),
poll_result: PollResult::None,
int_err: Arc::new(AtomicBool::new(false)),
was_checked: Arc::new(AtomicBool::new(false)),
};
xous::claim_interrupt(
@ -349,27 +429,25 @@ impl SpinalUsbDevice {
usbdev.csr.wfo(utra::usbdev::EV_ENABLE_USB, 1);
// also have to enable ints at the SpinalHDL layer
let regs = unsafe{usbdev.regs.load(Ordering::SeqCst).as_mut().unwrap()};
regs.config.set_enable_ints(true);
let mut cfg = UdcConfig(0);
cfg.set_enable_ints(true);
usbdev.regs.set_config(cfg);
usbdev
}
pub fn get_iface(&self) -> SpinalUsbMgmt {
SpinalUsbMgmt {
csr: AtomicCsr::new(self.csr_addr as *mut u32),
srmem: ManagedMem::new(self.usb),
regs: AtomicPtr::new(unsafe {
(self.usb.as_mut_ptr().add(0xFF00) as *mut SpinalUdcRegs).as_mut().unwrap()
usb: AtomicPtr::new(self.usb.as_mut_ptr() as *mut u8),
eps: AtomicPtr::new(unsafe {
(self.usb.as_mut_ptr().add(0x00) as *mut UdcEpStatus).as_mut().unwrap()
}),
int_err: self.int_err.clone(),
was_checked: self.was_checked.clone(),
srmem: ManagedMem::new(self.usb),
regs: self.regs.clone(),
}
}
fn print_poll_result(&self) {
if self.int_err.load(Ordering::SeqCst) {
log::info!("error was detected in interrupt handler: previous poll result was not used");
}
match self.poll_result {
fn print_poll_result(&self, poll_result: &PollResult) {
match poll_result {
PollResult::None => log::info!("PollResult::None"),
PollResult::Reset => log::info!("PollResult::Reset"),
PollResult::Resume => log::info!("PollResult::Resume"),
@ -385,11 +463,24 @@ impl SpinalUsbDevice {
/// discards the lower 4 bits).
pub fn alloc_region(&mut self, requested: u32) -> Option<u32> {
alloc_inner(&mut self.allocs.lock().unwrap(), requested)
}
}
#[allow(dead_code)]
/// returns `true` if the region was available to be deallocated
pub fn dealloc_region(&mut self, offset: u32) -> bool {
dealloc_inner(&mut self.allocs.lock().unwrap(), offset)
}
pub fn descriptor_from_status(&self, ep_status: &UdcEpStatus) -> SpinalUdcDescriptor {
SpinalUdcDescriptor::new(
unsafe{ self.usb.as_mut_ptr().add(
ep_status.head_offset() as usize * 16
) as *mut u32}
)
}
pub fn status_from_index(&self, index: usize) -> UdcEpStatus {
unsafe {
self.eps.load(Ordering::SeqCst).add(index).read_volatile()
}
}
}
impl UsbBus for SpinalUsbDevice {
@ -419,35 +510,40 @@ impl UsbBus for SpinalUsbDevice {
ep_addr: Option<EndpointAddress>,
ep_type: EndpointType,
max_packet_size: u16,
interval: u8,
_interval: u8,
) -> Result<EndpointAddress> {
// if ep_addr is specified, create a 1-unit range else a range through the entire space
// note that ep_addr is a packed representation of index and direction,
// so you must use `.index()` to get just the index part
for index in ep_addr.map(|a| a.index()..a.index() + 1).unwrap_or(1..NUM_ENDPOINTS) {
if self.eps.lock().unwrap()[index].is_some() {
continue
if index == 0 && ep_dir == UsbDirection::In {
log::info!("ep0/in is hard-wired, nothing to do (requested size: {})", max_packet_size);
// endpoint 0 in is hard-mapped to a fixed location, no need to allocate it
return Ok(EndpointAddress::from_parts(0, ep_dir))
}
log::info!("trying to allocate ep {}", index);
// 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,
};
log::info!("allocated offset {:x}({})", offset, max_packet_size);
let mut ep_status = UdcEpStatus(0);
match ep_type {
EndpointType::Isochronous => ep.ep_status.set_isochronous(true),
_ => ep.ep_status.set_isochronous(false),
EndpointType::Isochronous => ep_status.set_isochronous(true),
_ => ep_status.set_isochronous(false),
}
log::info!("setting ep{}@{:x?} max_packet_size {}", index, offset, max_packet_size);
ep.ep_status.set_head_offset(offset / 16);
ep.ep_status.set_max_packet_size(max_packet_size as u32);
ep.ep_status.set_enable(true); // set the enable as the last op
log::info!("alloc ep{}@{:x?} max_packet_size {}", index, offset, max_packet_size);
ep_status.set_head_offset(offset / 16);
ep_status.set_max_packet_size(max_packet_size as u32);
ep_status.set_enable(true);
log::info!("ep{}_status: {:?}", index, ep_status);
self.eps.lock().unwrap()[index] = Some(ep);
// unsafe volatile write to commit the computed ep_status state
// it's up to us to make sure we got the right type and index bounds :-/
// couldn't find an abstraction in Rust that met the simultaneous demands
// of the hardware along side the external USB crate.
unsafe{self.eps.load(Ordering::SeqCst).add(index).write_volatile(ep_status)};
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
log::info!("returning endpoint {}", index);
return Ok(EndpointAddress::from_parts(index as usize, ep_dir))
} else {
return Err(UsbError::EndpointMemoryOverflow);
@ -463,16 +559,14 @@ impl UsbBus for SpinalUsbDevice {
/// Enables and initializes the USB peripheral. Soon after enabling the device will be reset, so
/// there is no need to perform a USB reset in this method.
fn enable(&mut self) {
let regs = unsafe{self.regs.load(Ordering::SeqCst).as_mut().unwrap()};
log::info!("enable");
// clear all the interrupts in a single write
regs.interrupts.0 = 0xFFFF_FFFF;
// clear other registers
regs.address = 0;
self.regs.clear_all_interrupts();
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
// enable the interrupt
regs.config.set_enable_ints(true);
let mut udc_config = self.regs.config();
udc_config.set_enable_ints(true);
self.regs.set_config(udc_config);
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
}
@ -482,30 +576,16 @@ impl UsbBus for SpinalUsbDevice {
/// enumeration, as well as ensure that all endpoints previously allocated with alloc_ep are
/// initialized as specified.
fn reset(&self) {
let regs = unsafe{self.regs.load(Ordering::SeqCst).as_mut().unwrap()};
// clear the endpoint RAM
for ep in self.eps.lock().unwrap().iter_mut() {
*ep = None;
}
self.allocs.lock().unwrap().clear();
// set the RAM from 0x0-0xFF00 to all 0's
let usbmem = unsafe{slice::from_raw_parts_mut(self.usb.as_mut_ptr(), 0xFF00)};
for m in usbmem.iter_mut() {
*m = 0;
}
// clear all the interrupts in a single write
regs.interrupts.0 = 0xFFFF_FFFF;
log::info!("reset");
// clear other registers
regs.address = 0;
self.regs.set_address(0);
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
}
/// Sets the device USB address to `addr`.
fn set_device_address(&self, addr: u8) {
let regs = unsafe{self.regs.load(Ordering::SeqCst).as_mut().unwrap()};
regs.address = addr as u32;
log::info!("set_addr {}", addr);
self.regs.set_address(addr as _);
}
/// Writes a single packet of data to the specified endpoint and returns number of bytes
@ -527,31 +607,31 @@ impl UsbBus for SpinalUsbDevice {
///
/// Implementations may also return other errors if applicable.
fn write(&self, ep_addr: EndpointAddress, buf: &[u8]) -> Result<usize> {
if let Some(ep) = &self.eps.lock().unwrap()[ep_addr.index()] {
if buf.len() > ep.ep_status.max_packet_size() as usize {
Err(UsbError::BufferOverflow)
} else {
let base = self.usb.as_mut_ptr();
let descriptor = unsafe {
(base.add(ep.ep_status.head_offset() as usize * 16) as *mut SpinalUdcDescriptorHeader).as_mut().unwrap()
};
descriptor.d0.set_offset(0);
descriptor.d1.set_next_offset(0);
descriptor.d1.set_length(buf.len() as u32);
descriptor.d2.set_direction(DESC_OUT);
descriptor.d2.set_int_on_done(true);
let data = unsafe {
slice::from_raw_parts_mut(
base.add(ep.ep_status.head_offset() as usize * 16 + size_of::<SpinalUdcDescriptorHeader>()),
ep.ep_status.max_packet_size() as usize
)};
for (&src, dst) in buf.iter().zip(data.iter_mut()) {
*dst = src;
}
Ok(buf.len())
}
log::info!("write ep{}", ep_addr.index());
let ep_status = self.status_from_index(ep_addr.index());
let descriptor = self.descriptor_from_status(&ep_status);
if buf.len() > ep_status.max_packet_size() as usize {
Err(UsbError::BufferOverflow)
} else {
Err(UsbError::InvalidEndpoint)
descriptor.set_desc0(0); // <-- somehow this needs to track across multiple packets
descriptor.set_desc1(0, buf.len());
descriptor.set_desc2(
UsbDirection::Out,
true,
true, // this should be equal to "packet_end", but this driver doesn't have that...?
ep_addr.index() == 0, // only trigger for ep0 (per spinal linux driver)
);
if buf.len() % 4 != 0 {
// the linux driver doesn't handle anything other than word aligned, can we get away with it here?
log::warn!("non word aligned buffer received, this needs to be handled");
}
for (index, src) in buf.chunks_exact(4).enumerate() {
let w = u32::from_le_bytes(src.try_into().unwrap());
descriptor.write_data(index, w);
}
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
Ok(buf.len())
}
}
@ -574,45 +654,63 @@ impl UsbBus for SpinalUsbDevice {
///
/// Implementations may also return other errors if applicable.
fn read(&self, ep_addr: EndpointAddress, buf: &mut [u8]) -> Result<usize> {
if let Some(ep) = &self.eps.lock().unwrap()[ep_addr.index()] {
let base = self.usb.as_mut_ptr();
let descriptor = unsafe {
(base.add(ep.ep_status.head_offset() as usize * 16) as *mut SpinalUdcDescriptorHeader).as_mut().unwrap()
};
if descriptor.d0.code() == 0xF {
log::info!("read called but descriptor was in progress")
log::info!("read ep{}", ep_addr.index());
let ep_status = self.status_from_index(ep_addr.index());
let descriptor = self.descriptor_from_status(&ep_status);
if descriptor.in_progress() {
log::info!("read called but descriptor was in progress")
}
let len = descriptor.length();
if buf.len() > len {
return Err(UsbError::BufferOverflow)
}
descriptor.set_desc1(0, buf.len());
descriptor.set_desc2(
UsbDirection::In,
true,
true,
ep_addr.index() == 0,
);
if ep_addr.index() == 0 {
// hard coded to 8 bytes in hardware
if buf.len() < 8 {
return Err(UsbError::BufferOverflow)
}
descriptor.d1.set_next_offset(0);
descriptor.d2.set_direction(DESC_IN);
descriptor.d2.set_int_on_done(true);
let len = descriptor.d0.offset() as usize;
if len > buf.len() {
Err(UsbError::BufferOverflow)
} else {
let data = unsafe {
slice::from_raw_parts_mut(
base.add(ep.ep_status.head_offset() as usize * 16 + size_of::<SpinalUdcDescriptorHeader>()),
ep.ep_status.max_packet_size() as usize
)};
for (&src, dst) in data[..len].iter().zip(buf.iter_mut()) {
// setup data is in a special, fixed location
let setup_data_base = unsafe{self.usb.as_mut_ptr().add(0x40) as *mut u32};
buf[..4].copy_from_slice(
&unsafe{setup_data_base.add(0).read_volatile()}
.to_le_bytes()
);
buf[4..8].copy_from_slice(
&unsafe{setup_data_base.add(1).read_volatile()}
.to_le_bytes()
);
Ok(8)
} else {
if len % 4 != 0 {
log::info!("non-word aligned length encountered, need code to handle this case");
}
for i in 0..len / 4 {
let word = descriptor.read_data(i);
for (&src, dst) in word.to_le_bytes().iter().zip(buf[i*4..(i+1)*4].iter_mut()) {
*dst = src;
}
Ok(len)
}
} else {
Err(UsbError::InvalidEndpoint)
Ok(len)
}
}
/// Sets or clears the STALL condition for an endpoint. If the endpoint is an OUT endpoint, it
/// should be prepared to receive data again.
fn set_stalled(&self, ep_addr: EndpointAddress, stalled: bool) {
log::info!("set_stalled{}->{}", ep_addr.index(), stalled);
// it looks like a STALL condition could be forced even on unallocated endpoints, so
// we alias into the register block and force it to happen.
let ep_status = unsafe {
(self.usb.as_mut_ptr().add(ep_addr.index() * size_of::<UdcEpStatus>()) as *mut UdcEpStatus).as_mut().unwrap()
let mut ep_status = unsafe {
self.eps.load(Ordering::SeqCst).add(ep_addr.index()).read_volatile()
};
match (stalled, ep_addr.direction()) {
(true, UsbDirection::In) => {
ep_status.set_force_nack(false);
@ -625,13 +723,18 @@ impl UsbBus for SpinalUsbDevice {
},
(false, UsbDirection::Out) => ep_status.set_force_stall(false),
};
// single volatile commit of the results
unsafe {
self.eps.load(Ordering::SeqCst).add(ep_addr.index()).write_volatile(ep_status)
}
}
/// Gets whether the STALL condition is set for an endpoint.
fn is_stalled(&self, ep_addr: EndpointAddress) -> bool {
let ep_status = unsafe {
(self.usb.as_mut_ptr().add(ep_addr.index() * size_of::<UdcEpStatus>()) as *mut UdcEpStatus).as_mut().unwrap()
self.eps.load(Ordering::SeqCst).add(ep_addr.index()).read_volatile()
};
log::info!("is_stalled{} -> {}", ep_addr.index(), ep_status.force_stall());
ep_status.force_stall()
}
@ -653,20 +756,74 @@ impl UsbBus for SpinalUsbDevice {
/// Gets information about events and incoming data. Usually called in a loop or from an
/// interrupt handler. See the [`PollResult`] struct for more information.
fn poll(&self) -> PollResult {
if self.int_err.load(Ordering::SeqCst) {
log::warn!("interrupt triggered twice before handler got to it; an event was lost");
}
self.was_checked.store(true, Ordering::SeqCst);
self.print_poll_result();
// because the library type does not implement Copy or Clone
match self.poll_result {
PollResult::None => PollResult::None,
PollResult::Reset => PollResult::Reset,
PollResult::Resume => PollResult::Resume,
PollResult::Suspend => PollResult::Suspend,
PollResult::Data {ep_out, ep_in_complete, ep_setup} =>
PollResult::Data{ep_out, ep_in_complete, ep_setup},
let mut interrupts = UdcInterrupts(self.ints. load(Ordering::SeqCst));
log::info!("poll {}, {:x?}", interrupts.0, interrupts);
let poll_result =
if interrupts.disconnect() {
log::info!("disconnect");
interrupts.set_disconnect(false);
PollResult::Reset
} else if interrupts.resume() {
log::info!("resume");
interrupts.set_reset(false);
PollResult::Resume
} else if interrupts.reset() {
log::info!("reset");
interrupts.set_reset(false);
PollResult::Reset
} else if interrupts.suspend() {
log::info!("suspend");
interrupts.set_suspend(false);
PollResult::Suspend
} else if interrupts.endpoint() != 0 || interrupts.ep0_setup() {
let ep_setup = if interrupts.ep0_setup() {
log::info!("ep0");
interrupts.set_ep0_setup(false);
1
} else {0};
let mut ep_in_complete = ep_setup; // mirror the value here
let mut ep_out = 0;
// all of them will be handled here, so, clear the interrupts as needed
if interrupts.endpoint() != 0 {
let mut bit = 0;
loop {
if (interrupts.endpoint() & (1 << bit)) != 0 {
log::info!("ep{}", bit);
// form a descriptor from the memory range assigned to the EP
let ep_status = self.status_from_index(bit);
let descriptor = self.descriptor_from_status(&ep_status);
if descriptor.direction() == UsbDirection::Out {
ep_out |= 1 << bit;
} else {
ep_in_complete |= 1 << bit;
}
interrupts.set_endpoint(interrupts.endpoint() & !(1 << bit));
break;
}
bit += 1;
}
}
PollResult::Data { ep_out, ep_in_complete, ep_setup }
} else {
PollResult::None
};
if interrupts.0 == 0 {
// all interrupts handled, re-enable nterrupts
let mut cfg = UdcConfig(0);
cfg.set_enable_ints(true); // to be enabled only when all the interrupts are handled
self.regs.set_config(cfg);
} else {
log::info!("more interrupts to handle: {:x}, {:x?}", interrupts.0, interrupts);
self.ints.store(interrupts.0, Ordering::SeqCst);
// re-enter the interrupt handler to handle the next interrupt
xous::try_send_message(self.conn,
xous::Message::new_scalar(Opcode::UsbIrqHandler.to_usize().unwrap(), 0, 0, 0, 0)).ok();
}
self.print_poll_result(&poll_result);
poll_result
}
/// Simulates a disconnect from the USB bus, causing the host to reset and re-enumerate the
@ -679,6 +836,7 @@ impl UsbBus for SpinalUsbDevice {
/// * [`Unsupported`](crate::UsbError::Unsupported) - This UsbBus implementation doesn't support
/// simulating a disconnect or it has not been enabled at creation time.
fn force_reset(&self) -> Result<()> {
log::info!("force_reset");
self.csr.wfo(utra::usbdev::USBSELECT_USBSELECT, 0);
self.tt.sleep_ms(5).unwrap();
self.csr.wfo(utra::usbdev::USBSELECT_USBSELECT, 1);

View file

@ -7,8 +7,6 @@ use api::*;
#[cfg(any(target_os = "none", target_os = "xous"))]
mod kbd;
#[cfg(any(target_os = "none", target_os = "xous"))]
use kbd::*;
#[cfg(any(target_os = "none", target_os = "xous"))]
mod hw;
#[cfg(any(target_os = "none", target_os = "xous"))]
use hw::*;
@ -62,7 +60,7 @@ fn xmain() -> ! {
let usbdev = SpinalUsbDevice::new(usbdev_sid);
let mut usbmgmt = usbdev.get_iface();
let mut kbd = crate::kbd::Keyboard::new(usbdev_sid);
let mut kbd = kbd::Keyboard::new(usbdev_sid);
let tt = ticktimer_server::Ticktimer::new().unwrap();
log::info!("connecting device core");
usbmgmt.connect_device_core(true);
@ -92,25 +90,30 @@ fn xmain() -> ! {
cid
).expect("couldn't create suspend/resume object");
log::info!("alloc");
let usb_alloc = UsbBusAllocator::new(usbdev);
log::info!("clock");
let clock = EmbeddedClock::new();
log::info!("hid");
let mut keyboard = UsbHidClassBuilder::new()
.add_interface(
NKROBootKeyboardInterface::default_config(&clock),
)
.build(&usb_alloc);
log::info!("dev");
let mut usb_dev = UsbDeviceBuilder::new(&usb_alloc, UsbVidPid(0x1209, 0x0001))
.manufacturer("usbd-human-interface-device")
.product("NKRO Keyboard")
.serial_number("PRECURSOR")
.build();
log::info!("main");
let mut cmdline = String::new();
loop {
let msg = xous::receive_message(usbdev_sid).unwrap();
log::info!("msg: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::SuspendResume) => xous::msg_scalar_unpack!(msg, token, _, _, _, {
kbd.suspend();
@ -271,6 +274,7 @@ pub(crate) fn alloc_inner(allocs: &mut BTreeMap<u32, u32>, requested: u32) -> Op
None
}
}
#[allow(dead_code)]
pub(crate) fn dealloc_inner(allocs: &mut BTreeMap<u32, u32>, offset: u32) -> bool {
allocs.remove(&offset).is_some()
}

File diff suppressed because it is too large Load diff