mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-20 09:03:28 +00:00
refactor of usb hardware drivers
- write only u32s to registers - make everything volatile
This commit is contained in:
parent
8310d64de9
commit
047b9e539d
4 changed files with 2239 additions and 268 deletions
|
|
@ -19,8 +19,10 @@ keyboard = {path = "../keyboard"}
|
||||||
bitfield = "0.13.2"
|
bitfield = "0.13.2"
|
||||||
vcell = "0.1.3"
|
vcell = "0.1.3"
|
||||||
|
|
||||||
usb-device = "0.2.8"
|
#usb-device = "0.2.8"
|
||||||
usbd-human-interface-device = "0.1.1"
|
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
|
embedded-time = "0.12.1" # required by the keyboard interface
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
|
|
||||||
|
|
@ -3,10 +3,8 @@ use usb_device::bus::PollResult;
|
||||||
use utralib::generated::*;
|
use utralib::generated::*;
|
||||||
use crate::*;
|
use crate::*;
|
||||||
use bitfield::bitfield;
|
use bitfield::bitfield;
|
||||||
use core::ops::{Deref, DerefMut};
|
|
||||||
use core::mem::size_of;
|
use core::mem::size_of;
|
||||||
use core::slice;
|
use core::sync::atomic::{AtomicPtr, Ordering, AtomicU32};
|
||||||
use core::sync::atomic::{AtomicPtr, Ordering, AtomicBool};
|
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use usb_device::{class_prelude::*, Result, UsbDirection};
|
use usb_device::{class_prelude::*, Result, UsbDirection};
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
@ -32,12 +30,12 @@ const NUM_ENDPOINTS: usize = 16;
|
||||||
bitfield! {
|
bitfield! {
|
||||||
pub struct UdcInterrupts(u32);
|
pub struct UdcInterrupts(u32);
|
||||||
impl Debug;
|
impl Debug;
|
||||||
pub endpoint, clear_endpoint: 15, 0;
|
pub endpoint, set_endpoint: 15, 0;
|
||||||
pub reset, clear_reset: 16;
|
pub reset, set_reset: 16;
|
||||||
pub ep0_setup, clear_ep0_setup: 17;
|
pub ep0_setup, set_ep0_setup: 17;
|
||||||
pub suspend, clear_suspend: 18;
|
pub suspend, set_suspend: 18;
|
||||||
pub resume, clear_resume: 19;
|
pub resume, set_resume: 19;
|
||||||
pub disconnect, clear_disconnect: 20;
|
pub disconnect, set_disconnect: 20;
|
||||||
}
|
}
|
||||||
bitfield! {
|
bitfield! {
|
||||||
pub struct UdcHalt(u32);
|
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
|
/// This is located at 0xFF00 offset from the base of the memory region open for the UDC
|
||||||
#[repr(C)]
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct SpinalUdcRegs {
|
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
|
/// 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
|
/// 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
|
/// 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 - 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
|
||||||
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
|
/// 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,
|
/// the returned value is the properly computed bytes as read out by the hardware field (no further maths needed)
|
||||||
}
|
pub fn ramsize(&self) -> u32 {
|
||||||
impl Deref for SpinalUdcRegs {
|
|
||||||
type Target = [u8];
|
|
||||||
fn deref(&self) -> &[u8] {
|
|
||||||
unsafe {
|
unsafe {
|
||||||
core::slice::from_raw_parts(self as *const SpinalUdcRegs as *const u8, core::mem::size_of::<SpinalUdcRegs>())
|
self.regs.load(Ordering::SeqCst).add(RAMSIZE_OFFSET / size_of::<u32>()).read_volatile()
|
||||||
as &[u8]
|
}
|
||||||
|
/*
|
||||||
|
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! {
|
bitfield! {
|
||||||
pub struct UdcEpStatus(u32);
|
pub struct UdcEpStatus(u32);
|
||||||
|
|
@ -111,17 +165,6 @@ bitfield! {
|
||||||
pub max_packet_size, set_max_packet_size: 31, 22;
|
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! {
|
bitfield! {
|
||||||
pub struct UdcDesc0(u32);
|
pub struct UdcDesc0(u32);
|
||||||
impl Debug;
|
impl Debug;
|
||||||
|
|
@ -153,92 +196,98 @@ bitfield! {
|
||||||
pub data1_on_completion, set_data1_on_completion: 19;
|
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
|
/// 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 SpinalUdcDescriptor {
|
||||||
pub struct SpinalUdcDescriptorHeader {
|
base: AtomicPtr::<u32>,
|
||||||
d0: UdcDesc0,
|
}
|
||||||
d1: UdcDesc1,
|
#[allow(dead_code)]
|
||||||
d2: UdcDesc2,
|
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 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],
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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) {
|
fn handle_usb(_irq_no: usize, arg: *mut usize) {
|
||||||
let usb = unsafe { &mut *(arg as *mut SpinalUsbDevice) };
|
let usb = unsafe { &mut *(arg as *mut SpinalUsbDevice) };
|
||||||
let pending = usb.csr.r(utra::usbdev::EV_PENDING);
|
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;
|
usb.ints.store(
|
||||||
// all of them will be handled here, so, clear the interrupts as needed
|
usb.regs.interrupts().0,
|
||||||
let ep_code = regs.interrupts.endpoint() as u16;
|
Ordering::SeqCst
|
||||||
regs.interrupts.clear_endpoint(ep_code as u32); // clear the interrupt bitmask
|
);
|
||||||
let mut bit = 1;
|
let mut cfg = UdcConfig(0);
|
||||||
for maybe_ep in usb.eps.lock().unwrap().iter() {
|
cfg.set_disable_ints(true); // to be enabled only when all the interrupts are handled
|
||||||
if bit & ep_code != 0 {
|
usb.regs.set_config(cfg);
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
// *** I *think* we want to halt the EP at this point so we can get the data wthout the memory being scribbled?
|
usb.regs.clear_all_interrupts();
|
||||||
|
// also: do we halt the cores??
|
||||||
} 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
|
|
||||||
};
|
|
||||||
|
|
||||||
xous::try_send_message(usb.conn,
|
xous::try_send_message(usb.conn,
|
||||||
xous::Message::new_scalar(Opcode::UsbIrqHandler.to_usize().unwrap(), 0, 0, 0, 0)).ok();
|
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 {
|
pub struct SpinalUsbMgmt {
|
||||||
csr: AtomicCsr<u32>, // consider using VolatileCell and/or refactory AtomicCsr so it is non-mutable
|
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>() }>,
|
srmem: ManagedMem<{ utralib::generated::HW_USBDEV_MEM_LEN / core::mem::size_of::<u32>() }>,
|
||||||
regs: AtomicPtr<SpinalUdcRegs>,
|
regs: SpinalUdcRegs,
|
||||||
int_err: Arc::<AtomicBool>,
|
|
||||||
was_checked: Arc::<AtomicBool>,
|
|
||||||
}
|
}
|
||||||
impl SpinalUsbMgmt {
|
impl SpinalUsbMgmt {
|
||||||
pub fn print_regs(&self) {
|
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) {
|
pub fn connect_device_core(&mut self, state: bool) {
|
||||||
log::info!("previous state: {}", self.csr.rf(utra::usbdev::USBSELECT_USBSELECT));
|
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.wo(utra::usbdev::EV_PENDING, p); // clear in case it's pending for some reason
|
||||||
self.csr.wfo(utra::usbdev::EV_ENABLE_USB, 1);
|
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 struct SpinalUsbDevice {
|
||||||
pub(crate) conn: CID,
|
pub(crate) conn: CID,
|
||||||
usb: xous::MemoryRange,
|
usb: xous::MemoryRange,
|
||||||
csr_addr: u32,
|
csr_addr: u32,
|
||||||
csr: AtomicCsr<u32>, // consider using VolatileCell and/or refactory AtomicCsr so it is non-mutable
|
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
|
// 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
|
// structure to track space allocations within the memory space
|
||||||
allocs: Arc::<Mutex::<BTreeMap<u32, u32>>>, // key is offset, value is len
|
allocs: Arc::<Mutex::<BTreeMap<u32, u32>>>, // key is offset, value is len
|
||||||
|
ints: AtomicU32,
|
||||||
tt: ticktimer_server::Ticktimer,
|
tt: ticktimer_server::Ticktimer,
|
||||||
poll_result: PollResult,
|
|
||||||
int_err: Arc::<AtomicBool>,
|
|
||||||
was_checked: Arc::<AtomicBool>,
|
|
||||||
}
|
}
|
||||||
impl SpinalUsbDevice {
|
impl SpinalUsbDevice {
|
||||||
pub fn new(sid: xous::SID) -> 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
|
// 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
|
// usb memory area. Mapping SpinalUdcRegs here is safe assuming the structure has
|
||||||
// been correctly defined.
|
// been correctly defined.
|
||||||
regs: AtomicPtr::new(unsafe {
|
regs: SpinalUdcRegs::new(unsafe{usb.as_mut_ptr().add(0xFF00) as *mut u32}),
|
||||||
(usb.as_mut_ptr().add(0xFF00) as *mut SpinalUdcRegs).as_mut().unwrap()
|
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())),
|
allocs: Arc::new(Mutex::new(BTreeMap::new())),
|
||||||
|
ints: AtomicU32::new(0),
|
||||||
tt: ticktimer_server::Ticktimer::new().unwrap(),
|
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(
|
xous::claim_interrupt(
|
||||||
|
|
@ -349,27 +429,25 @@ impl SpinalUsbDevice {
|
||||||
usbdev.csr.wfo(utra::usbdev::EV_ENABLE_USB, 1);
|
usbdev.csr.wfo(utra::usbdev::EV_ENABLE_USB, 1);
|
||||||
|
|
||||||
// also have to enable ints at the SpinalHDL layer
|
// also have to enable ints at the SpinalHDL layer
|
||||||
let regs = unsafe{usbdev.regs.load(Ordering::SeqCst).as_mut().unwrap()};
|
let mut cfg = UdcConfig(0);
|
||||||
regs.config.set_enable_ints(true);
|
cfg.set_enable_ints(true);
|
||||||
|
usbdev.regs.set_config(cfg);
|
||||||
|
|
||||||
usbdev
|
usbdev
|
||||||
}
|
}
|
||||||
pub fn get_iface(&self) -> SpinalUsbMgmt {
|
pub fn get_iface(&self) -> SpinalUsbMgmt {
|
||||||
SpinalUsbMgmt {
|
SpinalUsbMgmt {
|
||||||
csr: AtomicCsr::new(self.csr_addr as *mut u32),
|
csr: AtomicCsr::new(self.csr_addr as *mut u32),
|
||||||
srmem: ManagedMem::new(self.usb),
|
usb: AtomicPtr::new(self.usb.as_mut_ptr() as *mut u8),
|
||||||
regs: AtomicPtr::new(unsafe {
|
eps: AtomicPtr::new(unsafe {
|
||||||
(self.usb.as_mut_ptr().add(0xFF00) as *mut SpinalUdcRegs).as_mut().unwrap()
|
(self.usb.as_mut_ptr().add(0x00) as *mut UdcEpStatus).as_mut().unwrap()
|
||||||
}),
|
}),
|
||||||
int_err: self.int_err.clone(),
|
srmem: ManagedMem::new(self.usb),
|
||||||
was_checked: self.was_checked.clone(),
|
regs: self.regs.clone(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn print_poll_result(&self) {
|
fn print_poll_result(&self, poll_result: &PollResult) {
|
||||||
if self.int_err.load(Ordering::SeqCst) {
|
match poll_result {
|
||||||
log::info!("error was detected in interrupt handler: previous poll result was not used");
|
|
||||||
}
|
|
||||||
match self.poll_result {
|
|
||||||
PollResult::None => log::info!("PollResult::None"),
|
PollResult::None => log::info!("PollResult::None"),
|
||||||
PollResult::Reset => log::info!("PollResult::Reset"),
|
PollResult::Reset => log::info!("PollResult::Reset"),
|
||||||
PollResult::Resume => log::info!("PollResult::Resume"),
|
PollResult::Resume => log::info!("PollResult::Resume"),
|
||||||
|
|
@ -386,10 +464,23 @@ impl SpinalUsbDevice {
|
||||||
pub fn alloc_region(&mut self, requested: u32) -> Option<u32> {
|
pub fn alloc_region(&mut self, requested: u32) -> Option<u32> {
|
||||||
alloc_inner(&mut self.allocs.lock().unwrap(), requested)
|
alloc_inner(&mut self.allocs.lock().unwrap(), requested)
|
||||||
}
|
}
|
||||||
|
#[allow(dead_code)]
|
||||||
/// returns `true` if the region was available to be deallocated
|
/// returns `true` if the region was available to be deallocated
|
||||||
pub fn dealloc_region(&mut self, offset: u32) -> bool {
|
pub fn dealloc_region(&mut self, offset: u32) -> bool {
|
||||||
dealloc_inner(&mut self.allocs.lock().unwrap(), offset)
|
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 {
|
impl UsbBus for SpinalUsbDevice {
|
||||||
|
|
@ -419,35 +510,40 @@ impl UsbBus for SpinalUsbDevice {
|
||||||
ep_addr: Option<EndpointAddress>,
|
ep_addr: Option<EndpointAddress>,
|
||||||
ep_type: EndpointType,
|
ep_type: EndpointType,
|
||||||
max_packet_size: u16,
|
max_packet_size: u16,
|
||||||
interval: u8,
|
_interval: u8,
|
||||||
) -> Result<EndpointAddress> {
|
) -> Result<EndpointAddress> {
|
||||||
// if ep_addr is specified, create a 1-unit range else a range through the entire space
|
// 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,
|
// note that ep_addr is a packed representation of index and direction,
|
||||||
// so you must use `.index()` to get just the index part
|
// 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) {
|
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() {
|
if index == 0 && ep_dir == UsbDirection::In {
|
||||||
continue
|
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
|
// only if there is memory that can accommodate the max_packet_size
|
||||||
if let Some(offset) = self.alloc_region(max_packet_size as _) {
|
if let Some(offset) = self.alloc_region(max_packet_size as _) {
|
||||||
let ep = SpinalUdcEndpoint {
|
log::info!("allocated offset {:x}({})", offset, max_packet_size);
|
||||||
// Safety: the offset of the endpoint storage bank is defined as 0x0 + 4*index from the base of the
|
let mut ep_status = UdcEpStatus(0);
|
||||||
// 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 {
|
match ep_type {
|
||||||
EndpointType::Isochronous => ep.ep_status.set_isochronous(true),
|
EndpointType::Isochronous => ep_status.set_isochronous(true),
|
||||||
_ => ep.ep_status.set_isochronous(false),
|
_ => ep_status.set_isochronous(false),
|
||||||
}
|
}
|
||||||
log::info!("setting ep{}@{:x?} max_packet_size {}", index, offset, max_packet_size);
|
log::info!("alloc ep{}@{:x?} max_packet_size {}", index, offset, max_packet_size);
|
||||||
ep.ep_status.set_head_offset(offset / 16);
|
ep_status.set_head_offset(offset / 16);
|
||||||
ep.ep_status.set_max_packet_size(max_packet_size as u32);
|
ep_status.set_max_packet_size(max_packet_size as u32);
|
||||||
ep.ep_status.set_enable(true); // set the enable as the last op
|
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))
|
return Ok(EndpointAddress::from_parts(index as usize, ep_dir))
|
||||||
} else {
|
} else {
|
||||||
return Err(UsbError::EndpointMemoryOverflow);
|
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
|
/// 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.
|
/// there is no need to perform a USB reset in this method.
|
||||||
fn enable(&mut self) {
|
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
|
// clear all the interrupts in a single write
|
||||||
regs.interrupts.0 = 0xFFFF_FFFF;
|
self.regs.clear_all_interrupts();
|
||||||
|
|
||||||
// clear other registers
|
|
||||||
regs.address = 0;
|
|
||||||
|
|
||||||
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
|
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
|
||||||
// enable the interrupt
|
// 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);
|
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
|
/// enumeration, as well as ensure that all endpoints previously allocated with alloc_ep are
|
||||||
/// initialized as specified.
|
/// initialized as specified.
|
||||||
fn reset(&self) {
|
fn reset(&self) {
|
||||||
let regs = unsafe{self.regs.load(Ordering::SeqCst).as_mut().unwrap()};
|
log::info!("reset");
|
||||||
// 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;
|
|
||||||
|
|
||||||
// clear other registers
|
// clear other registers
|
||||||
regs.address = 0;
|
self.regs.set_address(0);
|
||||||
|
|
||||||
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
|
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets the device USB address to `addr`.
|
/// Sets the device USB address to `addr`.
|
||||||
fn set_device_address(&self, addr: u8) {
|
fn set_device_address(&self, addr: u8) {
|
||||||
let regs = unsafe{self.regs.load(Ordering::SeqCst).as_mut().unwrap()};
|
log::info!("set_addr {}", addr);
|
||||||
regs.address = addr as u32;
|
self.regs.set_address(addr as _);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Writes a single packet of data to the specified endpoint and returns number of bytes
|
/// Writes a single packet of data to the specified endpoint and returns number of bytes
|
||||||
|
|
@ -527,32 +607,32 @@ impl UsbBus for SpinalUsbDevice {
|
||||||
///
|
///
|
||||||
/// Implementations may also return other errors if applicable.
|
/// Implementations may also return other errors if applicable.
|
||||||
fn write(&self, ep_addr: EndpointAddress, buf: &[u8]) -> Result<usize> {
|
fn write(&self, ep_addr: EndpointAddress, buf: &[u8]) -> Result<usize> {
|
||||||
if let Some(ep) = &self.eps.lock().unwrap()[ep_addr.index()] {
|
log::info!("write ep{}", ep_addr.index());
|
||||||
if buf.len() > ep.ep_status.max_packet_size() as usize {
|
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)
|
Err(UsbError::BufferOverflow)
|
||||||
} else {
|
} else {
|
||||||
let base = self.usb.as_mut_ptr();
|
descriptor.set_desc0(0); // <-- somehow this needs to track across multiple packets
|
||||||
let descriptor = unsafe {
|
descriptor.set_desc1(0, buf.len());
|
||||||
(base.add(ep.ep_status.head_offset() as usize * 16) as *mut SpinalUdcDescriptorHeader).as_mut().unwrap()
|
descriptor.set_desc2(
|
||||||
};
|
UsbDirection::Out,
|
||||||
descriptor.d0.set_offset(0);
|
true,
|
||||||
descriptor.d1.set_next_offset(0);
|
true, // this should be equal to "packet_end", but this driver doesn't have that...?
|
||||||
descriptor.d1.set_length(buf.len() as u32);
|
ep_addr.index() == 0, // only trigger for ep0 (per spinal linux driver)
|
||||||
descriptor.d2.set_direction(DESC_OUT);
|
);
|
||||||
descriptor.d2.set_int_on_done(true);
|
|
||||||
let data = unsafe {
|
if buf.len() % 4 != 0 {
|
||||||
slice::from_raw_parts_mut(
|
// the linux driver doesn't handle anything other than word aligned, can we get away with it here?
|
||||||
base.add(ep.ep_status.head_offset() as usize * 16 + size_of::<SpinalUdcDescriptorHeader>()),
|
log::warn!("non word aligned buffer received, this needs to be handled");
|
||||||
ep.ep_status.max_packet_size() as usize
|
|
||||||
)};
|
|
||||||
for (&src, dst) in buf.iter().zip(data.iter_mut()) {
|
|
||||||
*dst = src;
|
|
||||||
}
|
}
|
||||||
|
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())
|
Ok(buf.len())
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
Err(UsbError::InvalidEndpoint)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reads a single packet of data from the specified endpoint and returns the actual length of
|
/// Reads a single packet of data from the specified endpoint and returns the actual length of
|
||||||
|
|
@ -574,45 +654,63 @@ impl UsbBus for SpinalUsbDevice {
|
||||||
///
|
///
|
||||||
/// Implementations may also return other errors if applicable.
|
/// Implementations may also return other errors if applicable.
|
||||||
fn read(&self, ep_addr: EndpointAddress, buf: &mut [u8]) -> Result<usize> {
|
fn read(&self, ep_addr: EndpointAddress, buf: &mut [u8]) -> Result<usize> {
|
||||||
if let Some(ep) = &self.eps.lock().unwrap()[ep_addr.index()] {
|
log::info!("read ep{}", ep_addr.index());
|
||||||
let base = self.usb.as_mut_ptr();
|
let ep_status = self.status_from_index(ep_addr.index());
|
||||||
let descriptor = unsafe {
|
let descriptor = self.descriptor_from_status(&ep_status);
|
||||||
(base.add(ep.ep_status.head_offset() as usize * 16) as *mut SpinalUdcDescriptorHeader).as_mut().unwrap()
|
if descriptor.in_progress() {
|
||||||
};
|
|
||||||
if descriptor.d0.code() == 0xF {
|
|
||||||
log::info!("read called but descriptor was in progress")
|
log::info!("read called but descriptor was in progress")
|
||||||
}
|
}
|
||||||
descriptor.d1.set_next_offset(0);
|
let len = descriptor.length();
|
||||||
descriptor.d2.set_direction(DESC_IN);
|
if buf.len() > len {
|
||||||
descriptor.d2.set_int_on_done(true);
|
return Err(UsbError::BufferOverflow)
|
||||||
let len = descriptor.d0.offset() as usize;
|
}
|
||||||
if len > buf.len() {
|
descriptor.set_desc1(0, buf.len());
|
||||||
Err(UsbError::BufferOverflow)
|
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)
|
||||||
|
}
|
||||||
|
// 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 {
|
} else {
|
||||||
let data = unsafe {
|
if len % 4 != 0 {
|
||||||
slice::from_raw_parts_mut(
|
log::info!("non-word aligned length encountered, need code to handle this case");
|
||||||
base.add(ep.ep_status.head_offset() as usize * 16 + size_of::<SpinalUdcDescriptorHeader>()),
|
}
|
||||||
ep.ep_status.max_packet_size() as usize
|
for i in 0..len / 4 {
|
||||||
)};
|
let word = descriptor.read_data(i);
|
||||||
for (&src, dst) in data[..len].iter().zip(buf.iter_mut()) {
|
for (&src, dst) in word.to_le_bytes().iter().zip(buf[i*4..(i+1)*4].iter_mut()) {
|
||||||
*dst = src;
|
*dst = src;
|
||||||
}
|
}
|
||||||
Ok(len)
|
|
||||||
}
|
}
|
||||||
} else {
|
Ok(len)
|
||||||
Err(UsbError::InvalidEndpoint)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets or clears the STALL condition for an endpoint. If the endpoint is an OUT endpoint, it
|
/// Sets or clears the STALL condition for an endpoint. If the endpoint is an OUT endpoint, it
|
||||||
/// should be prepared to receive data again.
|
/// should be prepared to receive data again.
|
||||||
fn set_stalled(&self, ep_addr: EndpointAddress, stalled: bool) {
|
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
|
// 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.
|
// we alias into the register block and force it to happen.
|
||||||
let ep_status = unsafe {
|
let mut 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()
|
||||||
};
|
};
|
||||||
|
|
||||||
match (stalled, ep_addr.direction()) {
|
match (stalled, ep_addr.direction()) {
|
||||||
(true, UsbDirection::In) => {
|
(true, UsbDirection::In) => {
|
||||||
ep_status.set_force_nack(false);
|
ep_status.set_force_nack(false);
|
||||||
|
|
@ -625,13 +723,18 @@ impl UsbBus for SpinalUsbDevice {
|
||||||
},
|
},
|
||||||
(false, UsbDirection::Out) => ep_status.set_force_stall(false),
|
(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.
|
/// Gets whether the STALL condition is set for an endpoint.
|
||||||
fn is_stalled(&self, ep_addr: EndpointAddress) -> bool {
|
fn is_stalled(&self, ep_addr: EndpointAddress) -> bool {
|
||||||
let ep_status = unsafe {
|
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()
|
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
|
/// Gets information about events and incoming data. Usually called in a loop or from an
|
||||||
/// interrupt handler. See the [`PollResult`] struct for more information.
|
/// interrupt handler. See the [`PollResult`] struct for more information.
|
||||||
fn poll(&self) -> PollResult {
|
fn poll(&self) -> PollResult {
|
||||||
if self.int_err.load(Ordering::SeqCst) {
|
let mut interrupts = UdcInterrupts(self.ints. load(Ordering::SeqCst));
|
||||||
log::warn!("interrupt triggered twice before handler got to it; an event was lost");
|
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;
|
||||||
}
|
}
|
||||||
self.was_checked.store(true, Ordering::SeqCst);
|
interrupts.set_endpoint(interrupts.endpoint() & !(1 << bit));
|
||||||
self.print_poll_result();
|
break;
|
||||||
// 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},
|
|
||||||
}
|
}
|
||||||
|
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
|
/// 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
|
/// * [`Unsupported`](crate::UsbError::Unsupported) - This UsbBus implementation doesn't support
|
||||||
/// simulating a disconnect or it has not been enabled at creation time.
|
/// simulating a disconnect or it has not been enabled at creation time.
|
||||||
fn force_reset(&self) -> Result<()> {
|
fn force_reset(&self) -> Result<()> {
|
||||||
|
log::info!("force_reset");
|
||||||
self.csr.wfo(utra::usbdev::USBSELECT_USBSELECT, 0);
|
self.csr.wfo(utra::usbdev::USBSELECT_USBSELECT, 0);
|
||||||
self.tt.sleep_ms(5).unwrap();
|
self.tt.sleep_ms(5).unwrap();
|
||||||
self.csr.wfo(utra::usbdev::USBSELECT_USBSELECT, 1);
|
self.csr.wfo(utra::usbdev::USBSELECT_USBSELECT, 1);
|
||||||
|
|
|
||||||
|
|
@ -7,8 +7,6 @@ use api::*;
|
||||||
#[cfg(any(target_os = "none", target_os = "xous"))]
|
#[cfg(any(target_os = "none", target_os = "xous"))]
|
||||||
mod kbd;
|
mod kbd;
|
||||||
#[cfg(any(target_os = "none", target_os = "xous"))]
|
#[cfg(any(target_os = "none", target_os = "xous"))]
|
||||||
use kbd::*;
|
|
||||||
#[cfg(any(target_os = "none", target_os = "xous"))]
|
|
||||||
mod hw;
|
mod hw;
|
||||||
#[cfg(any(target_os = "none", target_os = "xous"))]
|
#[cfg(any(target_os = "none", target_os = "xous"))]
|
||||||
use hw::*;
|
use hw::*;
|
||||||
|
|
@ -62,7 +60,7 @@ fn xmain() -> ! {
|
||||||
|
|
||||||
let usbdev = SpinalUsbDevice::new(usbdev_sid);
|
let usbdev = SpinalUsbDevice::new(usbdev_sid);
|
||||||
let mut usbmgmt = usbdev.get_iface();
|
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();
|
let tt = ticktimer_server::Ticktimer::new().unwrap();
|
||||||
log::info!("connecting device core");
|
log::info!("connecting device core");
|
||||||
usbmgmt.connect_device_core(true);
|
usbmgmt.connect_device_core(true);
|
||||||
|
|
@ -92,25 +90,30 @@ fn xmain() -> ! {
|
||||||
cid
|
cid
|
||||||
).expect("couldn't create suspend/resume object");
|
).expect("couldn't create suspend/resume object");
|
||||||
|
|
||||||
|
log::info!("alloc");
|
||||||
let usb_alloc = UsbBusAllocator::new(usbdev);
|
let usb_alloc = UsbBusAllocator::new(usbdev);
|
||||||
|
|
||||||
|
log::info!("clock");
|
||||||
let clock = EmbeddedClock::new();
|
let clock = EmbeddedClock::new();
|
||||||
|
log::info!("hid");
|
||||||
let mut keyboard = UsbHidClassBuilder::new()
|
let mut keyboard = UsbHidClassBuilder::new()
|
||||||
.add_interface(
|
.add_interface(
|
||||||
NKROBootKeyboardInterface::default_config(&clock),
|
NKROBootKeyboardInterface::default_config(&clock),
|
||||||
)
|
)
|
||||||
.build(&usb_alloc);
|
.build(&usb_alloc);
|
||||||
|
|
||||||
|
log::info!("dev");
|
||||||
let mut usb_dev = UsbDeviceBuilder::new(&usb_alloc, UsbVidPid(0x1209, 0x0001))
|
let mut usb_dev = UsbDeviceBuilder::new(&usb_alloc, UsbVidPid(0x1209, 0x0001))
|
||||||
.manufacturer("usbd-human-interface-device")
|
.manufacturer("usbd-human-interface-device")
|
||||||
.product("NKRO Keyboard")
|
.product("NKRO Keyboard")
|
||||||
.serial_number("PRECURSOR")
|
.serial_number("PRECURSOR")
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
|
log::info!("main");
|
||||||
let mut cmdline = String::new();
|
let mut cmdline = String::new();
|
||||||
loop {
|
loop {
|
||||||
let msg = xous::receive_message(usbdev_sid).unwrap();
|
let msg = xous::receive_message(usbdev_sid).unwrap();
|
||||||
|
log::info!("msg: {:?}", msg);
|
||||||
match FromPrimitive::from_usize(msg.body.id()) {
|
match FromPrimitive::from_usize(msg.body.id()) {
|
||||||
Some(Opcode::SuspendResume) => xous::msg_scalar_unpack!(msg, token, _, _, _, {
|
Some(Opcode::SuspendResume) => xous::msg_scalar_unpack!(msg, token, _, _, _, {
|
||||||
kbd.suspend();
|
kbd.suspend();
|
||||||
|
|
@ -271,6 +274,7 @@ pub(crate) fn alloc_inner(allocs: &mut BTreeMap<u32, u32>, requested: u32) -> Op
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#[allow(dead_code)]
|
||||||
pub(crate) fn dealloc_inner(allocs: &mut BTreeMap<u32, u32>, offset: u32) -> bool {
|
pub(crate) fn dealloc_inner(allocs: &mut BTreeMap<u32, u32>, offset: u32) -> bool {
|
||||||
allocs.remove(&offset).is_some()
|
allocs.remove(&offset).is_some()
|
||||||
}
|
}
|
||||||
|
|
|
||||||
1807
services/usb-test/src/spinal_udc.c
Normal file
1807
services/usb-test/src/spinal_udc.c
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Reference in a new issue