disastrous first draft of figuring out how to integrate smoltcp using a ping example.

This commit is contained in:
bunnie 2021-10-10 01:57:31 +08:00
parent 560c6e4197
commit 74a3c6df44
8 changed files with 280 additions and 28 deletions

12
Cargo.lock generated
View file

@ -461,7 +461,7 @@ dependencies = [
[[package]]
name = "com_rs"
version = "0.1.0"
source = "git+https://github.com/betrusted-io/com_rs.git?rev=37ad1e689ca48e610bd6ce1ee6a585ea05158e46#37ad1e689ca48e610bd6ce1ee6a585ea05158e46"
source = "git+https://github.com/betrusted-io/com_rs.git?rev=b3bf4aebe1d3c91e77dae5d3832d17e717c5669b#b3bf4aebe1d3c91e77dae5d3832d17e717c5669b"
[[package]]
name = "com_rs-ref"
@ -1172,9 +1172,9 @@ dependencies = [
[[package]]
name = "managed"
version = "0.7.2"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c75de51135344a4f8ed3cfe2720dc27736f7711989703a0b43aadf3753c55577"
checksum = "0ca88d725a0a943b096803bd34e73a4437208b6077654cc4ecb2947a5f91618d"
[[package]]
name = "maybe-uninit"
@ -1239,6 +1239,7 @@ dependencies = [
name = "net"
version = "0.1.0"
dependencies = [
"byteorder",
"com",
"llio",
"log",
@ -2048,9 +2049,8 @@ checksum = "fe0f37c9e8f3c5a4a66ad655a93c74daac4ad00c441533bf5c6e7990bb42604e"
[[package]]
name = "smoltcp"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e4a069bef843d170df47e7c0a8bf8d037f217d9f5b325865acc3e466ffe40d3"
version = "0.8.0"
source = "git+https://github.com/smoltcp-rs/smoltcp.git#35e833e33dfd3e4efc3eb7d5de06bec17c54b011"
dependencies = [
"bitflags",
"byteorder",

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 = "37ad1e689ca48e610bd6ce1ee6a585ea05158e46" }
com_rs = { git = "https://github.com/betrusted-io/com_rs.git", rev = "b3bf4aebe1d3c91e77dae5d3832d17e717c5669b" }
#com_rs = { path = "../../../betrusted-ec/sw/com_rs" }

View file

@ -181,6 +181,9 @@ pub(crate) enum Opcode {
/// wlan: get net packet
WlanFetchPacket,
/// wlan: send net packet
WlanSendPacket,
/// sets the EC-side com interrupt mask
IntSetMask,
@ -209,6 +212,8 @@ pub enum ComIntSources {
WlanIpConfigUpdate,
WlanSsidScanDone,
BatteryCritical,
WlanTxErr,
WlanRxErr,
Invalid,
}
impl From<u16> for ComIntSources {
@ -218,6 +223,8 @@ impl From<u16> for ComIntSources {
com_rs_ref::INT_WLAN_IPCONF_UPDATE => ComIntSources::WlanIpConfigUpdate,
com_rs_ref::INT_WLAN_SSID_UPDATE => ComIntSources::WlanSsidScanDone,
com_rs_ref::INT_BATTERY_CRITICAL => ComIntSources::BatteryCritical,
com_rs_ref::INT_WLAN_TX_ERROR => ComIntSources::WlanTxErr,
com_rs_ref::INT_WLAN_RX_ERROR => ComIntSources::WlanRxErr,
_ => ComIntSources::Invalid,
}
}
@ -229,6 +236,8 @@ impl From<ComIntSources> for u16 {
ComIntSources::WlanIpConfigUpdate => com_rs_ref::INT_WLAN_IPCONF_UPDATE,
ComIntSources::WlanSsidScanDone => com_rs_ref::INT_WLAN_SSID_UPDATE,
ComIntSources::WlanRxReady => com_rs_ref::INT_WLAN_RX_READY,
ComIntSources::WlanTxErr => com_rs_ref::INT_WLAN_TX_ERROR,
ComIntSources::WlanRxErr => com_rs_ref::INT_WLAN_RX_ERROR,
ComIntSources::Invalid => 0,
}
}

View file

@ -457,6 +457,22 @@ impl Com {
Ok(())
}
pub fn wlan_send_packet(&self, pkt: &[u8]) -> Result<(), xous::Error> {
if pkt.len() > NET_MTU {
return Err(xous::Error::OutOfMemory)
}
let mut prealloc: [u8; NET_MTU + 2] = [0; NET_MTU + 2];
let len_bytes = (pkt.len() as u16).to_be_bytes();
prealloc[0] = len_bytes[0];
prealloc[1] = len_bytes[1];
for (&src, dst) in pkt.iter().zip(prealloc[2..].iter_mut()) {
*dst = src;
}
let buf = Buffer::into_buf(prealloc).or(Err(xous::Error::InternalError))?;
buf.send(self.conn, Opcode::WlanSendPacket.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
Ok(())
}
pub fn ints_enable(&self, int_list: &[ComIntSources]) {
let mut mask_val: u16 = 0;
for &item in int_list.iter() {

View file

@ -762,11 +762,11 @@ fn xmain() -> ! {
} else {
len_bytes / 2 + 1
};
if len_words > NET_MTU as u16 / 2 {
log::error!("invalid packet fetch length: {}, aborting without fetch", len_words);
if len_bytes > NET_MTU as u16 {
log::error!("invalid packet fetch length: {}, aborting without fetch", len_bytes);
continue;
}
com.txrx(ComState::NET_FRAME_FETCH_0.verb | len_words);
com.txrx(ComState::NET_FRAME_FETCH_0.verb | len_bytes);
for word_index in 0..len_words as usize {
let w = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT));
let be_bytes = w.to_be_bytes();
@ -775,6 +775,26 @@ fn xmain() -> ! {
}
buffer.replace(retbuf).expect("couldn't return packet");
}
Some(Opcode::WlanSendPacket) => {
let buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let txbuf = buffer.as_flat::<[u8; NET_MTU + 2], _>().unwrap();
let be_bytes: [u8; 2] = [txbuf[0], txbuf[1]];
let len_bytes = u16::from_be_bytes(be_bytes);
let len_words = if len_bytes % 2 == 0 {
len_bytes / 2
} else {
len_bytes / 2 + 1
};
if len_bytes > NET_MTU as u16 {
log::error!("invalid packet send length: {}, aborting without send", len_bytes);
continue;
}
com.txrx(ComState::NET_FRAME_SEND_0.verb | len_bytes);
for word_index in 0..len_words as usize {
let be_bytes: [u8; 2] = [txbuf[2 + word_index * 2], txbuf[2 + word_index * 2 + 1]];
com.txrx(u16::from_be_bytes(be_bytes));
}
}
Some(Opcode::IntSetMask) => msg_blocking_scalar_unpack!(msg, mask_val, _, _, _, {
com.txrx(ComState::LINK_SET_INTMASK.verb);
com.txrx(mask_val as u16);

View file

@ -44,7 +44,6 @@ mod implementation {
fn handle_event_irq(_irq_no: usize, arg: *mut usize) {
let xl = unsafe { &mut *(arg as *mut Llio) };
// just clear the pending request for now and return
if xl.event_csr.rf(utra::btevents::EV_PENDING_COM_INT) != 0 {
if let Some(conn) = xl.handler_conn {
xous::try_send_message(conn,

View file

@ -17,9 +17,15 @@ susres = {path = "../susres"}
rkyv = "0.7.18"
llio = {path = "../llio"}
com = {path = "../com"}
byteorder = { version = "1.0", default-features = false }
[dependencies.smoltcp]
version = "0.7.5"
# ugh. have to reference `main` directly because they haven't pushed a new tag in months, and none
# of the worked examples match the actual documentation now.
# pin at a commit, at least, so we aren't building on shifting sand
git = "https://github.com/smoltcp-rs/smoltcp.git"
commit = "35e833e33dfd3e4efc3eb7d5de06bec17c54b011"
#version = "0.7.5"
#features = ["proto-ipv4"]

View file

@ -6,13 +6,70 @@ use api::*;
use num_traits::*;
use com::api::{Ipv4Conf, NET_MTU, ComIntSources};
/*
use smoltcp::iface::{InterfaceBuilder, NeighborCache};
use smoltcp::phy::{Loopback, Medium};
use smoltcp::socket::{SocketSet, TcpSocket, TcpSocketBuffer};
use smoltcp::time::{Duration, Instant};
use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr};
*/
mod device;
use device::*;
use byteorder::{ByteOrder, NetworkEndian};
use std::cmp;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::str::FromStr;
use smoltcp::phy::{Loopback, Medium, Device};
use smoltcp::iface::{InterfaceBuilder, NeighborCache, Routes, Interface};
use smoltcp::socket::{IcmpEndpoint, IcmpPacketMetadata, IcmpSocket, IcmpSocketBuffer, SocketSet};
use smoltcp::wire::{
EthernetAddress, Icmpv4Packet, Icmpv4Repr, IpAddress, IpCidr, Ipv4Address, Ipv4Cidr,
};
use smoltcp::{
time::{Duration, Instant},
};
macro_rules! send_icmp_ping {
( $repr_type:ident, $packet_type:ident, $ident:expr, $seq_no:expr,
$echo_payload:expr, $socket:expr, $remote_addr:expr ) => {{
let icmp_repr = $repr_type::EchoRequest {
ident: $ident,
seq_no: $seq_no,
data: &$echo_payload,
};
let icmp_payload = $socket.send(icmp_repr.buffer_len(), $remote_addr).unwrap();
let icmp_packet = $packet_type::new_unchecked(icmp_payload);
(icmp_repr, icmp_packet)
}};
}
macro_rules! get_icmp_pong {
( $repr_type:ident, $repr:expr, $payload:expr, $waiting_queue:expr, $remote_addr:expr,
$timestamp:expr, $received:expr ) => {{
if let $repr_type::EchoReply { seq_no, data, .. } = $repr {
if let Some(_) = $waiting_queue.get(&seq_no) {
let packet_timestamp_ms = NetworkEndian::read_i64(data);
println!(
"{} bytes from {}: icmp_seq={}, time={}ms",
data.len(),
$remote_addr,
seq_no,
$timestamp.total_millis() - packet_timestamp_ms
);
$waiting_queue.remove(&seq_no);
$received += 1;
}
}
}};
}
fn set_ipv4_addr<DeviceT>(iface: &mut Interface<'_, DeviceT>, cidr: Ipv4Cidr)
where
DeviceT: for<'d> Device<'d>,
{
iface.update_ip_addrs(|addrs| {
let dest = addrs.iter_mut().next().unwrap();
*dest = IpCidr::Ipv4(cidr);
});
}
#[xous::xous_main]
fn xmain() -> ! {
@ -43,10 +100,49 @@ fn xmain() -> ! {
com.ints_get_active(&mut com_int_list);
log::info!("COM pending interrupts after enabling: {:?}", com_int_list);
let mut net_config: Ipv4Conf; // = Ipv4Conf::default();
let mut net_config: Option<Ipv4Conf> = None;
let mut incoming_pkt_buf: [u8; NET_MTU] = [0; NET_MTU];
let mut incoming_pkt: &mut [u8];
// ping-specific storage
let ping_remote_addr = IpAddress::from_str("10.0.245.10").expect("invalid address format");
let icmp_rx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::EMPTY], vec![0; 256]);
let icmp_tx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::EMPTY], vec![0; 256]);
let icmp_socket = IcmpSocket::new(icmp_rx_buffer, icmp_tx_buffer);
let mut sockets = SocketSet::new(vec![]);
let icmp_handle = sockets.add(icmp_socket);
let mut send_at = Instant::from_millis(0);
let mut seq_no = 0;
let mut received = 0;
let mut echo_payload = [0xffu8; 40];
let mut waiting_queue = HashMap::new();
let ident = 0x22b;
let count = 10; // number of ping iters
let interval = Duration::from_secs(1);
let timeout = Duration::from_secs(10);
// link storage
let neighbor_cache = NeighborCache::new(BTreeMap::new());
let mut routes_storage = [None; 1];
let routes = Routes::new(&mut routes_storage[..]);
let device = device::NetPhy::new(&xns);
let device_caps = device.capabilities();
let medium = device.capabilities().medium;
let mut builder = InterfaceBuilder::new(device)
.ip_addrs([IpCidr::new(IpAddress::v4(0, 0, 0, 0), 24,)])
.routes(routes);
if medium == Medium::Ethernet {
builder = builder
.ethernet_addr(EthernetAddress::from_bytes(&[0; 6]))
.neighbor_cache(neighbor_cache);
}
let mut iface = builder.finalize();
log::trace!("ready to accept requests");
// register a suspend/resume listener
let sr_cid = xous::connect(net_sid).expect("couldn't create suspend callback connection");
@ -71,16 +167,122 @@ fn xmain() -> ! {
log::warn!("Battery is critical! TODO: go into SHIP mode");
},
ComIntSources::WlanIpConfigUpdate => {
net_config = com.wlan_get_config().unwrap();
log::info!("Network config updated: {:?}", net_config);
let config = com.wlan_get_config().unwrap();
net_config = Some(config);
log::info!("Network config updated: {:?}", config);
let mac = EthernetAddress::from_bytes(&config.mac);
iface.set_ethernet_addr(mac);
let ip_addr =
Ipv4Cidr::new(Ipv4Address::new(
config.addr[0],
config.addr[1],
config.addr[2],
config.addr[3],
), 24);
set_ipv4_addr(&mut iface, ip_addr);
let default_v4_gw = Ipv4Address::new(
config.gtwy[0],
config.gtwy[1],
config.gtwy[2],
config.gtwy[3],
);
iface.routes_mut().remove_default_ipv4_route();
iface.routes_mut().add_default_ipv4_route(default_v4_gw).unwrap();
},
ComIntSources::WlanRxReady => {
if let Some(rxlen) = maybe_rxlen {
incoming_pkt = &mut incoming_pkt_buf[0..rxlen as usize];
com.wlan_fetch_packet(incoming_pkt).unwrap();
log::info!("Rx: {:x?}", incoming_pkt);
} else {
log::error!("Got RxReady interrupt but no packet length specified!");
if let Some(_config) = net_config {
if let Some(rxlen) = maybe_rxlen {
match iface.device_mut().push_rx_avail(rxlen) {
None => {},
Some(_) => log::warn!("Got more packets, but smoltcp didn't receive them"),
}
// now fire off the smoltcp receive machine....
{
let timestamp = Instant::now();
match iface.poll(&mut sockets, timestamp) {
Ok(_) => {}
Err(e) => {
log::debug!("poll error: {}", e);
}
}
{
let timestamp = Instant::now();
let mut socket = sockets.get::<IcmpSocket>(icmp_handle);
if !socket.is_open() {
socket.bind(IcmpEndpoint::Ident(ident)).unwrap();
send_at = timestamp;
}
if socket.can_send() && seq_no < count as u16 && send_at <= timestamp {
NetworkEndian::write_i64(&mut echo_payload, timestamp.total_millis());
match ping_remote_addr {
IpAddress::Ipv4(_) => {
let (icmp_repr, mut icmp_packet) = send_icmp_ping!(
Icmpv4Repr,
Icmpv4Packet,
ident,
seq_no,
echo_payload,
socket,
ping_remote_addr
);
icmp_repr.emit(&mut icmp_packet, &device_caps.checksum);
}
_ => unimplemented!(),
}
waiting_queue.insert(seq_no, timestamp);
seq_no += 1;
send_at += interval;
}
if socket.can_recv() {
let (payload, _) = socket.recv().unwrap();
match ping_remote_addr {
IpAddress::Ipv4(_) => {
let icmp_packet = Icmpv4Packet::new_checked(&payload).unwrap();
let icmp_repr =
Icmpv4Repr::parse(&icmp_packet, &device_caps.checksum).unwrap();
get_icmp_pong!(
Icmpv4Repr,
icmp_repr,
payload,
waiting_queue,
ping_remote_addr,
timestamp,
received
);
}
_ => unimplemented!(),
}
}
waiting_queue.retain(|seq, from| {
if timestamp - *from < timeout {
true
} else {
log::info!("From {} icmp_seq={} timeout", ping_remote_addr, seq);
false
}
});
if seq_no == count as u16 && waiting_queue.is_empty() {
break;
}
}
}
/*
incoming_pkt = &mut incoming_pkt_buf[0..rxlen as usize];
com.wlan_fetch_packet(incoming_pkt).unwrap();
log::info!("Rx: {:x?}", incoming_pkt);*/
} else {
log::error!("Got RxReady interrupt but no packet length specified!");
}
}
},
ComIntSources::WlanSsidScanDone => {