Merge branch 'main' of github.com:betrusted-io/xous-core

This commit is contained in:
Sean Cross 2021-09-15 17:18:14 +08:00
commit 45d8124418
42 changed files with 7613 additions and 536 deletions

364
API.md Normal file
View file

@ -0,0 +1,364 @@
## Xous Messaging API In Practice
Here are the idioms for building servers and passing messages.
### api.rs
Incoming messages are defined in an `Opcode` enum, by convention
```rust
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum Opcode {
ExampleScalar,
ExampleBlockingScalar,
ExampleMemory,
ExampleMemoryWithReturn,
RegisterCallback,
UnregisterCallback,
}
```
Synchronous return messages are defined in a `Return` enum, by convention
```rust
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) enum Return {
ExampleMemoryReturn(RichMemStruct),
Failure,
}
```
Asynchronous callback messages are defined in a `Callback` enum, by convention
```rust
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) enum Callback {
Hello,
Drop,
}
```
Rich memory structures for IPC are also defined in the api.rs crate. These may or may not
be scoped to crate-local.
```rust
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) struct RichMemStruct {
pub name: xous_ipc::String::<64>,
pub stuff: [u32; 42],
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct AnotherRichStruct {
pub name: xous_ipc::String::<64>,
pub other: Option<bool>,
}
```
A server name is also defined in api.rs. This is a human-readable, 64-byte
description that uniquely identifies your server to the name server. This is
later mapped to a random 64-bit ID that only the name server knows.
```rust
pub(crate) const MY_SERVER_NAME: &str = "_Example server_"; // the underscores are optional, but they help readability in logs
```
### lib.rs
Client state is held in an object defined in lib.rs.
```rust
#![cfg_attr(target_os = "none", no_std)]
pub mod api;
use api::{Callback, Opcode}; // if you prefer to map the api into your local namespace
use xous::{send_message, Error, CID, Message, msg_scalar_unpack};
use xous_ipc::{String, Buffer};
use num_traits::{ToPrimitive, FromPrimitive};
pub struct MyServer {
conn: xous::CID,
callback_sid: Option<xous::SID>, // this is only necessary if you have callbacks
}
impl MyServer {
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
let conn = xns.request_connection_blocking(api::MY_SERVER_NAME).expect("Can't connect to MyServer");
Ok(MyServer {
conn,
callback_sid: None,
})
}
/// an example of a client requesting to send a message to MyServer
/// you can pass up to four usize-args this way, this example has none and just sends 4 zeros as placeholders
pub fn send_example_scalar(&self) -> Result<(), xous::Error> {
send_message(self.conn,
Message::new_scalar(Opcode::ExampleScalar.to_usize().unwrap()), 0, 0, 0, 0)
).map(|_|())
}
/// if you want some return data, a blocking scalar is the way to go
/// in this case, we introduce two arbitrary args, `a` and `b`, and return a u32
pub fn send_example_scalar(&self, a: u32, b: u32) -> Result<u32, xous::Error> {
let response = send_message(self.conn,
Message::new_blocking_scalar(Opcode::ExampleBlockingScalar.to_usize().unwrap()), a, b, 0, 0)
).expect("ExampleBlockingScalar failed");
// you could also receive two scalar values if you use Scalar2 instead of Scalar1
if let xous::Result::Scalar1(result) = response {
Ok(result as u32)
} else {
log::error!("unexpected return value: {:#?}", response);
Err(xous::Error::InternalError)
}
}
/// an example of sending a rich data structure
pub fn send_richdata(&self, words: &str, stuff: [u32; 42]) -> Result<(), xous::Error> {
// build the structure up. Note that RichMemStruct is just inside the API! the caller doesn't need to know about it.
let mut rich_struct = RichMemStruct {
name: String::<64>::new(),
stuff,
};
use core::fmt::Write;
write!(rich_struct.name, "{}", words).expect("words too long");
// now convert it into a Xous::Buffer, which can then be lent to the server
let buf = Buffer::into_buf(rich_struct).or(Err(xous::Error::InternalError))?;
buf.lend(self.conn, Opcode::ExampleMemory.to_u32().unwrap()).map(|_| ())
}
/// an example of rich data with a return type
pub fn get_richdata(&self, stuff: [u32; 42]) -> Result<AnotherRichStruct, xous::Error> {
// build the query up. We're going to re-use RichMemStruct, but it could be anything
let mut rich_struct = RichMemStruct {
name: String::<64>::from_str("example rich query"),
stuff,
};
// now convert it into a Xous::Buffer, which can then be mutably lent to the server
let mut buf = Buffer::into_buf(rich_struct).or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.conn, Opcode::ExampleMemoryWithReturn.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
// note that to_original() creates a local copy on the stack of the returned buffer
// if you just need to access fields, you can use to_flat() which is a
// zerocopy operation on an "Archived" version of your structure
match buf.to_original().unwrap() {
api::Return::ExampleMemoryReturn(rms) => {
Ok( AnotherRichStruct {
name: String::<64>::from_str(rms.name),
other: None,
} )
}
api::Return::Failure => {
Err(xous::Error::InternalError)
}
_ => panic!("Got unknown return code")
}
}
/// an example of registering for a callback
static mut MYSERVER_CB: Option<fn(BattStats)> = None; // this actually goes outside the object decl
pub fn hook_callback(&mut self, cb: fn(u32)) -> Result<(), xous::Error> {
if unsafe{MYSERVER_CB}.is_some() {
return Err(xous::Error::MemoryInUse) // can't hook it twice
}
let sid_tuple = (u32, u32, u32, u32);
unsafe{MYSERVER_CB = Some(cb)};
if let Some(sid) = self.callback_sid {
sid_tuple = sid.to_u32();
} else {
let sid = xous::create_server().unwrap();
self.callback_sid = Some(sid);
sid_tuple = sid.to_u32();
xous::create_thread_4(callback_server, sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize).unwrap();
}
xous::send_message(self.conn,
Message::new_scalar(Opcode::RegisterCallback.to_usize().unwrap(),
sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize
)).unwrap();
Ok(())
}
pub fn unhook_callback(&mut self) -> Result<(), xous::Error> {
unsafe{MYSERVER_CB = None};
if let Some(sid) = self.callback_sid {
let sid_tuple = sid.to_u32();
xous::send_message(self.conn,
Message::new_scalar(Opcode::UnregisterCallback.to_usize().unwrap(),
sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize
)).unwrap();
}
Ok(())
}
}
/// handles callback messages from server, in the library user's process space.
fn callback_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
let sid = xous::SID::from_u32(sid0 as u32, sid1 as u32, sid2 as u32, sid3 as u32);
loop {
let msg = xous::receive_message(sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(Callback::Hello) => msg_scalar_unpack!(msg, a, _, _, _, {
unsafe {
if let Some(cb) = MYSERVER_CB {
cb(a as u32)
} else {
// this results in a race condition between the unregister message and the actual
// unregistration. In this case, just ignore the message.
continue;
}
}
}),
Some(Callback::Drop) => {
break; // this exits the loop and kills the thread
}
None => (),
}
}
xous::destroy_server(sid).unwrap();
}
impl Drop for MyServer {
fn drop(&mut self) {
// if we have callbacks, destroy the callback server
if let Some(sid) = self.callback_sid.take() {
// no need to tell the upstream server we're quitting: the next time a callback processes,
// it will automatically remove my entry as it will receive a ServerNotFound error.
// tell my handler thread to quit
let cid = xous::connect(sid).unwrap();
xous::send_message(cid,
Message::new_scalar(api::Callback::Drop.to_usize().unwrap(), 0, 0, 0, 0)).unwrap();
unsafe{xous::disconnect(cid).unwrap();}
}
// now de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection.
// all implementations will need this
unsafe{xous::disconnect(self.conn).unwrap();}
}
}
// reference counting implementation for servers that can be cloned or have multiple instances in a thread
//REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed);
use core::sync::atomic::{AtomicU32, Ordering};
static REFCOUNT: AtomicU32 = AtomicU32::new(0);
impl Drop for Codec {
fn drop(&mut self) {
// de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection.
if REFCOUNT.load(Ordering::Relaxed) == 0 {
unsafe{xous::disconnect(self.conn).unwrap();}
}
}
}
```
### main.rs
The server implementation is in main.rs. It handles the requests coming from lib.rs.
Here is a generic template example that doesn't do very much, other than exercise the four
API cases laid out above: sending a scalar message, handling a blocking scalar (e.g. scalar
message with return value), a "lend" memory message, and a "mutable lend" memory message (e.g.
a memory message with return value).
Note that all message types block the caller until they are returned.
```rust
#![cfg_attr(target_os = "none", no_std)]
#![cfg_attr(target_os = "none", no_main)]
use num_traits::FromPrimitive;
use xous_ipc::{String, Buffer};
use api::Opcode;
use xous::{CID, msg_scalar_unpack, msg_blocking_scalar_unpack};
#[xous::xous_main]
fn xmain() -> ! {
log_server::init_wait().unwrap();
info!("my PID is {}", xous::process::id()); // this is so we can figure out what PID goes to what server
let xns = xous_names::XousNames::new().unwrap();
let my_sid = xns.register_name(api::MY_SERVER_NAME).expect("can't register server");
trace!("registered with NS -- {:?}", sid);
// only needed if doing callbacks
let mut cb_conns: [bool; xous::MAX_CID] = [false; xous::MAX_CID]; // 34 to hold maximum connection ID number
loop {
let msg = xous::receive_message(sid).unwrap(); // this blocks until we get a message
trace!("Message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::ExampleScalar) => msg_scalar_unpack!(msg, _, _, _, _, { /* what the scalar message does */ }),
Some(Opcode::ExampleBlockingScalar) => msg_blocking_scalar_unpack!(msg, a, b, _, _, {
let value = a + b;
xous::return_scalar(msg.sender, value).expect("couldn't return value to ExampleBlockingScalar");
// note that you can also return two usize values with return_scalar2
}),
Some(Opcode::ExampleMemory) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let rms = buffer.as_flat::<RichMemStruct, _>().unwrap();
// we can now access fields in rms without copying the data
// use to_original if you need to invoke methods on the struct object
}
Some(Opcode::ExampleMemoryWithReturn) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let rms = buffer.to_original::<RichMemStruct, _>().unwrap();
let response = api::Return;
if things_look_okay {
let retstruct = AnotherRichStruct {
name: String::<64>::from_str(rms.as_str()),
other: Some(true),
}
response = api::Return::ExampleMemoryReturn(retstruct);
} else {
response = api::Return::Failure
}
buffer.replace(response).unwrap(); // the buffer that was sent is replaced with AnotherRichStruct
}
// only needed if doing callbacks
Some(Opcode::RegisterCallback) => msg_scalar_unpack!(msg, sid0, sid1, sid2, sid3, {
let sid = xous::SID::from_u32(sid0 as _, sid1 as _, sid2 as _, sid3 as _);
let cid = xous::connect(sid).unwrap();
if (cid as usize) < cb_conns.len() {
cb_conns[cid as usize] = true;
} else {
error!("RegisterCallback CID out of range");
}
}
),
Some(Opcode::UnregisterCallback) => msg_scalar_unpack!(msg, sid0, sid1, sid2, sid3, {
let sid = xous::SID::from_u32(sid0 as _, sid1 as _, sid2 as _, sid3 as _);
let cid = xous::connect(sid).unwrap();
if (cid as usize) < cb_conns.len() {
cb_conns[cid as usize] = false;
} else {
error!("UnregisterCallback CID out of range");
}
unsafe{xous::disconnect(cid).unwrap()};
})
None => log::error!("couldn't convert opcode")
}
// if you have callbacks, you'll probably want to start a separate thread to handle them
// but for simplicity we just call a function here. But in this example, it means the callback
// can only gets processed after any message is received.
do_callback(&mut cb_conns);
}
}
/// only if doing callbacks. This might actually make more sense in a thread of its own, to make it
/// truly asynchronous, but this example is focused on the messaging API, not the threading API.
/// This example admittedly sweeps a rather hairy issue (passing data between process-local threads)
/// under the carpet. As of Xous 0.8 your options to send data around between threads within a process
/// are:
/// 1. Define a crate-local API to pass the messages
/// 2. Use Atomic data types (only applicable if you have primitive data to send)
/// 3. Do some static mut unsafe thing because we don't have a Mutex data type yet.
fn do_callback(cb_conns: &mut [bool; xous::MAX_CID]) {
let a = useful_computation();
for cid in 1..cb_conns {
if cb_conns[cid] {
match xous::send_message(cid,
xous::Message::new_scalar(api::Callback::Hello.to_usize().unwrap(), a, 0, 0, 0)
) {
Err(xous::Error::ServerNotFound) => {
cb_conns[cid] = false // automatically de-allocate callbacks for clients that have dropped
},
Ok(xous::Result::Ok) => {}
_ => panic!("unhandled error or result in callback processing")
}
}
}
}
```

200
Cargo.lock generated
View file

@ -61,9 +61,9 @@ dependencies = [
[[package]]
name = "anyhow"
version = "1.0.38"
version = "1.0.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afddf7f520a80dbf76e6f50a35bca42a2331ef227a28b3b6dc5c2e2338d114b1"
checksum = "28ae2b3dec75a406790005a200b1bd89785afc02517a00ca99ecfe093ee9e6cf"
[[package]]
name = "atty"
@ -372,7 +372,7 @@ dependencies = [
"ansi_term",
"atty",
"bitflags",
"strsim",
"strsim 0.8.0",
"textwrap",
"unicode-width",
"vec_map",
@ -418,6 +418,7 @@ dependencies = [
"rkyv 0.4.3",
"susres",
"ticktimer-server",
"trng",
"typenum",
"utralib",
"xous",
@ -428,7 +429,7 @@ dependencies = [
[[package]]
name = "com_rs"
version = "0.1.0"
source = "git+https://github.com/betrusted-io/com_rs.git?rev=8959b373adc359f03a0da7c000bd8208b47d90a7#8959b373adc359f03a0da7c000bd8208b47d90a7"
source = "git+https://github.com/betrusted-io/com_rs.git?rev=5338f9959572d57f1014d04aa129804da5b4d339#5338f9959572d57f1014d04aa129804da5b4d339"
[[package]]
name = "com_rs-ref"
@ -557,6 +558,41 @@ dependencies = [
"zeroize",
]
[[package]]
name = "darling"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "757c0ded2af11d8e739c4daea1ac623dd1624b06c844cf3f5a39f1bdbd99bb12"
dependencies = [
"darling_core",
"darling_macro",
]
[[package]]
name = "darling_core"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c34d8efb62d0c2d7f60ece80f75e5c63c1588ba68032740494b0b9a996466e3"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
"strsim 0.10.0",
"syn",
]
[[package]]
name = "darling_macro"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ade7bff147130fe5e6d39f089c6bd49ec0250f35d70b2eebf72afdfc919f15cc"
dependencies = [
"darling_core",
"quote",
"syn",
]
[[package]]
name = "debug-here"
version = "0.2.2"
@ -676,6 +712,16 @@ dependencies = [
"termcolor",
]
[[package]]
name = "eyre"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "221239d1d5ea86bf5d6f91c9d6bc3646ffe471b08ff9b0f91c44f115ac969d2b"
dependencies = [
"indenter",
"once_cell",
]
[[package]]
name = "failure"
version = "0.1.8"
@ -709,6 +755,21 @@ dependencies = [
"miniz_oxide",
]
[[package]]
name = "float-cmp"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1267f4ac4f343772758f7b1bdcbe767c218bbab93bb432acbf5162bbf85a6c4"
dependencies = [
"num-traits",
]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "gam"
version = "0.1.0"
@ -844,6 +905,12 @@ version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
[[package]]
name = "ident_case"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "ime-frontend"
version = "0.1.0"
@ -897,6 +964,12 @@ dependencies = [
"xous-names",
]
[[package]]
name = "indenter"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce23b50ad8242c51a442f3ff322d56b02f08852c77e4c0b4d3fd684abc89c683"
[[package]]
name = "itoa"
version = "0.4.7"
@ -986,6 +1059,12 @@ dependencies = [
"winapi",
]
[[package]]
name = "libm"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7d73b3f436185384286bd8098d17ec07c9a7d2388a6599f824d8502b529702a"
[[package]]
name = "libz-sys"
version = "1.1.3"
@ -1070,6 +1149,16 @@ dependencies = [
"autocfg",
]
[[package]]
name = "microfft"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b04ffc2e74da5513185343835177bfd4adf718986185c6d81c2ae2c6ebc07637"
dependencies = [
"num-complex",
"static_assertions",
]
[[package]]
name = "minifb"
version = "0.19.3"
@ -1130,6 +1219,15 @@ dependencies = [
"version_check",
]
[[package]]
name = "num-complex"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26873667bbbb7c5182d4a37c1add32cdf09f841af72da53318fdb81543c15085"
dependencies = [
"num-traits",
]
[[package]]
name = "num-derive"
version = "0.3.3"
@ -1247,9 +1345,9 @@ checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5"
[[package]]
name = "proc-macro2"
version = "1.0.24"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71"
checksum = "5c7ed8b8c7b886ea3ed7dde405212185f423ab44682667c8c6dd14aa1d9f6612"
dependencies = [
"unicode-xid",
]
@ -1291,9 +1389,9 @@ dependencies = [
[[package]]
name = "quote"
version = "1.0.8"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "991431c3519a3f36861882da93630ce66b52918dcf1b8e2fd66b397fc96f28df"
checksum = "c3d0b9745dc2debf507c8422de05d7226cc1f0644216dfdfead988f9b1ab32a7"
dependencies = [
"proc-macro2",
]
@ -1612,6 +1710,12 @@ dependencies = [
"semver",
]
[[package]]
name = "rustversion"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61b3909d758bb75c79f23d4736fac9433868679d3ad2ea7a61e3c25cfda9a088"
[[package]]
name = "ryu"
version = "1.0.5"
@ -1664,9 +1768,23 @@ checksum = "568a8e6258aa33c13358f81fd834adb854c6f7c9468520910a9b1e8fac068012"
[[package]]
name = "serde"
version = "1.0.123"
version = "1.0.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92d5161132722baa40d802cc70b15262b98258453e85e5d1d365c757c73869ae"
checksum = "d1f72836d2aa753853178eda473a3b9d8e4eefdaf20523b919677e6de489f8f1"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e57ae87ad533d9a56427558b516d0adac283614e347abf85b0dc0cbbf0a249f3"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
@ -1679,6 +1797,30 @@ dependencies = [
"serde",
]
[[package]]
name = "serde_with"
version = "1.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ad9fdbb69badc8916db738c25efd04f0a65297d26c2f8de4b62e57b8c12bc72"
dependencies = [
"hex",
"rustversion",
"serde",
"serde_with_macros",
]
[[package]]
name = "serde_with_macros"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1569374bd54623ec8bd592cf22ba6e03c0f177ff55fbc8c29a49e296e7adecf"
dependencies = [
"darling",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "sha2"
version = "0.9.5"
@ -1731,6 +1873,7 @@ dependencies = [
"root-keys",
"rtc",
"sha2",
"spectrum-analyzer",
"spinor",
"susres",
"ticktimer-server",
@ -1771,6 +1914,17 @@ dependencies = [
"winapi",
]
[[package]]
name = "spectrum-analyzer"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b3c55cf9ba96815eb07435b381048ea2d031b21223b850bdba7d401eaae6388"
dependencies = [
"float-cmp",
"libm",
"microfft",
]
[[package]]
name = "spin"
version = "0.5.2"
@ -1799,6 +1953,12 @@ dependencies = [
"xous-names",
]
[[package]]
name = "static_assertions"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "status"
version = "0.1.0"
@ -1833,6 +1993,12 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]
name = "subtle"
version = "2.4.0"
@ -1876,9 +2042,9 @@ dependencies = [
[[package]]
name = "syn"
version = "1.0.67"
version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6498a9efc342871f91cc2d0d694c674368b4ceb40f62b65a7a08c3792935e702"
checksum = "b7f58f7e8eaa0009c5fec437aabf511bd9933e4b2d7407bd05273c01a8906ea7"
dependencies = [
"proc-macro2",
"quote",
@ -2308,6 +2474,16 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "wycheproof-import"
version = "0.1.0"
dependencies = [
"eyre",
"serde",
"serde_json",
"serde_with",
]
[[package]]
name = "x11-dl"
version = "2.18.5"

View file

@ -77,6 +77,7 @@ members = [
"services/spinor",
"services/root-keys",
"services/jtag",
"tools/wycheproof-import",
]
resolver = "2"
@ -110,8 +111,7 @@ path = "services/engine-sha512"
git="https://github.com/betrusted-io/curve25519-dalek.git"
branch="main"
#path = "../curve25519-dalek" # when doing local dev work
default-features = false
features = ["u32_backend", "betrusted"]
# feature overrides are specified at the crate level
[patch."https://github.com/betrusted-io/xous-engine-25519.git"]
engine-25519 = {path = "services/engine-25519"}

View file

@ -63,367 +63,3 @@ compatibility, over refactoring and improvement.
- Incorporation of `msg_scalar_unpack!()`, `msg_blocking_scalar_unpack!()`, `new_scalar()`,
and `new_blocking_scalar()` to de-clutter code and make scalar messages a little bit
easier to deal with
## Xous 0.8 Messaging API In Practice
Here are the idioms for building servers and passing messages.
### api.rs
Incoming messages are defined in an `Opcode` enum, by convention
```rust
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum Opcode {
ExampleScalar,
ExampleBlockingScalar,
ExampleMemory,
ExampleMemoryWithReturn,
RegisterCallback,
UnregisterCallback,
}
```
Synchronous return messages are defined in a `Return` enum, by convention
```rust
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) enum Return {
ExampleMemoryReturn(RichMemStruct),
Failure,
}
```
Asynchronous callback messages are defined in a `Callback` enum, by convention
```rust
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) enum Callback {
Hello,
Drop,
}
```
Rich memory structures for IPC are also defined in the api.rs crate. These may or may not
be scoped to crate-local.
```rust
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) struct RichMemStruct {
pub name: xous_ipc::String::<64>,
pub stuff: [u32; 42],
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct AnotherRichStruct {
pub name: xous_ipc::String::<64>,
pub other: Option<bool>,
}
```
A server name is also defined in api.rs. This is a human-readable, 64-byte
description that uniquely identifies your server to the name server. This is
later mapped to a random 64-bit ID that only the name server knows.
```rust
pub(crate) const MY_SERVER_NAME: &str = "_Example server_"; // the underscores are optional, but they help readability in logs
```
### lib.rs
Client state is held in an object defined in lib.rs.
```rust
#![cfg_attr(target_os = "none", no_std)]
pub mod api;
use api::{Callback, Opcode}; // if you prefer to map the api into your local namespace
use xous::{send_message, Error, CID, Message, msg_scalar_unpack};
use xous_ipc::{String, Buffer};
use num_traits::{ToPrimitive, FromPrimitive};
pub struct MyServer {
conn: xous::CID,
callback_sid: Option<xous::SID>, // this is only necessary if you have callbacks
}
impl MyServer {
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
let conn = xns.request_connection_blocking(api::MY_SERVER_NAME).expect("Can't connect to MyServer");
Ok(MyServer {
conn,
callback_sid: None,
})
}
/// an example of a client requesting to send a message to MyServer
/// you can pass up to four usize-args this way, this example has none and just sends 4 zeros as placeholders
pub fn send_example_scalar(&self) -> Result<(), xous::Error> {
send_message(self.conn,
Message::new_scalar(Opcode::ExampleScalar.to_usize().unwrap()), 0, 0, 0, 0)
).map(|_|())
}
/// if you want some return data, a blocking scalar is the way to go
/// in this case, we introduce two arbitrary args, `a` and `b`, and return a u32
pub fn send_example_scalar(&self, a: u32, b: u32) -> Result<u32, xous::Error> {
let response = send_message(self.conn,
Message::new_blocking_scalar(Opcode::ExampleBlockingScalar.to_usize().unwrap()), a, b, 0, 0)
).expect("ExampleBlockingScalar failed");
// you could also receive two scalar values if you use Scalar2 instead of Scalar1
if let xous::Result::Scalar1(result) = response {
Ok(result as u32)
} else {
log::error!("unexpected return value: {:#?}", response);
Err(xous::Error::InternalError)
}
}
/// an example of sending a rich data structure
pub fn send_richdata(&self, words: &str, stuff: [u32; 42]) -> Result<(), xous::Error> {
// build the structure up. Note that RichMemStruct is just inside the API! the caller doesn't need to know about it.
let mut rich_struct = RichMemStruct {
name: String::<64>::new(),
stuff,
};
use core::fmt::Write;
write!(rich_struct.name, "{}", words).expect("words too long");
// now convert it into a Xous::Buffer, which can then be lent to the server
let buf = Buffer::into_buf(rich_struct).or(Err(xous::Error::InternalError))?;
buf.lend(self.conn, Opcode::ExampleMemory.to_u32().unwrap()).map(|_| ())
}
/// an example of rich data with a return type
pub fn get_richdata(&self, stuff: [u32; 42]) -> Result<AnotherRichStruct, xous::Error> {
// build the query up. We're going to re-use RichMemStruct, but it could be anything
let mut rich_struct = RichMemStruct {
name: String::<64>::from_str("example rich query"),
stuff,
};
// now convert it into a Xous::Buffer, which can then be mutably lent to the server
let mut buf = Buffer::into_buf(rich_struct).or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.conn, Opcode::ExampleMemoryWithReturn.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
// note that to_original() creates a local copy on the stack of the returned buffer
// if you just need to access fields, you can use to_flat() which is a
// zerocopy operation on an "Archived" version of your structure
match buf.to_original().unwrap() {
api::Return::ExampleMemoryReturn(rms) => {
Ok( AnotherRichStruct {
name: String::<64>::from_str(rms.name),
other: None,
} )
}
api::Return::Failure => {
Err(xous::Error::InternalError)
}
_ => panic!("Got unknown return code")
}
}
/// an example of registering for a callback
static mut MYSERVER_CB: Option<fn(BattStats)> = None; // this actually goes outside the object decl
pub fn hook_callback(&mut self, cb: fn(u32)) -> Result<(), xous::Error> {
if unsafe{MYSERVER_CB}.is_some() {
return Err(xous::Error::MemoryInUse) // can't hook it twice
}
let sid_tuple = (u32, u32, u32, u32);
unsafe{MYSERVER_CB = Some(cb)};
if let Some(sid) = self.callback_sid {
sid_tuple = sid.to_u32();
} else {
let sid = xous::create_server().unwrap();
self.callback_sid = Some(sid);
sid_tuple = sid.to_u32();
xous::create_thread_4(callback_server, sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize).unwrap();
}
xous::send_message(self.conn,
Message::new_scalar(Opcode::RegisterCallback.to_usize().unwrap(),
sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize
)).unwrap();
Ok(())
}
pub fn unhook_callback(&mut self) -> Result<(), xous::Error> {
unsafe{MYSERVER_CB = None};
if let Some(sid) = self.callback_sid {
let sid_tuple = sid.to_u32();
xous::send_message(self.conn,
Message::new_scalar(Opcode::UnregisterCallback.to_usize().unwrap(),
sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize
)).unwrap();
}
Ok(())
}
}
/// handles callback messages from server, in the library user's process space.
fn callback_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
let sid = xous::SID::from_u32(sid0 as u32, sid1 as u32, sid2 as u32, sid3 as u32);
loop {
let msg = xous::receive_message(sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(Callback::Hello) => msg_scalar_unpack!(msg, a, _, _, _, {
unsafe {
if let Some(cb) = MYSERVER_CB {
cb(a as u32)
} else {
// this results in a race condition between the unregister message and the actual
// unregistration. In this case, just ignore the message.
continue;
}
}
}),
Some(Callback::Drop) => {
break; // this exits the loop and kills the thread
}
None => (),
}
}
xous::destroy_server(sid).unwrap();
}
impl Drop for MyServer {
fn drop(&mut self) {
// if we have callbacks, destroy the callback server
if let Some(sid) = self.callback_sid.take() {
// no need to tell the upstream server we're quitting: the next time a callback processes,
// it will automatically remove my entry as it will receive a ServerNotFound error.
// tell my handler thread to quit
let cid = xous::connect(sid).unwrap();
xous::send_message(cid,
Message::new_scalar(api::Callback::Drop.to_usize().unwrap(), 0, 0, 0, 0)).unwrap();
unsafe{xous::disconnect(cid).unwrap();}
}
// now de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection.
// all implementations will need this
unsafe{xous::disconnect(self.conn).unwrap();}
}
}
// reference counting implementation for servers that can be cloned or have multiple instances in a thread
//REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed);
use core::sync::atomic::{AtomicU32, Ordering};
static REFCOUNT: AtomicU32 = AtomicU32::new(0);
impl Drop for Codec {
fn drop(&mut self) {
// de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection.
if REFCOUNT.load(Ordering::Relaxed) == 0 {
unsafe{xous::disconnect(self.conn).unwrap();}
}
}
}
```
### main.rs
The server implementation is in main.rs. It handles the requests coming from lib.rs.
Here is a generic template example that doesn't do very much, other than exercise the four
API cases laid out above: sending a scalar message, handling a blocking scalar (e.g. scalar
message with return value), a "lend" memory message, and a "mutable lend" memory message (e.g.
a memory message with return value).
Note that all message types block the caller until they are returned.
```rust
#![cfg_attr(target_os = "none", no_std)]
#![cfg_attr(target_os = "none", no_main)]
use num_traits::FromPrimitive;
use xous_ipc::{String, Buffer};
use api::Opcode;
use xous::{CID, msg_scalar_unpack, msg_blocking_scalar_unpack};
#[xous::xous_main]
fn xmain() -> ! {
log_server::init_wait().unwrap();
info!("my PID is {}", xous::process::id()); // this is so we can figure out what PID goes to what server
let xns = xous_names::XousNames::new().unwrap();
let my_sid = xns.register_name(api::MY_SERVER_NAME).expect("can't register server");
trace!("registered with NS -- {:?}", sid);
// only needed if doing callbacks
let mut cb_conns: [bool; xous::MAX_CID] = [false; xous::MAX_CID]; // 34 to hold maximum connection ID number
loop {
let msg = xous::receive_message(sid).unwrap(); // this blocks until we get a message
trace!("Message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::ExampleScalar) => msg_scalar_unpack!(msg, _, _, _, _, { /* what the scalar message does */ }),
Some(Opcode::ExampleBlockingScalar) => msg_blocking_scalar_unpack!(msg, a, b, _, _, {
let value = a + b;
xous::return_scalar(msg.sender, value).expect("couldn't return value to ExampleBlockingScalar");
// note that you can also return two usize values with return_scalar2
}),
Some(Opcode::ExampleMemory) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let rms = buffer.as_flat::<RichMemStruct, _>().unwrap();
// we can now access fields in rms without copying the data
// use to_original if you need to invoke methods on the struct object
}
Some(Opcode::ExampleMemoryWithReturn) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let rms = buffer.to_original::<RichMemStruct, _>().unwrap();
let response = api::Return;
if things_look_okay {
let retstruct = AnotherRichStruct {
name: String::<64>::from_str(rms.as_str()),
other: Some(true),
}
response = api::Return::ExampleMemoryReturn(retstruct);
} else {
response = api::Return::Failure
}
buffer.replace(response).unwrap(); // the buffer that was sent is replaced with AnotherRichStruct
}
// only needed if doing callbacks
Some(Opcode::RegisterCallback) => msg_scalar_unpack!(msg, sid0, sid1, sid2, sid3, {
let sid = xous::SID::from_u32(sid0 as _, sid1 as _, sid2 as _, sid3 as _);
let cid = xous::connect(sid).unwrap();
if (cid as usize) < cb_conns.len() {
cb_conns[cid as usize] = true;
} else {
error!("RegisterCallback CID out of range");
}
}
),
Some(Opcode::UnregisterCallback) => msg_scalar_unpack!(msg, sid0, sid1, sid2, sid3, {
let sid = xous::SID::from_u32(sid0 as _, sid1 as _, sid2 as _, sid3 as _);
let cid = xous::connect(sid).unwrap();
if (cid as usize) < cb_conns.len() {
cb_conns[cid as usize] = false;
} else {
error!("UnregisterCallback CID out of range");
}
unsafe{xous::disconnect(cid).unwrap()};
})
None => log::error!("couldn't convert opcode")
}
// if you have callbacks, you'll probably want to start a separate thread to handle them
// but for simplicity we just call a function here. But in this example, it means the callback
// can only gets processed after any message is received.
do_callback(&mut cb_conns);
}
}
/// only if doing callbacks. This might actually make more sense in a thread of its own, to make it
/// truly asynchronous, but this example is focused on the messaging API, not the threading API.
/// This example admittedly sweeps a rather hairy issue (passing data between process-local threads)
/// under the carpet. As of Xous 0.8 your options to send data around between threads within a process
/// are:
/// 1. Define a crate-local API to pass the messages
/// 2. Use Atomic data types (only applicable if you have primitive data to send)
/// 3. Do some static mut unsafe thing because we don't have a Mutex data type yet.
fn do_callback(cb_conns: &mut [bool; xous::MAX_CID]) {
let a = useful_computation();
for cid in 1..cb_conns {
if cb_conns[cid] {
match xous::send_message(cid,
xous::Message::new_scalar(api::Callback::Hello.to_usize().unwrap(), a, 0, 0, 0)
) {
Err(xous::Error::ServerNotFound) => {
cb_conns[cid] = false // automatically de-allocate callbacks for clients that have dropped
},
Ok(xous::Result::Ok) => {}
_ => panic!("unhandled error or result in callback processing")
}
}
}
}
```

0
RELEASE-v0.9.md Executable file → Normal file
View file

View file

@ -19,8 +19,8 @@ Since there is no external compiler, it can be difficult to know if your code is
Fortunately, Visual Studio Code is free and has excellent C# tooling. All you need to do is point it at your Renode installation, load the C# plugin, and open a `.cs` file.
1. Copy `peripherals.csproj.template` to `peripherals.csproj`
2. Open `peripherals.csproj` and point `<RenodePath>` to your Renode installation directory
3. Install [C# for VSCode](vscode:extension/ms-dotnettools.csharp)
2. Open `peripherals.csproj` and point `<RenodePath>` to your Renode installation directory. On ubuntu, this may be `/opt/renode/bin/`.
3. Install [C# for VSCode](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp)
4. You can refer to [core Renode peripherals](https://github.com/renode/renode-infrastructure/tree/master/src/Emulator/Peripherals/Peripherals) as examples of what C# code looks like.
## Debugging with GDB

View file

@ -455,6 +455,12 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous
this.illegalOpcodeStatus = true;
throw new Exception("Unhandled opcode");
}
//this.Log(LogLevel.Error, "RAM[0x{0:X}] {1}\n Ra:{2:x}\n Rb:{3:x}\n W:{4:x}", this.mpc, op,
// this.engineRam.ReadRegister(op.Ra, op.Ca),
// this.engineRam.ReadRegister(op.Rb, op.Cb),
// this.engineRam.ReadRegister(op.Wd, false)
//);
// Interlocked.Increment(ref this.mpc);
this.mpc += 1;
if (op.Op == 10)

View file

@ -6,7 +6,7 @@ edition = "2018"
description = "com_rs import package"
[dependencies]
com_rs = { git = "https://github.com/betrusted-io/com_rs.git", rev = "8959b373adc359f03a0da7c000bd8208b47d90a7" }
com_rs = { git = "https://github.com/betrusted-io/com_rs.git", rev = "5338f9959572d57f1014d04aa129804da5b4d339" }
#com_rs = { path = "../../../betrusted-ec/sw/com_rs" }

View file

@ -40,7 +40,7 @@ utralib = { path = "utralib" }
[patch.crates-io.sha2]
path = "./sha2"
package = "sha2"
default-features = false
#default-features = false
[patch.crates-io.utralib]
path = "utralib"

View file

@ -1,128 +1,128 @@
KEYROM 0 A SLICE_X36Y50 b'b15b948858499af6'
KEYROM 0 B SLICE_X36Y50 b'7821752fbf541bd6'
KEYROM 0 C SLICE_X36Y50 b'7b5e83d85eca687a'
KEYROM 0 D SLICE_X36Y50 b'9a1699a88f642262'
KEYROM 1 A SLICE_X37Y50 b'bb039cd618157bcb'
KEYROM 1 B SLICE_X37Y50 b'8c46ea66e8e5e9d7'
KEYROM 1 C SLICE_X37Y50 b'0cd419ef497404c4'
KEYROM 1 D SLICE_X37Y50 b'c46ab62cc8c85dde'
KEYROM 2 A SLICE_X36Y51 b'd13a161dfe57d62b'
KEYROM 2 B SLICE_X36Y51 b'9c4c09dad1d7ff84'
KEYROM 2 C SLICE_X36Y51 b'28817088665f4f59'
KEYROM 2 D SLICE_X36Y51 b'721aded79246c10e'
KEYROM 3 A SLICE_X37Y51 b'3f2943ab982e9d86'
KEYROM 3 B SLICE_X37Y51 b'fc75e7bb90a30f64'
KEYROM 3 C SLICE_X37Y51 b'9e82e96a0aa963d2'
KEYROM 3 D SLICE_X37Y51 b'ced5b294d83fea26'
KEYROM 4 A SLICE_X36Y52 b'bade04cae8e713b5'
KEYROM 4 B SLICE_X36Y52 b'c3ccafa1f9a611b0'
KEYROM 4 C SLICE_X36Y52 b'a3823403d17c4782'
KEYROM 4 D SLICE_X36Y52 b'c4f9d11bd15ed764'
KEYROM 5 A SLICE_X37Y52 b'653ee33c41c5ace4'
KEYROM 5 B SLICE_X37Y52 b'868b0eabb87dac3f'
KEYROM 5 C SLICE_X37Y52 b'0ba3585e7d3004f4'
KEYROM 5 D SLICE_X37Y52 b'c5c433b7e222a49c'
KEYROM 6 A SLICE_X36Y53 b'001dbeb890c19249'
KEYROM 6 B SLICE_X36Y53 b'30b8f2df805daff3'
KEYROM 6 C SLICE_X36Y53 b'0641cfb851ec9853'
KEYROM 6 D SLICE_X36Y53 b'05ea4b5d42af6baf'
KEYROM 7 A SLICE_X37Y53 b'08caf1f3d7979abe'
KEYROM 7 B SLICE_X37Y53 b'9895c6d070175303'
KEYROM 7 C SLICE_X37Y53 b'9f79825ea460e6a4'
KEYROM 7 D SLICE_X37Y53 b'a8483aecf52b0475'
KEYROM 8 A SLICE_X36Y54 b'7de1009ad1b6cdca'
KEYROM 8 B SLICE_X36Y54 b'a10f1c2bbd72f667'
KEYROM 8 C SLICE_X36Y54 b'3ac098831fbb7b87'
KEYROM 8 D SLICE_X36Y54 b'4c71ca7f23bc6c82'
KEYROM 9 A SLICE_X37Y54 b'77e31b87a1888d3b'
KEYROM 9 B SLICE_X37Y54 b'38e1bb95230a1686'
KEYROM 9 C SLICE_X37Y54 b'822870083481a830'
KEYROM 9 D SLICE_X37Y54 b'e4a49bd21eb5daaa'
KEYROM 10 A SLICE_X36Y55 b'82db9d7cf1183a43'
KEYROM 10 B SLICE_X36Y55 b'53cb05695ff567e4'
KEYROM 10 C SLICE_X36Y55 b'a8cccfd47947b15a'
KEYROM 10 D SLICE_X36Y55 b'11f306d63e9d4495'
KEYROM 11 A SLICE_X37Y55 b'97cdf98f0b938daa'
KEYROM 11 B SLICE_X37Y55 b'8d1261af20f13f69'
KEYROM 11 C SLICE_X37Y55 b'd8aafd6c2dbea5b6'
KEYROM 11 D SLICE_X37Y55 b'1ae3210567e7d2dc'
KEYROM 12 A SLICE_X36Y56 b'3001c40510acbac5'
KEYROM 12 B SLICE_X36Y56 b'90fb6931ac1f58aa'
KEYROM 12 C SLICE_X36Y56 b'abde32073ed69435'
KEYROM 12 D SLICE_X36Y56 b'45e24850a2cabe38'
KEYROM 13 A SLICE_X37Y56 b'4132ecebf23bb952'
KEYROM 13 B SLICE_X37Y56 b'1c4e9600d860d044'
KEYROM 13 C SLICE_X37Y56 b'a90064999d321a43'
KEYROM 13 D SLICE_X37Y56 b'e71a9a76c55e99bb'
KEYROM 14 A SLICE_X36Y57 b'fe51d54d5a73cb7b'
KEYROM 14 B SLICE_X36Y57 b'28b9f3943c097696'
KEYROM 14 C SLICE_X36Y57 b'700de65df9dda4b8'
KEYROM 14 D SLICE_X36Y57 b'502b935ba5609210'
KEYROM 15 A SLICE_X37Y57 b'c96ce2c5d65e4334'
KEYROM 15 B SLICE_X37Y57 b'55f6ef5fb0dd034e'
KEYROM 15 C SLICE_X37Y57 b'af76d9a7e858a353'
KEYROM 15 D SLICE_X37Y57 b'01dc633bb76cb003'
KEYROM 16 A SLICE_X36Y58 b'67bdad785fbbb949'
KEYROM 16 B SLICE_X36Y58 b'bebef631eb4ea4f0'
KEYROM 16 C SLICE_X36Y58 b'98568d75da1e02fe'
KEYROM 16 D SLICE_X36Y58 b'1dd53e24dfaceb22'
KEYROM 17 A SLICE_X37Y58 b'5ed99284ca738350'
KEYROM 17 B SLICE_X37Y58 b'f3a69fb49f3a5334'
KEYROM 17 C SLICE_X37Y58 b'1b613146929e348f'
KEYROM 17 D SLICE_X37Y58 b'99b3ad406fe98155'
KEYROM 18 A SLICE_X36Y59 b'9de6d11fa6273f4b'
KEYROM 18 B SLICE_X36Y59 b'7d724052b870921d'
KEYROM 18 C SLICE_X36Y59 b'50b85a024e645a26'
KEYROM 18 D SLICE_X36Y59 b'7a6a4bfd4918e678'
KEYROM 19 A SLICE_X37Y59 b'9f3e9c3b7199917a'
KEYROM 19 B SLICE_X37Y59 b'259310ff58de4c72'
KEYROM 19 C SLICE_X37Y59 b'06acb3c84bbf63d6'
KEYROM 19 D SLICE_X37Y59 b'1e2c703f20977102'
KEYROM 20 A SLICE_X36Y60 b'9f883d2e25b3db08'
KEYROM 20 B SLICE_X36Y60 b'70035b7d6684da49'
KEYROM 20 C SLICE_X36Y60 b'78f8f5a7e97f9f35'
KEYROM 20 D SLICE_X36Y60 b'45e15cbcc5726838'
KEYROM 21 A SLICE_X37Y60 b'930b02de01c72f65'
KEYROM 21 B SLICE_X37Y60 b'1cc553eb5f198e87'
KEYROM 21 C SLICE_X37Y60 b'b9cf2883e45c00a4'
KEYROM 21 D SLICE_X37Y60 b'864deda8b37b29e9'
KEYROM 22 A SLICE_X36Y61 b'b347222bf51da1de'
KEYROM 22 B SLICE_X36Y61 b'6b0481128489fc68'
KEYROM 22 C SLICE_X36Y61 b'68ee272b741de7b9'
KEYROM 22 D SLICE_X36Y61 b'4dcd96093a3b5377'
KEYROM 23 A SLICE_X37Y61 b'cc71e20fc71ad4a2'
KEYROM 23 B SLICE_X37Y61 b'd54cca438b1b1197'
KEYROM 23 C SLICE_X37Y61 b'5389826854cdbcfc'
KEYROM 23 D SLICE_X37Y61 b'51ce8a49d1971bb5'
KEYROM 24 A SLICE_X36Y62 b'e62950ee65d30d45'
KEYROM 24 B SLICE_X36Y62 b'1aef2a0df61b18ab'
KEYROM 24 C SLICE_X36Y62 b'98eaf798bdb8c54d'
KEYROM 24 D SLICE_X36Y62 b'dc8b9929a63ea343'
KEYROM 25 A SLICE_X37Y62 b'a0e0d0d7a29cdbf7'
KEYROM 25 B SLICE_X37Y62 b'498a32d2b0a3b94e'
KEYROM 25 C SLICE_X37Y62 b'8811006afd09f8d8'
KEYROM 25 D SLICE_X37Y62 b'cc0120e789508a6c'
KEYROM 26 A SLICE_X36Y63 b'30af60e33bf7cd6a'
KEYROM 26 B SLICE_X36Y63 b'f7b935e1d1c1f381'
KEYROM 26 C SLICE_X36Y63 b'ade197ee470fe075'
KEYROM 26 D SLICE_X36Y63 b'ea42183a25f54bd7'
KEYROM 27 A SLICE_X37Y63 b'f00e6c1201b0ff73'
KEYROM 27 B SLICE_X37Y63 b'94a8a548d618bcb2'
KEYROM 27 C SLICE_X37Y63 b'e819d1f26fbcbb24'
KEYROM 27 D SLICE_X37Y63 b'37049aac3bfb56a9'
KEYROM 28 A SLICE_X36Y64 b'534e447baa64ee79'
KEYROM 28 B SLICE_X36Y64 b'162bea7553ffd73a'
KEYROM 28 C SLICE_X36Y64 b'19556384afa06a05'
KEYROM 28 D SLICE_X36Y64 b'875f9aaaaec6205c'
KEYROM 29 A SLICE_X37Y64 b'4e384b22934cf22d'
KEYROM 29 B SLICE_X37Y64 b'bc3b943960d28f26'
KEYROM 29 C SLICE_X37Y64 b'a3b351addce431ca'
KEYROM 29 D SLICE_X37Y64 b'af3441e6b7c6d2a0'
KEYROM 30 A SLICE_X36Y65 b'1d9780e85878e1fb'
KEYROM 30 B SLICE_X36Y65 b'395965439d6e1c90'
KEYROM 30 C SLICE_X36Y65 b'c6d3dde0e563edca'
KEYROM 30 D SLICE_X36Y65 b'a65dafc978fa9e28'
KEYROM 31 A SLICE_X37Y65 b'dfc6bf07c7ec553d'
KEYROM 31 B SLICE_X37Y65 b'2d5f5bf56a650782'
KEYROM 31 C SLICE_X37Y65 b'89f47f7f8e52e438'
KEYROM 31 D SLICE_X37Y65 b'7fa68ca830a7e48d'
KEYROM 0 A SLICE_X36Y50 b'24dd50c4dccc2320'
KEYROM 0 B SLICE_X36Y50 b'edd8f446c0a4a150'
KEYROM 0 C SLICE_X36Y50 b'dbeba16072d275b2'
KEYROM 0 D SLICE_X36Y50 b'4c6c0e5f1d42ba27'
KEYROM 1 A SLICE_X37Y50 b'a1c92a152a09be28'
KEYROM 1 B SLICE_X37Y50 b'11c7189265eda819'
KEYROM 1 C SLICE_X37Y50 b'3a93e1147ee5bce2'
KEYROM 1 D SLICE_X37Y50 b'c450580f6c7b7467'
KEYROM 2 A SLICE_X36Y51 b'979f453d265bf247'
KEYROM 2 B SLICE_X36Y51 b'f0b4338951e71d2c'
KEYROM 2 C SLICE_X36Y51 b'b633703924e4cbcd'
KEYROM 2 D SLICE_X36Y51 b'13ffe60db41f8322'
KEYROM 3 A SLICE_X37Y51 b'6e0af8f91c0124a3'
KEYROM 3 B SLICE_X37Y51 b'48d60b6ef3d12e23'
KEYROM 3 C SLICE_X37Y51 b'f3e8bc13df6f6126'
KEYROM 3 D SLICE_X37Y51 b'4d331af1a29ead1c'
KEYROM 4 A SLICE_X36Y52 b'25b683e7db6311b0'
KEYROM 4 B SLICE_X36Y52 b'e5d6850bc51bec75'
KEYROM 4 C SLICE_X36Y52 b'8fc63d5f298ceefe'
KEYROM 4 D SLICE_X36Y52 b'0bf600a0863c8095'
KEYROM 5 A SLICE_X37Y52 b'7415957ed7c59ca4'
KEYROM 5 B SLICE_X37Y52 b'57d97b2b62596410'
KEYROM 5 C SLICE_X37Y52 b'f7e22eb00acd93b1'
KEYROM 5 D SLICE_X37Y52 b'03956ecd96614f60'
KEYROM 6 A SLICE_X36Y53 b'7962f945cbf480b9'
KEYROM 6 B SLICE_X36Y53 b'0cd3050f62d45b44'
KEYROM 6 C SLICE_X36Y53 b'a9670bbd0cf5c189'
KEYROM 6 D SLICE_X36Y53 b'a9061155f673a3ad'
KEYROM 7 A SLICE_X37Y53 b'5d2cc7c30ee7d601'
KEYROM 7 B SLICE_X37Y53 b'e01c88067b545391'
KEYROM 7 C SLICE_X37Y53 b'587f164581583601'
KEYROM 7 D SLICE_X37Y53 b'4d7dc6edaa027015'
KEYROM 8 A SLICE_X36Y54 b'9d934ddc59cfc63a'
KEYROM 8 B SLICE_X36Y54 b'e0b7e03092b0f8ba'
KEYROM 8 C SLICE_X36Y54 b'e0b9849fa9d2d854'
KEYROM 8 D SLICE_X36Y54 b'4c814629e324749e'
KEYROM 9 A SLICE_X37Y54 b'c102b099b84e99e8'
KEYROM 9 B SLICE_X37Y54 b'9bb0fb0d20723548'
KEYROM 9 C SLICE_X37Y54 b'c0b754e678502ed3'
KEYROM 9 D SLICE_X37Y54 b'8d0d019ea8630d34'
KEYROM 10 A SLICE_X36Y55 b'9c478f624459e155'
KEYROM 10 B SLICE_X36Y55 b'05700b24a2a4b35e'
KEYROM 10 C SLICE_X36Y55 b'7f3817bac560a417'
KEYROM 10 D SLICE_X36Y55 b'9844a4ce6f9f041f'
KEYROM 11 A SLICE_X37Y55 b'aa7d489e28736098'
KEYROM 11 B SLICE_X37Y55 b'20e76ec2ae348a7f'
KEYROM 11 C SLICE_X37Y55 b'58ed38b580d81236'
KEYROM 11 D SLICE_X37Y55 b'f902e8d5c27646ec'
KEYROM 12 A SLICE_X36Y56 b'791b7cb748db31df'
KEYROM 12 B SLICE_X36Y56 b'c958a1bb2b7f78f9'
KEYROM 12 C SLICE_X36Y56 b'7e1e1f190e1708b8'
KEYROM 12 D SLICE_X36Y56 b'7d1bc8cfb7441aa6'
KEYROM 13 A SLICE_X37Y56 b'1d6ffba9e34b4de0'
KEYROM 13 B SLICE_X37Y56 b'bf4f64f2b194de78'
KEYROM 13 C SLICE_X37Y56 b'ea1b9455172a3e86'
KEYROM 13 D SLICE_X37Y56 b'15cbb12dda700bcb'
KEYROM 14 A SLICE_X36Y57 b'2c11135e92c6f059'
KEYROM 14 B SLICE_X36Y57 b'16a79a997aa31967'
KEYROM 14 C SLICE_X36Y57 b'50fbec51aa3e2e58'
KEYROM 14 D SLICE_X36Y57 b'b0cd5a126c0f2aab'
KEYROM 15 A SLICE_X37Y57 b'265ae79a566a2f36'
KEYROM 15 B SLICE_X37Y57 b'b8ed56c63d85fa8b'
KEYROM 15 C SLICE_X37Y57 b'fc904e4087d0919c'
KEYROM 15 D SLICE_X37Y57 b'f81e506ea44ea2ce'
KEYROM 16 A SLICE_X36Y58 b'89aa1c12757d02ec'
KEYROM 16 B SLICE_X36Y58 b'c7b96e935d002c93'
KEYROM 16 C SLICE_X36Y58 b'dad9dbe9f05cc87c'
KEYROM 16 D SLICE_X36Y58 b'066a4f976dc22dc7'
KEYROM 17 A SLICE_X37Y58 b'51ebd71c28f80646'
KEYROM 17 B SLICE_X37Y58 b'93856584a09a16b4'
KEYROM 17 C SLICE_X37Y58 b'cb72e4a8fd7edf9c'
KEYROM 17 D SLICE_X37Y58 b'3ee2b12c77ff2787'
KEYROM 18 A SLICE_X36Y59 b'9a0325954000c4be'
KEYROM 18 B SLICE_X36Y59 b'af92a2715d7a82b4'
KEYROM 18 C SLICE_X36Y59 b'ad94f800cb63dcef'
KEYROM 18 D SLICE_X36Y59 b'9695abe3db06ca54'
KEYROM 19 A SLICE_X37Y59 b'873d39d4f1fd1f3f'
KEYROM 19 B SLICE_X37Y59 b'62fad5775a422213'
KEYROM 19 C SLICE_X37Y59 b'd0931418abceafea'
KEYROM 19 D SLICE_X37Y59 b'223cce375c3bb55a'
KEYROM 20 A SLICE_X36Y60 b'f79a85a87df6d82a'
KEYROM 20 B SLICE_X36Y60 b'8e9a587d20f61014'
KEYROM 20 C SLICE_X36Y60 b'e2328f9b813f713a'
KEYROM 20 D SLICE_X36Y60 b'cc94fb8a5d5b6b49'
KEYROM 21 A SLICE_X37Y60 b'566c8c521c3ee06c'
KEYROM 21 B SLICE_X37Y60 b'17c6dd694108c7c1'
KEYROM 21 C SLICE_X37Y60 b'0630f5506bda2479'
KEYROM 21 D SLICE_X37Y60 b'b6bc45e2d73e43e0'
KEYROM 22 A SLICE_X36Y61 b'5010a16bdf813405'
KEYROM 22 B SLICE_X36Y61 b'a4be46102ddb6f36'
KEYROM 22 C SLICE_X36Y61 b'993a0be495b1c7b6'
KEYROM 22 D SLICE_X36Y61 b'3387610754e84a61'
KEYROM 23 A SLICE_X37Y61 b'5abb1a68ddbc058f'
KEYROM 23 B SLICE_X37Y61 b'aebadc57794b0212'
KEYROM 23 C SLICE_X37Y61 b'fb4d713662a4429d'
KEYROM 23 D SLICE_X37Y61 b'3fb84713795b9d2a'
KEYROM 24 A SLICE_X36Y62 b'52dca715e57d1b0d'
KEYROM 24 B SLICE_X36Y62 b'c2d891a6f9f9e2ec'
KEYROM 24 C SLICE_X36Y62 b'735c0b2db109f675'
KEYROM 24 D SLICE_X36Y62 b'4a1d0adac53ca1bd'
KEYROM 25 A SLICE_X37Y62 b'cf4bdf80b8bffcda'
KEYROM 25 B SLICE_X37Y62 b'f69f46df7fb630ed'
KEYROM 25 C SLICE_X37Y62 b'f096b08dd29f6a7f'
KEYROM 25 D SLICE_X37Y62 b'57a7adcdfb6a30e9'
KEYROM 26 A SLICE_X36Y63 b'f02e2d403d031b37'
KEYROM 26 B SLICE_X36Y63 b'af1748b620c9c47d'
KEYROM 26 C SLICE_X36Y63 b'696b536b54e9ee0b'
KEYROM 26 D SLICE_X36Y63 b'16f1091d758702c1'
KEYROM 27 A SLICE_X37Y63 b'50474f86e8892c58'
KEYROM 27 B SLICE_X37Y63 b'79443ea805fdd99a'
KEYROM 27 C SLICE_X37Y63 b'e82925d380e88902'
KEYROM 27 D SLICE_X37Y63 b'bb1b2f408a542736'
KEYROM 28 A SLICE_X36Y64 b'0694d94a8e64abf3'
KEYROM 28 B SLICE_X36Y64 b'23c04f31ab2066ef'
KEYROM 28 C SLICE_X36Y64 b'771285b34a78bb05'
KEYROM 28 D SLICE_X36Y64 b'28e81406ea40fa29'
KEYROM 29 A SLICE_X37Y64 b'b4f821110f25508e'
KEYROM 29 B SLICE_X37Y64 b'e8edfd8a5619ddf2'
KEYROM 29 C SLICE_X37Y64 b'7baa099dc89780da'
KEYROM 29 D SLICE_X37Y64 b'91935ab29fcd30e9'
KEYROM 30 A SLICE_X36Y65 b'45dfe240d9944f47'
KEYROM 30 B SLICE_X36Y65 b'dd0fa208d2c7f12d'
KEYROM 30 C SLICE_X36Y65 b'55ff784d182db2f1'
KEYROM 30 D SLICE_X36Y65 b'c6e7ec98a0bb1085'
KEYROM 31 A SLICE_X37Y65 b'4dd71145c64011b4'
KEYROM 31 B SLICE_X37Y65 b'224052cda91dadd7'
KEYROM 31 C SLICE_X37Y65 b'52c9c87fbf67c815'
KEYROM 31 D SLICE_X37Y65 b'd0cf7cb22dc8f1bf'

View file

@ -3,7 +3,7 @@
<device schemaVersion="1.1" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xs:noNamespaceSchemaLocation="CMSIS-SVD.xsd" >
<vendor>litex</vendor>
<name>SOC</name>
<description><![CDATA[Litex SoC 2021-08-30 00:36:49]]></description>
<description><![CDATA[Litex SoC 2021-09-07 03:25:12]]></description>
<addressUnitBits>8</addressUnitBits>
<width>32</width>
@ -3584,7 +3584,7 @@ inject too fast.]]></description>
<name>SEED1</name>
<description><![CDATA[Bits 32-63 of `SEED_SEED`. Seed used for the build]]></description>
<addressOffset>0x0000</addressOffset>
<resetValue>0x5e716c92</resetValue>
<resetValue>0x2950f5ce</resetValue>
<size>32</size>
<fields>
<field>
@ -3599,7 +3599,7 @@ inject too fast.]]></description>
<name>SEED0</name>
<description><![CDATA[Bits 0-31 of `SEED_SEED`.]]></description>
<addressOffset>0x0004</addressOffset>
<resetValue>0x7355f69a</resetValue>
<resetValue>0x59b4e46b</resetValue>
<size>32</size>
<fields>
<field>

Binary file not shown.

View file

@ -36,10 +36,27 @@ pub(crate) enum Opcode {
/// send a frame ready notification
AnotherFrame,
/// set speaker volume
SetSpeakerVolume,
/// set headphone volume -- L&R channels are ganged together in this API, but codec can do separately
SetHeadphoneVolume,
/// Suspend/resume callback
SuspendResume,
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub enum VolumeOps {
UpOne,
DownOne,
Set,
Mute,
RestoreDefault,
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum EventCallback {
Event,

View file

@ -78,4 +78,11 @@ impl Codec {
pub fn audio_i2s_stop(&mut self) {
}
pub fn set_speaker_gain_db(&mut self, _gain_db: f32) {
}
pub fn set_headphone_gain_db(&mut self, _gain_db: f32) {
}
}

View file

@ -30,6 +30,23 @@ pub struct Codec {
static SILENCE: [u32; FIFO_DEPTH] = [ZERO_PCM as u32 | (ZERO_PCM as u32) << 16; FIFO_DEPTH];
/// gain is specified in dB, and has a useful range from 0 to -80dB
fn analog_volume_db_to_code(g: f32) -> u8 {
if g >= 0.0 {
0
} else if g >= -17.5 {
(-g * 2.0) as u8
} else if g >= -34.6 {
(-g * 2.0 - 0.4) as u8
} else if g >= -49.3 {
(100.0 - (50.0 + g) * 0.7202) as u8
} else if g >= -72.2 {
127
} else {
127
}
}
fn audio_handler(_irq_no: usize, arg: *mut usize) {
let codec = unsafe { &mut *(arg as *mut Codec) };
let volatile_audio = codec.fifo.as_mut_ptr() as *mut u32;
@ -204,6 +221,37 @@ impl Codec {
self.live
}
pub fn set_speaker_gain_db(&mut self, gain_db: f32) {
if gain_db <= -79.0 {
// mute
self.w(0, &[1]); // select page 1
self.w(32, &[0b0_0_00011_0]); // class D amp powered off
} else {
let code = analog_volume_db_to_code(gain_db);
self.w(0, &[1]); // select page 1
self.w(32, &[0b1_0_00011_0]); // class D amp powered on
self.w(38, &[
0b1_000_0000 | code,
]);
}
}
pub fn set_headphone_gain_db(&mut self, gain_db: f32) {
if gain_db <= -79.0 {
// mute
self.w(0, &[1]); // select page 1
self.w(31, &[0b0_0_0_10_1_0_0]); // headphones powered down
} else {
let code = analog_volume_db_to_code(gain_db);
self.w(0, &[1]); // select page 1
self.w(31, &[0b1_1_00011_0]); // headphones powered up
self.w(36, &[
0b1_000_0000 | code, // HPL
0b1_000_0000 | code, // HPR
]);
}
}
fn w(&mut self, adr: u8, data: &[u8]) -> bool {
//log::trace!("writing to 0x{:x}, {:x?}", adr, data);
match self.llio.i2c_write(TLV320AIC3100_I2C_ADR, adr, data, None) {

View file

@ -80,6 +80,48 @@ impl Codec {
Message::new_scalar(Opcode::PauseStream.to_usize().unwrap(), 0, 0, 0, 0)
).map(|_| ())
}
/// gain goes from 0dB down to -80dB
pub fn set_speaker_volume(&self, op: VolumeOps, gain: Option<f32>) -> Result<(), xous::Error> {
let code = if let Some(g) = gain {
if g > 0.0 {
0 as usize
} else {
(-g * 10.0) as usize
}
} else {
800 // -80.0 dB => mute
};
send_message(self.conn,
Message::new_scalar(Opcode::SetSpeakerVolume.to_usize().unwrap(),
op.to_usize().unwrap(),
code, // gain as -dB * 10 as usize
0,
0
)
).map(|_| ())
}
/// gain goes from 0dB down to -80dB
pub fn set_headphone_volume(&self, op: VolumeOps, gain: Option<f32>) -> Result<(), xous::Error> {
let code = if let Some(g) = gain {
if g > 0.0 {
0 as usize
} else {
(-g * 10.0) as usize
}
} else {
800 // -80.0 dB => mute
};
send_message(self.conn,
Message::new_scalar(Opcode::SetHeadphoneVolume.to_usize().unwrap(),
op.to_usize().unwrap(),
code, // gain as -dB * 10 as usize
0,
0
)
).map(|_| ())
}
}
use core::sync::atomic::{AtomicU32, Ordering};

View file

@ -48,6 +48,8 @@ fn xmain() -> ! {
}
*/
let mut speaker_analog_gain_db: f32 = -6.0;
let mut headphone_analog_gain_db: f32 = -15.0;
let mut audio_cb_conns: [Option<ScalarCallback>; 32] = [None; 32];
loop {
let mut msg = xous::receive_message(codec_sid).unwrap();
@ -152,6 +154,60 @@ fn xmain() -> ! {
//log::trace!("A rd {} wr {}", rdcount, wrcount);
send_event(&audio_cb_conns, codec.free_play_frames(), codec.available_rec_frames());
}),
Some(api::Opcode::SetSpeakerVolume) => xous::msg_scalar_unpack!(msg, op, gain_code, _, _, {
match FromPrimitive::from_usize(op) {
Some(VolumeOps::Set) => {
speaker_analog_gain_db = -(gain_code as f32) / 10.0;
},
Some(VolumeOps::Mute) => {
speaker_analog_gain_db = -80.0;
},
Some(VolumeOps::RestoreDefault) => {
speaker_analog_gain_db = -6.0;
},
Some(VolumeOps::UpOne) => {
speaker_analog_gain_db += 3.0;
if speaker_analog_gain_db >= 0.0 {
speaker_analog_gain_db = 0.0;
}
},
Some(VolumeOps::DownOne) => {
speaker_analog_gain_db -= 3.0;
if speaker_analog_gain_db <= -80.0 {
speaker_analog_gain_db = -80.0;
}
},
_ => log::error!("got speaker volume primitive that we don't recognize, ignoring!"),
};
codec.set_speaker_gain_db(speaker_analog_gain_db);
}),
Some(api::Opcode::SetHeadphoneVolume) => xous::msg_scalar_unpack!(msg, op, gain_code, _, _, {
match FromPrimitive::from_usize(op) {
Some(VolumeOps::Set) => {
headphone_analog_gain_db = -(gain_code as f32) / 10.0;
},
Some(VolumeOps::Mute) => {
headphone_analog_gain_db = -80.0;
},
Some(VolumeOps::RestoreDefault) => {
headphone_analog_gain_db = -6.0;
},
Some(VolumeOps::UpOne) => {
headphone_analog_gain_db += 3.0;
if headphone_analog_gain_db >= 0.0 {
headphone_analog_gain_db = 0.0;
}
},
Some(VolumeOps::DownOne) => {
headphone_analog_gain_db -= 3.0;
if headphone_analog_gain_db <= -80.0 {
headphone_analog_gain_db = -80.0;
}
},
_ => log::error!("got speaker volume primitive that we don't recognize, ignoring!"),
};
codec.set_headphone_gain_db(headphone_analog_gain_db);
}),
None => {
log::error!("couldn't convert opcode");
break

View file

@ -15,6 +15,7 @@ typenum = "1.12"
xous = {path = "../../xous-rs"}
xous-ipc = {path = "../../xous-ipc"}
xous-names = {path = "../xous-names"}
trng = {path = "../trng"}
num-derive = {version = "0.3", default-features = false}
num-traits = {version = "0.2", default-features = false}

View file

@ -61,6 +61,12 @@ pub struct FlashRecord {
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum Opcode {
/// Refresh the TRNG seed for the EC
ReseedTrng,
/// Fetch the uptime of the EC
GetUptime,
/// Battery stats
BattStats,
@ -73,6 +79,12 @@ pub(crate) enum Opcode {
/// Query Full charge capacity of the battery
//BattFullCapacity,
/// More charger and gas gauge status, primarily for diagnostics
MoreStats,
/// Poll the USB CC chip
PollUsbCc,
/// Turn Boost Mode On
BoostOn,

View file

@ -78,6 +78,22 @@ impl Com {
}
}
pub fn reseed_ec_trng(&self) -> Result<(), xous::Error> {
send_message(self.conn,
Message::new_scalar(Opcode::ReseedTrng.to_usize().unwrap(), 0, 0, 0, 0)
).map(|_| ())
}
pub fn get_ec_uptime(&self) -> Result<u64, xous::Error> {
let response = send_message(self.conn,
Message::new_blocking_scalar(Opcode::GetUptime.to_usize().unwrap(), 0, 0, 0, 0)
)?;
if let xous::Result::Scalar2(lsb, msb) = response {
Ok( lsb as u64 | (msb as u64) << 32)
} else {
Err(xous::Error::InternalError)
}
}
pub fn get_wf200_fw_rev(&self) -> Result<(u8, u8, u8), xous::Error> {
let response = send_message(self.conn,
Message::new_blocking_scalar(Opcode::Wf200Rev.to_usize().unwrap(), 0, 0, 0, 0))?;
@ -140,6 +156,47 @@ impl Com {
Ok(())
}
pub fn get_batt_stats_blocking(&mut self) -> Result<BattStats, xous::Error> {
let response = send_message(self.conn,
Message::new_blocking_scalar(Opcode::BattStats.to_usize().unwrap(), 0, 0, 0, 0))?;
if let xous::Result::Scalar2(rs0, rs1) = response {
let bs: BattStats = [rs0, rs1].into();
Ok(bs)
} else {
Err(xous::Error::InternalError)
}
}
pub fn get_more_stats(&mut self) -> Result<[u16; 15], xous::Error> {
let alloc_stats: [u16; 15] = [0; 15];
let mut buf = Buffer::into_buf(alloc_stats).or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.conn, Opcode::MoreStats.to_u32().unwrap())?;
let stats: [u16; 15] = buf.to_original::<[u16; 15], _>().unwrap();
Ok(stats)
}
pub fn poll_usb_cc(&mut self) -> Result<(bool, [u16; 3], u8), xous::Error> {
let response = send_message(self.conn,
Message::new_blocking_scalar(Opcode::PollUsbCc.to_usize().unwrap(), 0, 0, 0, 0))?;
if let xous::Result::Scalar2(val1, val2) = response {
let event = if ((val1 >> 16) & 0xff) == 0 {
false
} else {
true
};
let regs: [u16; 3] = [
(val1 & 0xFFFF) as u16,
(val2 & 0xFFFF) as u16,
((val2 >> 16) & 0xFF) as u16
];
let rev: u8 = ((val1 >> 24) & 0xff) as u8;
Ok((event, regs, rev))
} else {
Err(xous::Error::InternalError)
}
}
pub fn wifi_disable(&self) -> Result<(), xous::Error> {
send_message(self.conn, Message::new_scalar(Opcode::Wf200Disable.to_usize().unwrap(), 0, 0, 0, 0,)).map(|_| ())
}

View file

@ -189,6 +189,34 @@ mod implementation {
stats
}
pub fn get_more_stats(&mut self) -> [u16; 15] {
self.txrx(ComState::STAT.verb);
let ack = self.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT));
if ack != 0x8888 {
log::error!("didn't receive the expected ack header to the stats readout");
}
let mut ret: [u16; 15] = [0; 15];
for r in ret.iter_mut() {
*r = self.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT));
}
ret
}
pub fn poll_usb_cc(&mut self) -> [u32; 2] {
self.txrx(ComState::POLL_USB_CC.verb);
let event = self.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT));
let mut ret: [u16; 3] = [0; 3];
for r in ret.iter_mut() {
*r = self.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT));
}
let rev = self.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT));
// pack into a format that can be returned as a scalar2
[
((rev & 0xff) as u32) << 24 | (((event & 0xff) as u32) << 16) | ret[0] as u32,
ret[1] as u32 | ((ret[2] as u32) << 16)
]
}
}
}
@ -262,6 +290,13 @@ mod implementation {
None
}
}
pub fn get_more_stats(&mut self) -> [u16; 15] {
[0; 15]
}
pub fn poll_usb_cc(&mut self) -> [u32; 2] {
[0; 2]
}
}
}
@ -296,6 +331,17 @@ fn xmain() -> ! {
const FLASH_LEN: u32 = 0x10_0000;
const FLASH_TIMEOUT: u32 = 250;
// initial seed of the COM trng
let trng = trng::Trng::new(&xns).expect("couldn't connect to TRNG");
com.txrx(ComState::TRNG_SEED.verb);
for _ in 0..2 {
let mut rng = trng.get_u64().expect("couldn't fetch rngs");
for _ in 0..4 {
com.txrx(rng as u16);
rng >>= 16;
}
}
trace!("starting main loop");
loop {
let mut msg = xous::receive_message(com_sid).unwrap();
@ -312,6 +358,25 @@ fn xmain() -> ! {
com.txrx(ComState::BL_START.verb | (bl_main as u16) & 0x1f | (((bl_sec as u16) & 0x1f) << 5));
}
}),
Some(Opcode::ReseedTrng) => xous::msg_scalar_unpack!(msg, _, _, _, _, {
com.txrx(ComState::TRNG_SEED.verb);
for _ in 0..2 {
let mut rng = trng.get_u64().expect("couldn't fetch rngs");
for _ in 0..4 {
com.txrx(rng as u16);
rng >>= 16;
}
}
}),
Some(Opcode::GetUptime) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let mut uptime: u64 = 0;
com.txrx(ComState::UPTIME.verb);
for _ in 0..4 {
uptime >>= 16;
uptime |= (com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)) as u64) << 48;
}
xous::return_scalar2(msg.sender, uptime as usize, (uptime >> 32) as usize).expect("couldn't return uptime");
}),
Some(Opcode::FlashAcquire) => msg_blocking_scalar_unpack!(msg, id0, id1, id2, id3, {
let acquired = if flash_id.is_none() {
flash_id = Some([id0 as u32, id1 as u32, id2 as u32, id3 as u32]);
@ -467,13 +532,21 @@ fn xmain() -> ! {
).expect("coludn't return accelerometer read data");
}),
Some(Opcode::BattStats) => {
info!("batt stats request received");
let stats = com.get_battstats();
let raw_stats: [usize; 2] = stats.into();
xous::return_scalar2(msg.sender, raw_stats[1], raw_stats[0])
xous::return_scalar2(msg.sender, raw_stats[0], raw_stats[1])
.expect("couldn't return batt stats request");
info!("done returning batt stats request");
}
Some(Opcode::MoreStats) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let stats = com.get_more_stats();
buffer.replace(stats).unwrap();
}
Some(Opcode::PollUsbCc) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let usb_cc: [u32; 2] = com.poll_usb_cc();
xous::return_scalar2(msg.sender, usb_cc[0] as usize, usb_cc[1] as usize)
.expect("couldn't return Usb CC result");
}),
Some(Opcode::BattStatsNb) => {
for &maybe_conn in battstats_conns.iter() {
if let Some(conn) = maybe_conn {

View file

@ -35,6 +35,5 @@ utralib = {path = "../../utralib"}
[features]
debugprint = []
slowstatus = [] # used for braille mode, so console isn't overwhelmed with status
# default = ["debugprint"] # "debugprint"
default = []

View file

@ -28,4 +28,5 @@ minifb = {version = "0.19.2", git = "https://github.com/xobs/rust_minifb.git", r
[features]
debugprint = []
braille = []
default = [] # "debugprint"

View file

@ -480,7 +480,9 @@ fn xmain() -> ! {
tv.text.as_str().unwrap().len()
);
}
log::debug!("{}", tv);
if cfg!(feature = "braille") {
log::info!("{}", tv);
}
let do_xor = tv.invert;
blitstr::paint_str(
display.native_buffer(),

View file

@ -25,4 +25,5 @@ utralib = {path = "../../utralib"}
[features]
debugprint = []
debuginject = [] # used only if you want key injection via the UART
braille = []
default = ["debuginject"] # "debugprint"

View file

@ -293,13 +293,19 @@ mod implementation {
let ticktimer = ticktimer_server::Ticktimer::new().expect("couldn't connect to ticktimer");
let timestamp = ticktimer.elapsed_ms();
let default_map = if cfg!(feature = "braille") {
KeyMap::Braille
} else {
KeyMap::Qwerty
};
let mut kbd = Keyboard {
conn: xous::connect(sid).unwrap(),
csr: CSR::new(csr.as_mut_ptr() as *mut u32),
new_state: HashSet::with_capacity(16), // pre-allocate space since this has to work in an interrupt context
last_state: HashSet::with_capacity(16),
ticktimer,
map: KeyMap::Qwerty,
map: default_map,
delay: 500,
rate: 20,
shift_down: false,

View file

@ -39,6 +39,9 @@ num-derive = {version = "0.3", default-features = false}
num-traits = {version = "0.2", default-features = false}
rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]}
# for audio self-test analysis
spectrum-analyzer = "0.5.2"
# for the curve25519 tests
# hardware acceleration adaptations are inserted into a fork of the main branch.
rand_core = "0.5"

View file

@ -160,7 +160,7 @@ impl CmdEnv {
common_env: common,
lastverb: String::<256>::new(),
///// 3. initialize your storage, by calling new()
test_cmd: Test::new(),
test_cmd: Test::new(&xns),
sleep_cmd: Sleep::new(&xns),
sensors_cmd: Sensors::new(),
callback_cmd: CallBack::new(),

View file

@ -205,12 +205,77 @@ pub fn benchmark_thread(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
xous::destroy_server(sid).unwrap();
}
mod wycheproof {
pub const WYCHEPROOF_NO_TEST_CASES: usize = 518;
pub const WHYCHEPROOF_TEST_CASE_SIZE: usize = 96;
#[export_name = "wycheproof_vectors"]
pub static WYCHEPROOF_VECTORS: &[u8; WYCHEPROOF_NO_TEST_CASES * WHYCHEPROOF_TEST_CASE_SIZE] =
include_bytes!("x25519_test.bin");
pub struct WycheproofTestCase {
// inferred from the index; not read from the binary data
public: [u8; 32],
id: usize,
private: [u8; 32],
shared: [u8; 32],
}
impl WycheproofTestCase {
pub fn read(test_index: usize) -> Self {
use std::io::Read;
let test_offset = test_index * WHYCHEPROOF_TEST_CASE_SIZE;
let mut public = [0u8; 32];
(&WYCHEPROOF_VECTORS[test_offset..test_offset + 32])
.read_exact(&mut public)
.unwrap();
let mut private = [0u8; 32];
(&WYCHEPROOF_VECTORS[test_offset + 32..test_offset + 64])
.read_exact(&mut private)
.unwrap();
let mut shared = [0u8; 32];
(&WYCHEPROOF_VECTORS[test_offset + 64..test_offset + 96])
.read_exact(&mut shared)
.unwrap();
WycheproofTestCase {
id: test_index + 1,
public,
private,
shared,
}
}
pub fn run(&self) -> Option<TestCaseError> {
use x25519_dalek::{PublicKey, StaticSecret};
let private = StaticSecret::from(self.private);
let public = PublicKey::from(self.public);
let shared = private.diffie_hellman(&public).to_bytes();
if shared != self.shared {
Some(TestCaseError {
test_id: self.id,
expected: self.shared,
actual: shared,
})
} else {
None
}
}
}
pub struct TestCaseError {
pub(crate) test_id: usize,
pub(crate) expected: [u8; 32],
pub(crate) actual: [u8; 32],
}
}
#[derive(Debug)]
pub struct Engine {
susres: susres::Susres,
benchmark_cid: xous::CID,
start_time: Option<u64>,
}
impl Engine {
pub fn new(xns: &xous_names::XousNames, env: &mut CommonEnv) -> Self {
let sid = xous::create_server().unwrap();
@ -234,7 +299,7 @@ impl<'a> ShellCmdApi<'a> for Engine {
fn process(&mut self, args: String::<1024>, env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error> {
use core::fmt::Write;
let mut ret = String::<1024>::new();
let helpstring = "engine [check] [bench] [benchdh] [susres] [dh] [ed]";
let helpstring = "engine [check] [bench] [benchdh] [susres] [dh] [ed] [wycheproof]";
let mut tokens = args.as_str().unwrap().split(' ');
@ -449,6 +514,22 @@ impl<'a> ShellCmdApi<'a> for Engine {
write!(ret, "Passed ed25519 simple check").unwrap();
}
}
"wycheproof" => {
use wycheproof::*;
use hex::ToHex;
let failures: Vec<TestCaseError> = (0..WYCHEPROOF_NO_TEST_CASES)
.filter_map(|test_index| WycheproofTestCase::read(test_index).run())
.collect();
write!(ret, "Ran {} tests. {} failures.", WYCHEPROOF_NO_TEST_CASES, failures.len()).unwrap();
if failures.len() > 0 {
write!(ret, "\nFailed tests: {:?}", failures.iter().map(|tc| tc.test_id).collect::<Vec<usize>>()).unwrap();
for failure in failures {
log::error!("wycheproof test #{} failed:", failure.test_id);
log::error!("expected: {}", failure.expected.encode_hex::<std::string::String>());
log::error!("actual: {}", failure.actual.encode_hex::<std::string::String>());
}
}
}
_ => {
write!(ret, "{}", helpstring).unwrap();
}

View file

@ -1,32 +1,373 @@
use crate::{ShellCmdApi,CommonEnv};
use xous_ipc::String;
use xous::{MessageEnvelope, Message};
use llio::I2cStatus;
use codec::*;
use spectrum_analyzer::{FrequencyLimit, FrequencySpectrum, samples_fft_to_spectrum};
use spectrum_analyzer::windows::hann_window;
use rtc::{DateTime, Weekday};
#[derive(Debug)]
pub struct Test {
state: u32
state: u32,
// audio
codec: codec::Codec,
recbuf: xous::MemoryRange,
callback_id: Option<u32>,
callback_conn: u32,
framecount: u32,
play_sample: f32, // count of play samples generated. in f32 to avoid int<->f32 conversions
rec_sample: usize, // count of record samples recorded. in usize because we're not doing f32 wave table computations on this
left_play: bool,
right_play: bool,
speaker_play: bool,
freq: f32,
// rtc
start_time: Option<DateTime>,
end_time: Option<DateTime>,
start_elapsed: Option<u64>,
end_elapsed: Option<u64>,
}
impl Test {
pub fn new() -> Self {
pub fn new(xns: &xous_names::XousNames) -> Self {
let codec = codec::Codec::new(xns).unwrap();
let recbuf = xous::syscall::map_memory(
None,
None,
0x8000,
xous::MemoryFlags::R | xous::MemoryFlags::W,
).expect("couldn't allocate record buffer");
let callback_conn = xns.request_connection_blocking(crate::SERVER_NAME_SHELLCHAT).unwrap();
Test {
state: 0
codec,
recbuf,
state: 0,
callback_id: None,
callback_conn,
framecount: 0,
play_sample: 0.0,
rec_sample: 0,
left_play: true,
right_play: true,
speaker_play: true,
freq: 440.0,
start_time: None,
end_time: None,
start_elapsed: None,
end_elapsed: None,
}
}
}
const SAMPLE_RATE_HZ: f32 = 8000.0;
// note to self: A4 = 440.0, E4 = 329.63, C4 = 261.63
impl<'a> ShellCmdApi<'a> for Test {
cmd_api!(test);
fn process(&mut self, args: String::<1024>, env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error> {
use core::fmt::Write;
const SENTINEL: &'static str = "|TSTR";
self.state += 1;
let mut ret = String::<1024>::new();
write!(ret, "Test has run {} times.\n", self.state).unwrap();
write!(ret, "Test has run {} times.", self.state).unwrap();
let mut tokens = args.as_str().unwrap().split(' ');
if let Some(sub_cmd) = tokens.next() {
match sub_cmd {
"factory" => {
// force a specified time to make sure the elapsed time computation later on works
if !rtc_set(&mut env.llio, 0, 0, 10, 1, 6, 21) {
log::info!("{}|RTC|FAIL|SET|", SENTINEL);
}
self.start_elapsed = Some(env.ticktimer.elapsed_ms());
self.start_time = rtc_get(&mut env.llio);
// set uart MUX, and turn off WFI so UART reports are "clean" (no stuck characters when CPU is in WFI)
env.llio.set_uart_mux(llio::UartType::Log).unwrap();
env.llio.wfi_override(true).unwrap();
let vccint = env.llio.adc_vccint().unwrap() as f32 / 1365.0;
if vccint < 0.92 || vccint > 0.98 {
log::info!("{}|VCCINT|FAIL|{}", SENTINEL, vccint);
} else {
log::info!("{}|VCCINT|PASS|{}", SENTINEL, vccint);
}
let vccaux = env.llio.adc_vccaux().unwrap() as f32 / 1365.0;
if vccaux < 1.71 || vccaux > 1.89 {
log::info!("{}|VCCAUX|FAIL|{}", SENTINEL, vccaux);
} else {
log::info!("{}|VCCAUX|PASS|{}", SENTINEL, vccaux);
}
let vccbram = env.llio.adc_vccbram().unwrap() as f32 / 1365.0;
if vccbram < 0.92 || vccbram > 0.98 {
log::info!("{}|VCCBRAM|FAIL|{}", SENTINEL, vccbram);
} else {
log::info!("{}|VCCBRAM|PASS|{}", SENTINEL, vccbram);
}
let (x, y, z, id) = env.com.gyro_read_blocking().unwrap();
log::info!("{}|GYRO|{}|{}|{}|{}|", SENTINEL, x, y, z, id);
let (wf_maj, wf_min, wf_rev) = env.com.get_wf200_fw_rev().unwrap();
log::info!("{}|WF200REV|{}|{}|{}|", SENTINEL, wf_maj, wf_min, wf_rev);
let (ec_rev, ec_dirty) = env.com.get_ec_git_rev().unwrap();
log::info!("{}|ECREV|{:x}|{:?}|", SENTINEL, ec_rev, ec_dirty);
let morestats = env.com.get_more_stats().unwrap();
log::info!("{}|BATTSTATS|{:?}|", SENTINEL, morestats);
let (usbcc_event, usbcc_regs, usbcc_rev) = env.com.poll_usb_cc().unwrap();
log::info!("{}|USBCC|{:?}|{:?}|{}|", SENTINEL, usbcc_event, usbcc_regs, usbcc_rev);
let mut av_pass = [true, true];
let mut ro_pass = true;
let mut av_excurs: [u32; 2] = [0; 2];
let mut ht = env.trng.get_health_tests().unwrap();
for _ in 0..3 { // run the test 3 times
av_excurs = [
(((ht.av_excursion[0].max as f64 - ht.av_excursion[0].min as f64) / 4096.0) * 1000.0) as u32,
(((ht.av_excursion[1].max as f64 - ht.av_excursion[1].min as f64) / 4096.0) * 1000.0) as u32,
];
// 78mv minimum excursion requirement for good entropy generation
if av_excurs[0] < 78 { av_pass[0] = false; }
if av_excurs[1] < 78 { av_pass[1] = false; }
for core in ht.ro_miniruns.iter() {
for (bin, &val) in core.run_count.iter().enumerate() {
match bin {
0 => {
if val < 440 || val > 584 { ro_pass = false; }
},
1 => {
if val < 193 || val > 318 { ro_pass = false; }
},
2 => {
if val < 80 || val > 175 { ro_pass = false; }
},
3 => {
if val < 29 || val > 99 { ro_pass = false; }
}
_ => {
log::error!("internal error: too many bins in trng test!");
}
}
}
}
const ROUNDS: usize = 16; // pump a bunch of data to trigger another trng buffer refill, resetting the stats
for _ in 0..ROUNDS {
let mut buf: [u32; 1024] = [0; 1024];
env.trng.fill_buf(&mut buf).unwrap();
log::debug!("pump samples: {:x}, {:x}, {:x}", buf[0], buf[512], buf[1023]); // prevent the pump values from being optimized out
}
ht = env.trng.get_health_tests().unwrap();
}
if av_pass[0] && av_pass[1] && ro_pass {
log::info!("{}|TRNG|PASS|{}|{}|{}|{}|{}|{}|", SENTINEL, av_excurs[0], av_excurs[1],
ht.ro_miniruns[0].run_count[0],
ht.ro_miniruns[0].run_count[1],
ht.ro_miniruns[0].run_count[2],
ht.ro_miniruns[0].run_count[3],
);
}
if !av_pass[0] {
log::info!("{}|TRNG|FAIL|AV0|{}|", SENTINEL, av_excurs[0]);
}
if !av_pass[1] {
log::info!("{}|TRNG|FAIL|AV1|{}|", SENTINEL, av_excurs[1]);
}
if !ro_pass {
log::info!("{}|TRNG|FAIL|RO|{}|{}|{}|{}|", SENTINEL,
ht.ro_miniruns[0].run_count[0],
ht.ro_miniruns[0].run_count[1],
ht.ro_miniruns[0].run_count[2],
ht.ro_miniruns[0].run_count[3],
);
}
let ut = env.com.get_ec_uptime().unwrap();
env.llio.ec_reset().unwrap();
env.ticktimer.sleep_ms(4000).unwrap(); // wait so we have some realistic delta on the datetime function
self.end_elapsed = Some(env.ticktimer.elapsed_ms());
self.end_time = rtc_get(&mut env.llio);
let exact_time_secs = ((self.end_elapsed.unwrap() - self.start_elapsed.unwrap()) / 1000) as i32;
if let Some(end_dt) = self.end_time {
if let Some(start_dt) = self.start_time {
// this method of computation fails if the test was started just before midnight
// on the last day of the month and completes just after. we set the time so we ensure this
// can't happen.
let end_secs =
end_dt.days as i32 * 24 * 60 * 60 +
end_dt.hours as i32 * 60 * 60 +
end_dt.minutes as i32 * 60 +
end_dt.seconds as i32;
let start_secs =
start_dt.days as i32 * 24 * 60 * 60 +
start_dt.hours as i32 * 60 * 60 +
start_dt.minutes as i32 * 60 +
start_dt.seconds as i32;
let elapsed_secs = end_secs - start_secs;
let delta = exact_time_secs - elapsed_secs;
if delta.abs() > 2 {
log::info!("{}|RTC|FAIL|{}|{}|", SENTINEL, exact_time_secs, elapsed_secs);
} else {
log::info!("{}|RTC|PASS|{}|{}|", SENTINEL, exact_time_secs, elapsed_secs);
}
} else {
log::info!("{}|RTC|FAIL|NO_START|", SENTINEL);
}
} else {
log::info!("{}|RTC|FAIL|NO_END|", SENTINEL);
}
let ut_after = env.com.get_ec_uptime().unwrap();
if ut < ut_after || ut_after > 4200 {
log::info!("{}|ECRESET|FAIL|{}|{}|", SENTINEL, ut, ut_after);
} else {
log::info!("{}|ECRESET|PASS|{}|{}|", SENTINEL, ut, ut_after);
}
log::info!("{}|DONE|", SENTINEL);
write!(ret, "Factory test script has run, check serial terminal for output").unwrap();
env.llio.wfi_override(false).unwrap();
}
"bl2" => {
env.llio.wfi_override(true).unwrap();
env.com.set_backlight(255, 255).unwrap();
log::info!("{}|BL2|", SENTINEL);
}
"bl1" => {
env.llio.wfi_override(true).unwrap();
env.com.set_backlight(180, 180).unwrap();
log::info!("{}|BL1|", SENTINEL);
}
"bl0" => {
env.llio.wfi_override(true).unwrap();
env.com.set_backlight(0, 0).unwrap();
log::info!("{}|BL0|", SENTINEL);
}
"wfireset" => {
env.llio.wfi_override(false).unwrap();
log::info!("{}|WFIRESET|", SENTINEL);
}
"wfioff" => {
env.llio.wfi_override(true).unwrap();
log::info!("{}|WFIOFF|", SENTINEL);
}
"vibe" => {
env.llio.vibe(llio::VibePattern::Long).unwrap();
log::info!("{}|VIBE|", SENTINEL);
}
"booston" => {
env.llio.boost_on(true).unwrap();
env.com.set_boost(true).unwrap();
log::info!("{}|BOOSTON|", SENTINEL);
}
"boostoff" => {
env.com.set_boost(false).unwrap();
env.ticktimer.sleep_ms(50).unwrap();
env.llio.boost_on(false).unwrap();
log::info!("{}|BOOSTOFF|", SENTINEL);
}
"astart" => {
self.freq = if let Some(freq_str) = tokens.next() {
match freq_str.parse::<f32>() {
Ok(f) => f,
Err(_) => 440.0,
}
} else {
440.0
};
if let Some(channel_str) = tokens.next() {
match channel_str {
"left" => {self.left_play = true; self.right_play = false; self.speaker_play = false;},
"right" => {self.right_play = true; self.left_play = false; self.speaker_play = false;},
"speaker" => {self.left_play = true; self.right_play = false; self.speaker_play = true;},
_ => {self.left_play = true; self.right_play = true; self.speaker_play = true;}
}
} else {
self.left_play = true;
self.right_play = true;
self.speaker_play = true;
}
self.codec.setup_8k_stream().expect("couldn't set the CODEC to expected defaults");
env.ticktimer.sleep_ms(50).unwrap();
if self.speaker_play {
self.codec.set_speaker_volume(VolumeOps::RestoreDefault, None).unwrap();
} else {
self.codec.set_speaker_volume(VolumeOps::Mute, None).unwrap();
}
if self.left_play || self.right_play {
self.codec.set_headphone_volume(VolumeOps::RestoreDefault, None).unwrap();
} else {
self.codec.set_headphone_volume(VolumeOps::Mute, None).unwrap();
}
if self.callback_id.is_none() {
let cb_id = env.register_handler(String::<256>::from_str(self.verb()));
log::trace!("hooking frame callback with ID {}", cb_id);
self.codec.hook_frame_callback(cb_id, self.callback_conn).unwrap(); // any non-handled IDs get routed to our callback port
self.callback_id = Some(cb_id);
}
self.play_sample = 0.0;
self.rec_sample = 0;
self.codec.resume().unwrap();
log::info!("{}|ASTART|{}|{}|{}|", SENTINEL, self.freq, self.left_play, self.right_play);
}
"astop" => {
self.codec.pause().unwrap(); // this should stop callbacks from occurring too.
write!(ret, "Playback stopped at {} frames.", self.framecount).unwrap();
self.framecount = 0;
self.play_sample = 0.0;
self.rec_sample = 0;
self.codec.power_off().unwrap();
// now do FFT analysis on the sample buffer
// analyze one channel at a time
let mut right_samples = Vec::<f32>::new();
let recslice = self.recbuf.as_slice::<u32>();
for &sample in recslice[recslice.len()-4096..].iter() {
right_samples.push( ((sample & 0xFFFF) as i16) as f32 );
//left_samples.push( (((sample >> 16) & 0xFFFF) as i16) as f32 ); // reminder of how to extract the right channel
}
// only one channel is considered, because in reality the left is just a copy of the right, as
// we are taking a mono microphone signal and mixing it into both ADCs
let db = db_compute(&right_samples);
let hann_right = hann_window(&right_samples);
let spectrum_right = samples_fft_to_spectrum(
&hann_right,
SAMPLE_RATE_HZ as _,
FrequencyLimit::All,
None,
None
);
asciiplot(&spectrum_right);
let ratio = analyze(&spectrum_right, self.freq);
// ratio typical range 0.35 (speaker) to 3.5 (headphones)
// speaker has a wider spectrum because we don't have a filter on the PWM, so there are sampling issues feeding it back into the mic
// db typical <10 (silence) to 78 (full amplitude)
if (ratio > 0.25) && (db > 60.0) {
log::info!("{}|ARESULT|PASS|{}|{}|{}|{}|{}|", SENTINEL, ratio, db, self.freq, self.left_play, self.right_play);
} else {
log::info!("{}|ARESULT|FAIL|{}|{}|{}|{}|{}|", SENTINEL, ratio, db, self.freq, self.left_play, self.right_play);
}
log::debug!("off-target 1 {}", analyze(&spectrum_right, 329.63));
log::debug!("off-target 2 {}", analyze(&spectrum_right, 261.63));
log::info!("{}|ASTOP|", SENTINEL);
}
"devboot" => {
env.gam.set_devboot(true).unwrap();
write!(ret, "devboot on").unwrap();
@ -43,6 +384,220 @@ impl<'a> ShellCmdApi<'a> for Test {
}
Ok(Some(ret))
}
fn callback(&mut self, msg: &MessageEnvelope, _env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error> {
const AMPLITUDE: f32 = 0.8;
match &msg.body {
Message::Scalar(xous::ScalarMessage{id: _, arg1: free_play, arg2: _avail_rec, arg3: _, arg4: _}) => {
log::debug!("{} extending playback", free_play);
let mut frames: FrameRing = FrameRing::new();
let frames_to_push = if frames.writeable_count() < *free_play {
frames.writeable_count()
} else {
*free_play
};
self.framecount += frames_to_push as u32;
log::debug!("f{} p{}", self.framecount, frames_to_push);
for _ in 0..frames_to_push {
let mut frame: [u32; codec::FIFO_DEPTH] = [ZERO_PCM as u32 | (ZERO_PCM as u32) << 16; codec::FIFO_DEPTH];
// put the "expensive" f32 comparison outside the cosine wave table computation loop
let omega = self.freq * 2.0 * std::f32::consts::PI / SAMPLE_RATE_HZ;
for sample in frame.iter_mut() {
let raw_sine: i16 = (AMPLITUDE * f32::cos( self.play_sample * omega ) * i16::MAX as f32) as i16;
let left = if self.left_play { raw_sine as u16 } else { ZERO_PCM };
let right = if self.right_play { raw_sine as u16 } else { ZERO_PCM };
*sample = right as u32 | (left as u32) << 16;
self.play_sample += 1.0;
}
frames.nq_frame(frame).unwrap();
}
self.codec.swap_frames(&mut frames).unwrap();
let rec_samples = self.recbuf.as_slice_mut::<u32>();
let rec_len = rec_samples.len();
loop {
if let Some(frame) = frames.dq_frame() {
for &sample in frame.iter() {
rec_samples[self.rec_sample] = sample;
// increment and wrap around on overflow
// we should be sampling a continuous tone, so we'll get a small phase discontinutity once in the buffer.
// should be no problem for the analysis phase.
self.rec_sample += 1;
if self.rec_sample >= rec_len {
self.rec_sample = 0;
}
}
} else {
break;
};
}
},
Message::Move(_mm) => {
log::error!("received memory message when not expected")
},
_ => {
log::error!("received unknown callback type")
}
}
log::debug!("audio callback");
Ok(None)
}
}
// plus minus this amount for frequencing searching
// this is set less by our desired accuracy of the frequency
// than by the artifacts of the analysis: the FFT window has some "skirt" to it
// by a few Hz, and this ratio tries to capture about 90% of the power within the hanning window's skirt.
const ANALYSIS_DELTA: f32 = 10.0;
fn analyze(fs: &FrequencySpectrum, target: f32) -> f32 {
let mut total_power: f32 = 0.0;
let mut h1_power: f32 = 0.0;
let mut h2_power: f32 = 0.0;
let mut outside_power: f32 = 0.0;
for &(freq, mag) in fs.data().iter() {
let f = freq.val();
let m = mag.val();
total_power += m;
if (f >= target - ANALYSIS_DELTA) && (f <= target + ANALYSIS_DELTA) {
h1_power += m;
} else if (f >= (target * 2.0 - ANALYSIS_DELTA)) && (f <= (target * 2.0 + ANALYSIS_DELTA)) {
h2_power += m;
} else if f >= ANALYSIS_DELTA { // don't count the DC offset
outside_power += m;
} else {
log::debug!("ignoring {}Hz @ {}", f, m);
}
}
log::debug!("h1: {}, h2: {}, outside: {}, total: {}", h1_power, h2_power, outside_power, total_power);
let ratio = if outside_power > 0.0 {
(h1_power + h2_power) / outside_power
} else {
1_000_000.0
};
ratio
}
fn db_compute(samps: &[f32]) -> f32 {
let mut cum = 0.0;
for &s in samps.iter() {
cum += s;
}
let mid = cum / samps.len() as f32;
cum = 0.0;
for &s in samps.iter() {
let a = s - mid;
cum += a * a;
}
cum /= samps.len() as f32;
let db = 10.0 * f32::log10(cum);
db
}
fn asciiplot(fs: &FrequencySpectrum) {
let (max_f, max_val) = fs.max();
const LINES: usize = 100;
const WIDTH: usize = 80;
const MAX_F: usize = 1000;
for f in (0..MAX_F).step_by(MAX_F / LINES) {
let (freq, val) = fs.freq_val_closest(f as f32);
let pos = ((val.val() / max_val.val()) * WIDTH as f32) as usize;
log::debug!("{:>5} | {:width$}*", freq.val() as u32, " ", width = pos);
}
log::debug!("max freq: {}, max_val: {}", max_f, max_val);
}
/// convert binary to BCD
fn to_bcd(binary: u8) -> u8 {
let mut lsd: u8 = binary % 10;
if lsd > 9 {
lsd = 9;
}
let mut msd: u8 = binary / 10;
if msd > 9 {
msd = 9;
}
(msd << 4) | lsd
}
fn to_binary(bcd: u8) -> u8 {
(bcd & 0xf) + ((bcd >> 4) * 10)
}
fn to_weekday(bcd: u8) -> Weekday {
match bcd {
0 => Weekday::Sunday,
1 => Weekday::Monday,
2 => Weekday::Tuesday,
3 => Weekday::Wednesday,
4 => Weekday::Thursday,
5 => Weekday::Friday,
6 => Weekday::Saturday,
_ => Weekday::Sunday,
}
}
const ABRTCMC_I2C_ADR: u8 = 0x68;
const ABRTCMC_CONTROL3: u8 = 0x02;
const ABRTCMC_SECONDS: u8 = 0x3;
// vendor in the RTC code -- the RTC system was not architected to do our test sets
// in particular we need a synchronous callback on the date/time, which is not terribly useful in most other contexts
// so instead of burdening the OS with it, we just incorprate it specifically into this test function
fn rtc_set(llio: &mut llio::Llio, secs: u8, mins: u8, hours: u8, days: u8, months: u8, years: u8) -> bool {
let mut txbuf: [u8; 8] = [0; 8];
// convert enum to bitfields
let d = 1;
// make sure battery switchover is enabled, otherwise we won't keep time when power goes off
txbuf[0] = 0;
txbuf[1] = to_bcd(secs);
txbuf[2] = to_bcd(mins);
txbuf[3] = to_bcd(hours);
txbuf[4] = to_bcd(days);
txbuf[5] = to_bcd(d);
txbuf[6] = to_bcd(months);
txbuf[7] = to_bcd(years);
match llio.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL3, &txbuf, None) {
Ok(status) => {
match status {
I2cStatus::ResponseWriteOk => true,
I2cStatus::ResponseBusy => {log::error!("i2c server busy on RTC test function"); false},
_ => {log::error!("try_send_i2c unhandled response: {:?}", status); false},
}
}
_ => {log::error!("try_send_i2c unhandled error"); false}
}
}
fn rtc_get(llio: &mut llio::Llio) -> Option<DateTime> {
let mut rxbuf = [0; 7];
match llio.i2c_read(ABRTCMC_I2C_ADR, ABRTCMC_SECONDS, &mut rxbuf, None) {
Ok(status) => {
match status {
I2cStatus::ResponseReadOk => {
let dt = DateTime {
seconds: to_binary(rxbuf[0] & 0x7f),
minutes: to_binary(rxbuf[1] & 0x7f),
hours: to_binary(rxbuf[2] & 0x3f),
days: to_binary(rxbuf[3] & 0x3f),
weekday: to_weekday(rxbuf[4] & 0x7f),
months: to_binary(rxbuf[5] & 0x1f),
years: to_binary(rxbuf[6]),
};
Some(dt)
},
_ => None,
}
}
_ => None
}
}

Binary file not shown.

View file

@ -37,6 +37,6 @@ chrono = "0.4"
[features]
debugprint = []
slowstatus = [] # used for braille mode, so console isn't overwhelmed with status
braille = [] # used for braille mode, so console isn't overwhelmed with status
# default = ["debugprint"] # "debugprint"
default = []

View file

@ -277,7 +277,7 @@ fn xmain() -> ! {
let stats_interval;
let batt_interval;
let secnotes_interval;
if cfg!(feature = "slowstatus") {
if cfg!(feature = "braille") {
// lower the status output rate for braille mode, debugging, etc.
stats_interval = 30;
batt_interval = 60;
@ -310,7 +310,7 @@ fn xmain() -> ! {
)
.expect("couldn't create menu thread");
info!("|status: starting main loop");
info!("|status: starting main loop"); // don't change this -- factory test looks for this exact string
loop {
let msg = xous::receive_message(status_sid).unwrap();
log::trace!("|status: Message: {:?}", msg);

View file

@ -569,7 +569,7 @@ where
/// Read the contents of this register
pub fn r(&self, reg: Register) -> T {
// prevent re-ordering
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::Acquire);
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
let usize_base: *mut usize = unsafe { core::mem::transmute(self.base) };
unsafe { usize_base.add(reg.offset).read_volatile() }
@ -579,7 +579,7 @@ where
/// Read a field from this CSR
pub fn rf(&self, field: Field) -> T {
// prevent re-ordering
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::Acquire);
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
let usize_base: *mut usize = unsafe { core::mem::transmute(self.base) };
((unsafe { usize_base.add(field.register.offset).read_volatile() } >> field.offset)
@ -599,7 +599,7 @@ where
.write_volatile(previous | value_as_usize)
};
// prevent re-ordering
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::Acquire);
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
}
/// Write a given field without reading it first
pub fn wfo(&mut self, field: Field, value: T) {

View file

@ -89,11 +89,11 @@ optional arguments:
```
You can try reading the first word out of the ROM to see if `usb_update.py` is working correctly.
It's located at 0x20000000, and it's always `0x665599aa` (this is the Xilinx FPGA bitstream sync word),
It's located at 0x20000008, and it's always `0x665599aa` (this is the Xilinx FPGA bitstream sync word),
as follows:
```
% python3 ./usb_update.py --peek 0x20000000
% python3 ./usb_update.py --peek 0x20000008
0x665599aa
```

View file

@ -166,11 +166,11 @@ class PrecursorUsb:
exit(1)
def ping_wdt(self):
self.poke(self.register('wdt_watchdog'), 0x600d, display=False)
self.poke(self.register('wdt_watchdog'), 0xc0de, display=False)
self.poke(self.register('wdt_watchdog'), 1, display=False)
self.poke(self.register('wdt_watchdog'), 1, display=False)
def load_csrs(self):
LOC_CSRCSV = 0x20278000 # this address shouldn't change because it's how we figure out our version number
LOC_CSRCSV = 0x20277000 # this address shouldn't change because it's how we figure out our version number
csr_data = self.burst_read(LOC_CSRCSV, 0x8000)
hasher = hashlib.sha512()
@ -254,17 +254,32 @@ def main():
pc_usb.load_csrs() # prime the CSR values
if "v0.8" in pc_usb.gitrev:
LOC_SOC = 0x00000000
LOC_STAGING= 0x00280000
LOC_LOADER = 0x00500000
LOC_KERNEL = 0x00980000
LOC_WF200 = 0x07F80000
LOC_EC = 0x07FCE000
LOC_AUDIO = 0x06340000
LEN_AUDIO = 0x01C40000
elif "v0.9" in pc_usb.gitrev:
LOC_SOC = 0x00000000
LOC_STAGING= 0x00280000
LOC_LOADER = 0x00500000
LOC_KERNEL = 0x00980000
LOC_WF200 = 0x07F80000
LOC_EC = 0x07FCE000
LOC_AUDIO = 0x06340000
LEN_AUDIO = 0x01C40000
elif args.force == True:
# try the v0.8 offsets
LOC_SOC = 0x00000000
LOC_STAGING= 0x00280000
LOC_LOADER = 0x00500000
LOC_KERNEL = 0x00980000
LOC_WF200 = 0x07F80000
LOC_EC = 0x07FCE000
LOC_AUDIO = 0x06340000
LEN_AUDIO = 0x01C40000
else:
sys.stderr.write("SoC is from an unknow rev '{}', use --force to continue anyways with v0.8 firmware offsets".format(pc_usb.load_csrs()))
exit(1)

540
tools/usb_update_xous_0.8.py Executable file
View file

@ -0,0 +1,540 @@
#! /usr/bin/env python3
import argparse
import usb.core
import usb.util
import array
import sys
import hashlib
import csv
from progressbar.bar import ProgressBar
class PrecursorUsb:
def __init__(self, dev):
self.dev = dev
self.RDSR = 0x05
self.RDSCUR = 0x2B
self.RDID = 0x9F
self.WREN = 0x06
self.WRDI = 0x04
self.SE4B = 0x21
self.BE4B = 0xDC
self.PP4B = 0x12
self.registers = {}
self.regions = {}
self.gitrev = ''
def register(self, name):
return int(self.registers[name], 0)
def peek(self, addr, display=False):
_dummy_s = '\x00'.encode('utf-8')
data = array.array('B', _dummy_s * 4)
numread = self.dev.ctrl_transfer(bmRequestType=(0x80 | 0x43), bRequest=0,
wValue=(addr & 0xffff), wIndex=((addr >> 16) & 0xffff),
data_or_wLength=data, timeout=500)
read_data = int.from_bytes(data.tobytes(), byteorder='little', signed=False)
if display == True:
print("0x{:08x}".format(read_data))
return read_data
def poke(self, addr, wdata, check=False, display=False):
if check == True:
_dummy_s = '\x00'.encode('utf-8')
data = array.array('B', _dummy_s * 4)
numread = self.dev.ctrl_transfer(bmRequestType=(0x80 | 0x43), bRequest=0,
wValue=(addr & 0xffff), wIndex=((addr >> 16) & 0xffff),
data_or_wLength=data, timeout=500)
read_data = int.from_bytes(data.tobytes(), byteorder='little', signed=False)
print("before poke: 0x{:08x}".format(read_data))
data = array.array('B', wdata.to_bytes(4, 'little'))
numwritten = self.dev.ctrl_transfer(bmRequestType=(0x00 | 0x43), bRequest=0,
wValue=(addr & 0xffff), wIndex=((addr >> 16) & 0xffff),
data_or_wLength=data, timeout=500)
if check == True:
_dummy_s = '\x00'.encode('utf-8')
data = array.array('B', _dummy_s * 4)
numread = self.dev.ctrl_transfer(bmRequestType=(0x80 | 0x43), bRequest=0,
wValue=(addr & 0xffff), wIndex=((addr >> 16) & 0xffff),
data_or_wLength=data, timeout=500)
read_data = int.from_bytes(data.tobytes(), byteorder='little', signed=False)
print("after poke: 0x{:08x}".format(read_data))
if display == True:
print("wrote 0x{:08x} to 0x{:08x}".format(wdata, addr))
def burst_read(self, addr, len):
_dummy_s = '\x00'.encode('utf-8')
maxlen = 4096
ret = bytearray()
packet_count = len // maxlen
if (len % maxlen) != 0:
packet_count += 1
for pkt_num in range(packet_count):
cur_addr = addr + pkt_num * maxlen
if pkt_num == packet_count - 1:
if len % maxlen != 0:
bufsize = len % maxlen
else:
bufsize = maxlen
else:
bufsize = maxlen
data = array.array('B', _dummy_s * bufsize)
numread = self.dev.ctrl_transfer(bmRequestType=(0x80 | 0x43), bRequest=0,
wValue=(cur_addr & 0xffff), wIndex=((cur_addr >> 16) & 0xffff),
data_or_wLength=data, timeout=500)
if numread != bufsize:
print("Burst read error: {} bytes requested, {} bytes read at 0x{:08x}".format(bufsize, numread, cur_addr))
exit(1)
ret = ret + data
return ret
def burst_write(self, addr, data):
if len(data) == 0:
return
maxlen = 4096
packet_count = len(data) // maxlen
if (len(data) % maxlen) != 0:
packet_count += 1
for pkt_num in range(packet_count):
cur_addr = addr + pkt_num * maxlen
if pkt_num == packet_count - 1:
if len(data) % maxlen != 0:
bufsize = len(data) % maxlen
else:
bufsize = maxlen
else:
bufsize = maxlen
wdata = array.array('B', data[(pkt_num * maxlen):(pkt_num * maxlen) + bufsize])
numwritten = self.dev.ctrl_transfer(bmRequestType=(0x00 | 0x43), bRequest=0,
wValue=(cur_addr & 0xffff), wIndex=((cur_addr >> 16) & 0xffff),
data_or_wLength=wdata, timeout=500)
if numwritten != bufsize:
print("Burst write error: {} bytes requested, {} bytes written at 0x{:08x}".format(bufsize, numwritten, cur_addr))
exit(1)
def ping_wdt(self):
self.poke(self.register('wdt_watchdog'), 0x600d, display=False)
self.poke(self.register('wdt_watchdog'), 0xc0de, display=False)
def spinor_command_value(self, exec=0, lock_reads=0, cmd_code=0, dummy_cycles=0, data_words=0, has_arg=0):
return ((exec & 1) << 1 |
(lock_reads & 1) << 24 |
(cmd_code & 0xff) << 2 |
(dummy_cycles & 0x1f) << 11 |
(data_words & 0xff) << 16 |
(has_arg & 1) << 10
)
def flash_rdsr(self, lock_reads):
self.poke(self.register('spinor_cmd_arg'), 0)
self.poke(self.register('spinor_command'),
self.spinor_command_value(exec=1, lock_reads=lock_reads, cmd_code=self.RDSR, dummy_cycles=4, data_words=1, has_arg=1)
)
return self.peek(self.register('spinor_cmd_rbk_data'), display=False)
def flash_rdscur(self):
self.poke(self.register('spinor_cmd_arg'), 0)
self.poke(self.register('spinor_command'),
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.RDSCUR, dummy_cycles=4, data_words=1, has_arg=1)
)
return self.peek(self.register('spinor_cmd_rbk_data'), display=False)
def flash_rdid(self, offset):
self.poke(self.register('spinor_cmd_arg'), 0)
self.poke(self.register('spinor_command'),
self.spinor_command_value(exec=1, cmd_code=self.RDID, dummy_cycles=4, data_words=offset, has_arg=1)
)
return self.peek(self.register('spinor_cmd_rbk_data'), display=False)
def flash_wren(self):
self.poke(self.register('spinor_cmd_arg'), 0)
self.poke(self.register('spinor_command'),
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.WREN)
)
def flash_wrdi(self):
self.poke(self.register('spinor_cmd_arg'), 0)
self.poke(self.register('spinor_command'),
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.WRDI)
)
def flash_se4b(self, sector_address):
self.poke(self.register('spinor_cmd_arg'), sector_address)
self.poke(self.register('spinor_command'),
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.SE4B, has_arg=1)
)
def flash_be4b(self, block_address):
self.poke(self.register('spinor_cmd_arg'), block_address)
self.poke(self.register('spinor_command'),
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.BE4B, has_arg=1)
)
def flash_pp4b(self, address, data_bytes):
self.poke(self.register('spinor_cmd_arg'), address)
self.poke(self.register('spinor_command'),
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.PP4B, has_arg=1, data_words=(data_bytes//2))
)
def load_csrs(self):
LOC_CSRCSV = 0x20278000 # this address shouldn't change because it's how we figure out our version number
csr_data = self.burst_read(LOC_CSRCSV, 0x8000)
hasher = hashlib.sha512()
hasher.update(csr_data[:0x7FC0])
digest = hasher.digest()
if digest != csr_data[0x7fc0:]:
print("Could not find a valid csr.csv descriptor on the device, aborting!")
exit(1)
csr_len = int.from_bytes(csr_data[:4], 'little')
csr_extracted = csr_data[4:4+csr_len]
decoded = csr_extracted.decode('utf-8')
# strip comments
stripped = []
for line in decoded.split('\n'):
if line.startswith('#') == False:
stripped.append(line)
# create database
csr_db = csv.reader(stripped)
for row in csr_db:
if len(row) > 1:
if 'csr_register' in row[0]:
self.registers[row[1]] = row[2]
if 'memory_region' in row[0]:
self.regions[row[1]] = [row[2], row[3]]
if 'git_rev' in row[0]:
self.gitrev = row[1]
print("Using SoC {} registers".format(self.gitrev))
# addr is relative to the base of FLASH (not absolute)
def flash_program(self, addr, data, verify=True):
flash_region = int(self.regions['spiflash'][0], 0)
flash_len = int(self.regions['spiflash'][1], 0)
if (addr + len(data) > flash_len):
print("Write data out of bounds! Aborting.")
exit(1)
# ID code check
code = self.flash_rdid(1)
print("ID code bytes 1-2: 0x{:08x}".format(code))
if code != 0x8080c2c2:
print("ID code mismatch")
exit(1)
code = self.flash_rdid(2)
print("ID code bytes 2-3: 0x{:08x}".format(code))
if code != 0x3b3b8080:
print("ID code mismatch")
exit(1)
# block erase
progress = ProgressBar(min_value=0, max_value=len(data), prefix='Erasing ').start()
erased = 0
while erased < len(data):
self.ping_wdt()
if (len(data) - erased >= 65536) and ((addr & 0xFFFF) == 0):
blocksize = 65536
else:
blocksize = 4096
while True:
self.flash_wren()
status = self.flash_rdsr(1)
if status & 0x02 != 0:
break
if blocksize == 4096:
self.flash_se4b(addr + erased)
else:
self.flash_be4b(addr + erased)
erased += blocksize
while (self.flash_rdsr(1) & 0x01) != 0:
pass
result = self.flash_rdscur()
if result & 0x60 != 0:
print("E_FAIL/P_FAIL set on erase, programming may fail, but trying anyways...")
if self.flash_rdsr(1) & 0x02 != 0:
self.flash_wrdi()
while (self.flash_rdsr(1) & 0x02) != 0:
pass
if erased < len(data):
progress.update(erased)
progress.finish()
print("Erase finished")
# program
# pad out to the nearest word length
if len(data) % 4 != 0:
data += bytearray([0xff] * (4 - (len(data) % 4)))
written = 0
progress = ProgressBar(min_value=0, max_value=len(data), prefix='Writing ').start()
while written < len(data):
self.ping_wdt()
if len(data) - written > 256:
chunklen = 256
else:
chunklen = len(data) - written
while True:
self.flash_wren()
status = self.flash_rdsr(1)
if status & 0x02 != 0:
break
self.burst_write(flash_region, data[written:(written+chunklen)])
self.flash_pp4b(addr + written, chunklen)
written += chunklen
if written < len(data):
progress.update(written)
progress.finish()
print("Write finished")
if self.flash_rdsr(1) & 0x02 != 0:
self.flash_wrdi()
while (self.flash_rdsr(1) & 0x02) != 0:
pass
# dummy reads to clear the "read lock" bit
self.flash_rdsr(0)
# verify
self.ping_wdt()
if verify:
print("Performing readback for verification...")
self.ping_wdt()
rbk_data = self.burst_read(addr + flash_region, len(data))
if rbk_data != data:
print("Errors were found in verification, programming failed")
exit(1)
else:
print("Verification passed.")
else:
print("Skipped verification at user request")
self.ping_wdt()
def auto_int(x):
return int(x, 0)
def main():
parser = argparse.ArgumentParser(description="Update/upload to a Precursor device running Xous 0.8/0.9")
parser.add_argument(
"--soc", required=False, help="'Factory Reset' the SoC gateware. Note: this will overwrite any secret keys stored in your device!", type=str, nargs='?', metavar=('SoC gateware file'), const='../precursors/soc_csr.bin'
)
parser.add_argument(
"-s", "--staging", required=False, help="Stage an update to apply", type=str, nargs='?', metavar=('SoC gateware file'), const='../precursors/soc_csr.bin'
)
parser.add_argument(
"-l", "--loader", required=False, help="Loader", type=str, nargs='?', metavar=('loader file'), const='../target/riscv32imac-unknown-xous-elf/release/loader.bin'
)
parser.add_argument(
"-k", "--kernel", required=False, help="Kernel", type=str, nargs='?', metavar=('kernel file'), const='../target/riscv32imac-unknown-xous-elf/release/xous.img'
)
parser.add_argument(
"-e", "--ec", required=False, help="EC gateware", type=str, nargs='?', metavar=('EC gateware package'), const='ec_fw.bin'
)
parser.add_argument(
"-w", "--wf200", required=False, help="WF200 firmware", type=str, nargs='?', metavar=('WF200 firmware package'), const='wf200_fw.bin'
)
parser.add_argument(
"--audiotest", required=False, help="Test audio clip (must be 8kHz WAV)", type=str, nargs='?', metavar=('Test audio clip'), const="testaudio.wav"
)
parser.add_argument(
"--peek", required=False, help="Inspect an address", type=auto_int, metavar=('ADDR')
)
parser.add_argument(
"--poke", required=False, help="Write to an address", type=auto_int, nargs=2, metavar=('ADDR', 'DATA')
)
parser.add_argument(
"--check-poke", required=False, action='store_true', help="Read data before and after the poke"
)
parser.add_argument(
"--config", required=False, help="Print the descriptor", action='store_true'
)
parser.add_argument(
"-i", "--image", required=False, help="Manually specify an image and address. Offset is relative to bottom of flash.", type=str, nargs=2, metavar=('IMAGEFILE', 'ADDR')
)
parser.add_argument(
"--verify", help="Readback verification. May fail for large files due to WDT timeout.", default=False, action='store_true'
)
parser.add_argument(
"--force", help="Ignore gitrev version on SoC and try to burn an image anyways", action="store_true"
)
parser.add_argument(
"--bounce", help="cycle the device through a reset", action="store_true"
)
args = parser.parse_args()
if not len(sys.argv) > 1:
print("No arguments specified, doing nothing. Use --help for more information.")
exit(1)
dev = usb.core.find(idProduct=0x5bf0, idVendor=0x1209)
if dev is None:
raise ValueError('Precursor device not found')
dev.set_configuration()
if args.config:
cfg = dev.get_active_configuration()
print(cfg)
pc_usb = PrecursorUsb(dev)
if args.verify:
verify = True
else:
verify = False
if args.peek:
pc_usb.peek(args.peek, display=True)
# print(burst_read(dev, args.peek, 256).hex())
exit(0)
if args.poke:
addr, data = args.poke
pc_usb.poke(addr, data, check=args.check_poke, display=True)
# import os
# d = bytearray(os.urandom(8000))
# burst_write(dev, addr, d)
# r = burst_read(dev, addr, 8000)
# print(r.hex())
# if d != r:
# print("mismatch")
# else:
# print("match")
exit(0)
pc_usb.load_csrs() # prime the CSR values
if "v0.8" in pc_usb.gitrev:
LOC_SOC = 0x00000000
LOC_STAGING= 0x00280000
LOC_LOADER = 0x00500000
LOC_KERNEL = 0x00980000
LOC_WF200 = 0x07F80000
LOC_EC = 0x07FCE000
LOC_AUDIO = 0x06340000
LEN_AUDIO = 0x01C40000
elif "v0.9" in pc_usb.gitrev:
LOC_SOC = 0x00000000
LOC_STAGING= 0x00280000
LOC_LOADER = 0x00500000
LOC_KERNEL = 0x00980000
LOC_WF200 = 0x07F80000
LOC_EC = 0x07FCE000
LOC_AUDIO = 0x06340000
LEN_AUDIO = 0x01C40000
elif args.force == True:
# try the v0.8 offsets
LOC_SOC = 0x00000000
LOC_STAGING= 0x00280000
LOC_LOADER = 0x00500000
LOC_KERNEL = 0x00980000
LOC_WF200 = 0x07F80000
LOC_EC = 0x07FCE000
LOC_AUDIO = 0x06340000
LEN_AUDIO = 0x01C40000
else:
print("SoC is from an unknow rev '{}', use --force to continue anyways with v0.8 firmware offsets".format(pc_usb.load_csrs()))
exit(1)
vexdbg_addr = int(pc_usb.regions['vexriscv_debug'][0], 0)
pc_usb.ping_wdt()
print("Halting CPU.")
pc_usb.poke(vexdbg_addr, 0x00020000)
if args.image:
image_file, addr_str = args.image
addr = int(addr_str, 0)
print("Burning manually specified image '{}' to address 0x{:08x} relative to bottom of FLASH".format(image_file, addr))
with open(image_file, "rb") as f:
image_data = f.read()
pc_usb.flash_program(addr, image_data, verify=verify)
if args.ec != None:
print("Staging EC firmware package '{}' in SOC memory space...".format(args.ec))
with open(args.ec, "rb") as f:
image = f.read()
pc_usb.flash_program(LOC_EC, image, verify=verify)
if args.wf200 != None:
print("Staging WF200 firmware package '{}' in SOC memory space...".format(args.wf200))
with open(args.wf200, "rb") as f:
image = f.read()
pc_usb.flash_program(LOC_WF200, image, verify=verify)
if args.staging != None:
print("Programming SoC gateware {}".format(args.soc))
with open(args.staging, "rb") as f:
image = f.read()
pc_usb.flash_program(LOC_STAGING, image, verify=verify)
if args.kernel != None:
print("Programming kernel image {}".format(args.kernel))
with open(args.kernel, "rb") as f:
image = f.read()
pc_usb.flash_program(LOC_KERNEL, image, verify=verify)
if args.loader != None:
print("Programming loader image {}".format(args.loader))
with open(args.loader, "rb") as f:
image = f.read()
pc_usb.flash_program(LOC_LOADER, image, verify=verify)
if args.soc != None:
print("This will overwrite any secret keys in your device. Continue? (y/n)")
confirm = input()
if len(confirm) > 0 and confirm.lower()[:1] == 'y':
print("Programming SoC gateware {}".format(args.soc))
with open(args.soc, "rb") as f:
image = f.read()
pc_usb.flash_program(LOC_SOC, image, verify=verify)
if args.audiotest != None:
print("Loading audio test clip {}".format(args.audiotest))
with open(args.audiotest, "rb") as f:
image = f.read()
if len(image) >= LEN_AUDIO:
print("audio file is too long, aborting audio burn!")
else:
pc_usb.flash_program(LOC_AUDIO, image, verify=verify)
print("Resuming CPU.")
pc_usb.poke(vexdbg_addr, 0x02000000)
print("Resetting SOC...")
try:
pc_usb.poke(pc_usb.register('reboot_soc_reset'), 0xac, display=False)
except usb.core.USBError:
pass # we expect an error because we reset the SOC and that includes the USB core
# print("If you need to run more commands, please unplug and re-plug your device in, as the Precursor USB core was just reset")
if __name__ == "__main__":
main()
exit(0)

View file

@ -0,0 +1,10 @@
[package]
name = "wycheproof-import"
version = "0.1.0"
edition = "2018"
[dependencies]
eyre = "0.6.5"
serde = { version = "1.0.129", features = ["derive"] }
serde_json = "1.0.66"
serde_with = { version = "1.9.4", features = ["hex"] }

View file

@ -0,0 +1,20 @@
# Wycheproof x25519 Test Vectors
This package contains code to make the Diffie-Hellman Key exchange test vectors for Curve25519
from [Project Wycheproof](https://github.com/google/wycheproof) usable for Xous.
Project Wycheproof is published under the [Apache-2.0 License](../LICENSES/Apache-2.0.txt). The
file [x25519_test.json](x25519_test.json) was imported from Project Wycheproof. See the newest corresponding commit
message to map the local file to the upstream file's version. A subset of the information therein is compiled to binary
using this package.
## Usage
The repository contains the precompiled test vectors. To run them, use the `engine wycheproof` command when running on
Renode or on real hardware.
### (Re-)compiling the test vectors
Run `cargo xtask wychproof-import` in order to compile the test cases in `wycheproof-import/x25519_test.json`
to `services/shellchat/src/cmds/x25519_test.bin` which will be included when compiling
the `services/shellchat/src/cmds/engine.rs`. The `xtask` command runs the local binary crate with the proper arguments.

View file

@ -0,0 +1,75 @@
use std::env;
use std::io::Write;
use std::ops::AddAssign;
use std::path::Path;
use std::process::exit;
use eyre::{bail, Result, WrapErr};
use serde::Deserialize;
#[derive(Deserialize)]
struct TestData {
#[serde(rename(deserialize = "testGroups"))]
test_groups: Vec<TestGroup>,
}
#[derive(Deserialize)]
struct TestGroup {
tests: Vec<TestCase>,
}
#[serde_with::serde_as]
#[derive(Debug, Deserialize)]
struct TestCase {
#[serde(rename(deserialize = "tcId"))]
id: usize,
#[serde_as(as = "serde_with::hex::Hex")]
public: [u8; 32],
#[serde_as(as = "serde_with::hex::Hex")]
private: [u8; 32],
#[serde_as(as = "serde_with::hex::Hex")]
shared: [u8; 32],
result: String,
}
fn main() -> Result<()> {
let args: Vec<String> = env::args().collect();
if args.len() != 3 {
println!("usage: wycheproof-import <input.json> <output.bin>");
exit(0);
}
let input_file_path = Path::new(&args[1]);
let output_file_path = Path::new(&args[2]);
let test_data = std::fs::read_to_string(input_file_path).wrap_err(format!(
"Could not read test data from '{}'",
input_file_path.to_string_lossy()
))?;
let test_data: TestData =
serde_json::from_str(&test_data).wrap_err("Error parsing test vectors")?;
let expected_results = vec!["valid".to_string(), "acceptable".to_string()];
let mut output_file = std::fs::File::create(output_file_path).wrap_err(format!(
"Error creating output file '{}'",
output_file_path.to_string_lossy()
))?;
let mut last_id = 0;
for test_case in &test_data.test_groups[0].tests {
if test_case.id != last_id + 1 {
bail!("Expect test cases to be continuously ascending. Expected next tcId to be {}, was {}", last_id + 1, test_case.id)
}
if !expected_results.contains(&test_case.result) {
bail!(
"Expect test case results to be one of {:?}",
expected_results
);
}
last_id.add_assign(1);
output_file.write_all(&test_case.public)?;
output_file.write_all(&test_case.private)?;
output_file.write_all(&test_case.shared)?;
}
Ok(())
}

File diff suppressed because it is too large Load diff

View file

@ -193,6 +193,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
Some("nuke-soc") => update_usb(false, false, true, false)?,
Some("burn-soc") => update_usb(false, false, false, true)?,
Some("generate-locales") => generate_locales()?,
Some("wycheproof-import") => whycheproof_import()?,
_ => print_help(),
}
Ok(())
@ -221,6 +222,7 @@ burn-loader invoke the `usb_update.py` utility to burn the loader
burn-soc invoke the `usb_update.py` utility to stage the SoC gateware, which must then be provisioned with secret material using the Precursor device.
nuke-soc 'Factory reset' - invoke the `usb_update.py` utility to burn the SoC gateware, erasing most secrets. For developers.
generate-locales only generate the locales include for the language selected in xous-rs/src/locale.rs
wycheproof-import generate binary test vectors for engine-25519 from whycheproof-import/x25519.json
Please refer to tools/README_UPDATE.md for instructions on how to set up `usb_update.py`
"
@ -875,6 +877,30 @@ fn generate_locales() -> Result<(), std::io::Error> {
filetime::set_file_mtime("locales/src/lib.rs", ts)
}
fn whycheproof_import() -> Result<(), DynError> {
let input_file = "tools/wycheproof-import/x25519_test.json";
let output_file = "services/shellchat/src/cmds/x25519_test.bin";
let status = Command::new(cargo())
.current_dir(project_root())
.args(&[
"run",
"--package",
"wycheproof-import",
"--",
input_file,
output_file
])
.status()?;
if !status.success() {
return Err("wycheproof-import failed. If any, the output will not be usable.".into());
}
println!();
println!("Wrote wycheproof x25519 testvectors to '{}'.", output_file);
return Ok(())
}
// fn dist_dir() -> PathBuf {
// project_root().join("target/dist")
// }