update smoltcp to 0.8.0

the refactor changes the way sockets are handled, so now, when
the interface is rebound we are certain to get panics.

working on resolving this detail now, but at least the interface
is working now and it seems more stable than before.
This commit is contained in:
bunnie 2022-05-12 09:27:51 +08:00
parent fd500927d3
commit cc7e7f97c7
6 changed files with 147 additions and 110 deletions

View file

@ -149,6 +149,8 @@ for examples of idiomatic ways to write code for Xous.
- PR #149: index support for modals. Lists can be submitted as a `Vec` now, with an array index returned as the selection result. Thanks to nworbnhoj for the PR. - PR #149: index support for modals. Lists can be submitted as a `Vec` now, with an array index returned as the selection result. Thanks to nworbnhoj for the PR.
- PR #150 & #153: QR codes can now display a separate QR code from the actual text in the box via a Some/None specifier. Thanks to nworbnhoj for the PR & refinements. - PR #150 & #153: QR codes can now display a separate QR code from the actual text in the box via a Some/None specifier. Thanks to nworbnhoj for the PR & refinements.
- PR #151: message forwarding standardized as part of the messaging API. See https://betrusted.io/xous-book/ch07-07-forwarding.html - PR #151: message forwarding standardized as part of the messaging API. See https://betrusted.io/xous-book/ch07-07-forwarding.html
- fixed locking bug in dlmalloc (stdlib version 1.60.0.7)
- update smoltcp to 0.8.0 + latest commits (lates commits necessary as 0.8.0 base includes a rand_core reference that doesn't compile)
## Roadmap to 1.0 ## Roadmap to 1.0

View file

@ -35,7 +35,8 @@ pddb = {path = "../pddb"}
# with Xous in the commit after this -- we need to look into this and maybe send a PR so we can try to work with # with Xous in the commit after this -- we need to look into this and maybe send a PR so we can try to work with
# the latest smoltcp. But later...let's just get things even working first with what we have. # the latest smoltcp. But later...let's just get things even working first with what we have.
git = "https://github.com/smoltcp-rs/smoltcp.git" git = "https://github.com/smoltcp-rs/smoltcp.git"
rev = "35e833e33dfd3e4efc3eb7d5de06bec17c54b011" # rev = "35e833e33dfd3e4efc3eb7d5de06bec17c54b011"
rev = "007f8dd2e2d0a770609428aa4b0efb63f5dbb708"
#path = "../../../smoltcp" #path = "../../../smoltcp"
#features = ["verbose"] #features = ["verbose"]
#version = "0.7.5" #version = "0.7.5"

View file

@ -26,21 +26,24 @@ use xous_ipc::Buffer;
use byteorder::{ByteOrder, NetworkEndian}; use byteorder::{ByteOrder, NetworkEndian};
use smoltcp::iface::{Interface, InterfaceBuilder, NeighborCache, Routes}; use smoltcp::iface::{Interface, InterfaceBuilder, NeighborCache, Routes};
use smoltcp::phy::{Device, Medium}; use smoltcp::phy::{Device, Medium};
use smoltcp::socket::{IcmpEndpoint, IcmpPacketMetadata, IcmpSocket, IcmpSocketBuffer, SocketSet}; use smoltcp::socket::{IcmpEndpoint, IcmpPacketMetadata, IcmpSocket, IcmpSocketBuffer};
use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr, Ipv4Address, Ipv4Cidr, IpEndpoint}; use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr, Ipv4Address, Ipv4Cidr, IpEndpoint};
use smoltcp::wire::{Icmpv4Packet, Icmpv4Repr, Icmpv6Packet, Icmpv6Repr}; use smoltcp::wire::{Icmpv4Packet, Icmpv4Repr, Icmpv6Packet, Icmpv6Repr};
use crate::device::NetPhy;
use core::num::NonZeroU64; use core::num::NonZeroU64;
use core::sync::atomic::{AtomicU32, Ordering}; use core::sync::atomic::{AtomicU32, Ordering};
use smoltcp::socket::{ use smoltcp::socket::{
SocketHandle, TcpSocket, TcpSocketBuffer, UdpPacketMetadata, UdpSocket, UdpSocketBuffer, TcpSocket, TcpSocketBuffer, UdpPacketMetadata, UdpSocket, UdpSocketBuffer,
}; };
use smoltcp::iface::SocketHandle;
use smoltcp::time::{Duration, Instant}; use smoltcp::time::{Duration, Instant};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::thread; use std::thread;
const PING_DEFAULT_TIMEOUT_MS: u32 = 10_000; const PING_DEFAULT_TIMEOUT_MS: u32 = 10_000;
const MAX_DELAY_THREADS: u32 = 16; // limit the number of concurrent delay threads. Typically we have 1-2 running at any time, but DoS conditions could lead to many more. const MAX_DELAY_THREADS: u32 = 16; // limit the number of concurrent delay threads. Typically we have 1-2 running at any time, but DoS conditions could lead to many more.
const PING_IDENT: u16 = 0x22b;
fn set_ipv4_addr<DeviceT>(iface: &mut Interface<'_, DeviceT>, cidr: Ipv4Cidr) fn set_ipv4_addr<DeviceT>(iface: &mut Interface<'_, DeviceT>, cidr: Ipv4Cidr)
where where
@ -112,6 +115,38 @@ fn set_com_ints(com_int_list: &mut Vec<ComIntSources>) {
com_int_list.push(ComIntSources::WfxErr); com_int_list.push(ComIntSources::WfxErr);
} }
fn setup_icmp(iface: &mut Interface::<NetPhy>) -> SocketHandle {
// ping storage
// up to four concurrent pings in the queue
let icmp_rx_buffer = IcmpSocketBuffer::new(
vec![
IcmpPacketMetadata::EMPTY,
IcmpPacketMetadata::EMPTY,
IcmpPacketMetadata::EMPTY,
IcmpPacketMetadata::EMPTY,
],
vec![0; 1024],
);
let icmp_tx_buffer = IcmpSocketBuffer::new(
vec![
IcmpPacketMetadata::EMPTY,
IcmpPacketMetadata::EMPTY,
IcmpPacketMetadata::EMPTY,
IcmpPacketMetadata::EMPTY,
],
vec![0; 1024],
);
let icmp_socket = IcmpSocket::new(icmp_rx_buffer, icmp_tx_buffer);
let icmp_handle = iface.add_socket(icmp_socket);
{
let icmp_socket = iface.get_socket::<IcmpSocket>(icmp_handle);
icmp_socket
.bind(IcmpEndpoint::Ident(PING_IDENT))
.expect("couldn't bind to icmp socket");
}
icmp_handle
}
#[xous::xous_main] #[xous::xous_main]
fn xmain() -> ! { fn xmain() -> ! {
log_server::init_wait().unwrap(); log_server::init_wait().unwrap();
@ -150,9 +185,6 @@ fn xmain() -> ! {
let delay_threads = Arc::new(AtomicU32::new(0)); let delay_threads = Arc::new(AtomicU32::new(0));
let mut net_config: Option<Ipv4Conf> = None; let mut net_config: Option<Ipv4Conf> = None;
// storage for all our sockets
let mut sockets = SocketSet::new(vec![]);
// ------------- libstd variant ----------- // ------------- libstd variant -----------
// Each process keeps track of its own sockets. These are kept in a Vec. When a handle // Each process keeps track of its own sockets. These are kept in a Vec. When a handle
// is destroyed, it is turned into a `None`. // is destroyed, it is turned into a `None`.
@ -185,39 +217,7 @@ fn xmain() -> ! {
// incoming UDP socket data. // incoming UDP socket data.
let mut udp_rx_waiting: Vec<Option<UdpStdState>> = Vec::new(); let mut udp_rx_waiting: Vec<Option<UdpStdState>> = Vec::new();
// ------------- native variant ----------- // --------------- other link storage -------------
// ping storage
// up to four concurrent pings in the queue
let icmp_rx_buffer = IcmpSocketBuffer::new(
vec![
IcmpPacketMetadata::EMPTY,
IcmpPacketMetadata::EMPTY,
IcmpPacketMetadata::EMPTY,
IcmpPacketMetadata::EMPTY,
],
vec![0; 1024],
);
let icmp_tx_buffer = IcmpSocketBuffer::new(
vec![
IcmpPacketMetadata::EMPTY,
IcmpPacketMetadata::EMPTY,
IcmpPacketMetadata::EMPTY,
IcmpPacketMetadata::EMPTY,
],
vec![0; 1024],
);
let mut icmp_socket = IcmpSocket::new(icmp_rx_buffer, icmp_tx_buffer);
let ident = 0x22b;
icmp_socket
.bind(IcmpEndpoint::Ident(ident))
.expect("couldn't bind to icmp socket");
let icmp_handle = sockets.add(icmp_socket);
let mut seq: u16 = 0;
// this record stores the origin time + IP address of the outgoing ping sequence number
let mut ping_destinations = HashMap::<PingConnection, HashMap<u16, u64>>::new();
let mut ping_timeout_ms = PING_DEFAULT_TIMEOUT_MS;
// other link storage
let neighbor_cache = NeighborCache::new(BTreeMap::new()); let neighbor_cache = NeighborCache::new(BTreeMap::new());
let ip_addrs = [IpCidr::new(Ipv4Address::UNSPECIFIED.into(), 0)]; let ip_addrs = [IpCidr::new(Ipv4Address::UNSPECIFIED.into(), 0)];
let routes = Routes::new(BTreeMap::new()); let routes = Routes::new(BTreeMap::new());
@ -226,16 +226,23 @@ fn xmain() -> ! {
// needed by ICMP to determine if we should compute checksums // needed by ICMP to determine if we should compute checksums
let device_caps = device.capabilities(); let device_caps = device.capabilities();
let medium = device.capabilities().medium; let medium = device.capabilities().medium;
let mut builder = InterfaceBuilder::new(device) let mut builder = InterfaceBuilder::new(device, vec![])
.ip_addrs(ip_addrs) .ip_addrs(ip_addrs)
.routes(routes); .routes(routes);
if medium == Medium::Ethernet { if medium == Medium::Ethernet {
builder = builder builder = builder
.ethernet_addr(EthernetAddress::from_bytes(&[0; 6])) .hardware_addr(EthernetAddress::from_bytes(&[0; 6]).into())
.neighbor_cache(neighbor_cache); .neighbor_cache(neighbor_cache);
} }
let mut iface = builder.finalize(); let mut iface = builder.finalize();
// ------------- native variant -----------
let mut icmp_handle = setup_icmp(&mut iface);
let mut seq: u16 = 0;
// this record stores the origin time + IP address of the outgoing ping sequence number
let mut ping_destinations = HashMap::<PingConnection, HashMap<u16, u64>>::new();
let mut ping_timeout_ms = PING_DEFAULT_TIMEOUT_MS;
// DNS hooks - the DNS server can ask the Net crate to tickle it when IP configs change using these hooks // DNS hooks - the DNS server can ask the Net crate to tickle it when IP configs change using these hooks
// Currently, we assume there is only one DNS server in Xous. I suppose you could // Currently, we assume there is only one DNS server in Xous. I suppose you could
// upgrade the code to handle multiple DNS servers, but...why??? // upgrade the code to handle multiple DNS servers, but...why???
@ -245,7 +252,7 @@ fn xmain() -> ! {
let mut dns_ipv6_hook = XousScalarEndpoint::new(); let mut dns_ipv6_hook = XousScalarEndpoint::new();
let mut dns_allclear_hook = XousScalarEndpoint::new(); let mut dns_allclear_hook = XousScalarEndpoint::new();
// wakeup polling management // wakeup polling management - this is not reset on connection reset, because the stale timers are still running and there is no way to reset them mid-run
let wakeup_time: Arc::<Mutex::<BTreeSet<u64>>> = Arc::new(Mutex::new(BTreeSet::new())); let wakeup_time: Arc::<Mutex::<BTreeSet<u64>>> = Arc::new(Mutex::new(BTreeSet::new()));
log::trace!("ready to accept requests"); log::trace!("ready to accept requests");
@ -297,7 +304,7 @@ fn xmain() -> ! {
Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())
}; };
let mut pkt = buf.to_original::<NetPingPacket, _>().unwrap(); let mut pkt = buf.to_original::<NetPingPacket, _>().unwrap();
let mut socket = sockets.get::<IcmpSocket>(icmp_handle); let socket = iface.get_socket::<IcmpSocket>(icmp_handle);
if socket.can_send() { if socket.can_send() {
log::trace!("sending ping to {:?}", pkt.endpoint); log::trace!("sending ping to {:?}", pkt.endpoint);
let remote = IpAddress::from(pkt.endpoint); let remote = IpAddress::from(pkt.endpoint);
@ -351,7 +358,7 @@ fn xmain() -> ! {
match remote { match remote {
IpAddress::Ipv4(_) => { IpAddress::Ipv4(_) => {
let icmp_repr = Icmpv4Repr::EchoRequest { let icmp_repr = Icmpv4Repr::EchoRequest {
ident, ident: PING_IDENT,
seq_no: seq, seq_no: seq,
data: &echo_payload, data: &echo_payload,
}; };
@ -363,7 +370,7 @@ fn xmain() -> ! {
// not sure if this is a valid thing to do, to just assign the source some number like this?? // not sure if this is a valid thing to do, to just assign the source some number like this??
let src_ipv6 = IpAddress::v6(0xfdaa, 0, 0, 0, 0, 0, 0, 1); let src_ipv6 = IpAddress::v6(0xfdaa, 0, 0, 0, 0, 0, 0, 1);
let icmp_repr = Icmpv6Repr::EchoRequest { let icmp_repr = Icmpv6Repr::EchoRequest {
ident, ident: PING_IDENT,
seq_no: seq, seq_no: seq,
data: &echo_payload, data: &echo_payload,
}; };
@ -394,11 +401,11 @@ fn xmain() -> ! {
} }
Some(Opcode::PingSetTtl) => msg_scalar_unpack!(msg, ttl, _, _, _, { Some(Opcode::PingSetTtl) => msg_scalar_unpack!(msg, ttl, _, _, _, {
let checked_ttl = if ttl > 255 { 255 as u8 } else { ttl as u8 }; let checked_ttl = if ttl > 255 { 255 as u8 } else { ttl as u8 };
let mut socket = sockets.get::<IcmpSocket>(icmp_handle); let socket = iface.get_socket::<IcmpSocket>(icmp_handle);
socket.set_hop_limit(Some(checked_ttl)); socket.set_hop_limit(Some(checked_ttl));
}), }),
Some(Opcode::PingGetTtl) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { Some(Opcode::PingGetTtl) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let socket = sockets.get::<IcmpSocket>(icmp_handle); let socket = iface.get_socket::<IcmpSocket>(icmp_handle);
let checked_ttl = if let Some(ttl) = socket.hop_limit() { let checked_ttl = if let Some(ttl) = socket.hop_limit() {
ttl ttl
} else { } else {
@ -475,7 +482,7 @@ fn xmain() -> ! {
std_tcp_connect( std_tcp_connect(
msg, msg,
local_port, local_port,
&mut sockets, &mut iface,
&mut tcp_connect_waiting, &mut tcp_connect_waiting,
process_sockets.entry(pid).or_default(), process_sockets.entry(pid).or_default(),
); );
@ -494,7 +501,7 @@ fn xmain() -> ! {
std_tcp_tx( std_tcp_tx(
msg, msg,
&timer, &timer,
&mut sockets, &mut iface,
&mut tcp_tx_waiting, &mut tcp_tx_waiting,
process_sockets.entry(pid).or_default(), process_sockets.entry(pid).or_default(),
); );
@ -510,7 +517,7 @@ fn xmain() -> ! {
Some(Opcode::StdTcpPeek) => { Some(Opcode::StdTcpPeek) => {
log::debug!("StdTcpPeek"); log::debug!("StdTcpPeek");
let pid = msg.sender.pid(); let pid = msg.sender.pid();
std_tcp_peek(msg, &mut sockets, process_sockets.entry(pid).or_default()); std_tcp_peek(msg, &mut iface, process_sockets.entry(pid).or_default());
xous::try_send_message( xous::try_send_message(
net_conn, net_conn,
Message::new_scalar( Message::new_scalar(
@ -526,7 +533,7 @@ fn xmain() -> ! {
std_tcp_rx( std_tcp_rx(
msg, msg,
&timer, &timer,
&mut sockets, &mut iface,
&mut tcp_rx_waiting, &mut tcp_rx_waiting,
process_sockets.entry(pid).or_default(), process_sockets.entry(pid).or_default(),
); );
@ -558,8 +565,8 @@ fn xmain() -> ! {
respond_with_error(msg, NetError::Invalid); respond_with_error(msg, NetError::Invalid);
continue; continue;
}; };
sockets.get::<TcpSocket>(handle).close(); iface.get_socket::<TcpSocket>(handle).close();
sockets.remove(handle); iface.remove_socket(handle);
if let Some(response) = msg.body.memory_message_mut() { if let Some(response) = msg.body.memory_message_mut() {
response.buf.as_slice_mut::<u8>()[0] = 0; response.buf.as_slice_mut::<u8>()[0] = 0;
} else if !msg.body.has_memory() && msg.body.is_blocking() { } else if !msg.body.has_memory() && msg.body.is_blocking() {
@ -669,7 +676,7 @@ fn xmain() -> ! {
std_tcp_listen( std_tcp_listen(
msg, msg,
&mut sockets, &mut iface,
process_sockets.entry(pid).or_default(), process_sockets.entry(pid).or_default(),
); );
xous::try_send_message( xous::try_send_message(
@ -686,7 +693,7 @@ fn xmain() -> ! {
std_tcp_accept( std_tcp_accept(
msg, msg,
&mut sockets, &mut iface,
&mut tcp_accept_waiting, &mut tcp_accept_waiting,
process_sockets.entry(pid).or_default(), process_sockets.entry(pid).or_default(),
); );
@ -715,7 +722,7 @@ fn xmain() -> ! {
.or_default() .or_default()
.get_mut(connection_idx) .get_mut(connection_idx)
{ {
let socket = sockets.get::<TcpSocket>(*connection); let socket = iface.get_socket::<TcpSocket>(*connection);
body.valid = xous::MemorySize::new( body.valid = xous::MemorySize::new(
write_address(socket.local_endpoint().addr, body.buf.as_slice_mut()) write_address(socket.local_endpoint().addr, body.buf.as_slice_mut())
.unwrap_or_default(), .unwrap_or_default(),
@ -741,10 +748,10 @@ fn xmain() -> ! {
{ {
let args = msg.body.scalar_message().unwrap(); let args = msg.body.scalar_message().unwrap();
let limit = if args.arg4 == 1 { let limit = if args.arg4 == 1 {
let socket = sockets.get::<UdpSocket>(*connection); let socket = iface.get_socket::<UdpSocket>(*connection);
socket.hop_limit().unwrap_or(64) as usize socket.hop_limit().unwrap_or(64) as usize
} else { } else {
let socket = sockets.get::<TcpSocket>(*connection); let socket = iface.get_socket::<TcpSocket>(*connection);
socket.hop_limit().unwrap_or(64) as usize socket.hop_limit().unwrap_or(64) as usize
}; };
xous::return_scalar( xous::return_scalar(
@ -779,10 +786,10 @@ fn xmain() -> ! {
Some(args.arg1 as u8) Some(args.arg1 as u8)
}; };
if args.arg4 == 1 { if args.arg4 == 1 {
let mut socket = sockets.get::<UdpSocket>(*connection); let socket = iface.get_socket::<UdpSocket>(*connection);
socket.set_hop_limit(hop_limit); socket.set_hop_limit(hop_limit);
} else { } else {
let mut socket = sockets.get::<TcpSocket>(*connection); let socket = iface.get_socket::<TcpSocket>(*connection);
socket.set_hop_limit(hop_limit); socket.set_hop_limit(hop_limit);
} }
xous::return_scalar(msg.sender, 0).ok(); xous::return_scalar(msg.sender, 0).ok();
@ -806,7 +813,7 @@ fn xmain() -> ! {
.or_default() .or_default()
.get_mut(connection_idx) .get_mut(connection_idx)
{ {
let socket = sockets.get::<TcpSocket>(*connection); let socket = iface.get_socket::<TcpSocket>(*connection);
xous::return_scalar( xous::return_scalar(
msg.sender, msg.sender,
if socket.nagle_enabled().is_some() { if socket.nagle_enabled().is_some() {
@ -835,7 +842,7 @@ fn xmain() -> ! {
.or_default() .or_default()
.get_mut(connection_idx) .get_mut(connection_idx)
{ {
let mut socket = sockets.get::<TcpSocket>(*connection); let socket = iface.get_socket::<TcpSocket>(*connection);
let args = msg.body.scalar_message().unwrap(); let args = msg.body.scalar_message().unwrap();
socket.set_nagle_enabled(args.arg1 != 0); socket.set_nagle_enabled(args.arg1 != 0);
xous::return_scalar(msg.sender, 0).ok(); xous::return_scalar(msg.sender, 0).ok();
@ -848,7 +855,7 @@ fn xmain() -> ! {
let pid = msg.sender.pid(); let pid = msg.sender.pid();
std_udp_bind( std_udp_bind(
msg, msg,
&mut sockets, &mut iface,
process_sockets.entry(pid).or_default(), process_sockets.entry(pid).or_default(),
); );
} }
@ -858,7 +865,7 @@ fn xmain() -> ! {
std_udp_rx( std_udp_rx(
msg, msg,
&timer, &timer,
&mut sockets, &mut iface,
&mut udp_rx_waiting, &mut udp_rx_waiting,
process_sockets.entry(pid).or_default(), process_sockets.entry(pid).or_default(),
); );
@ -868,7 +875,7 @@ fn xmain() -> ! {
let pid = msg.sender.pid(); let pid = msg.sender.pid();
std_udp_tx( std_udp_tx(
msg, msg,
&mut sockets, &mut iface,
process_sockets.entry(pid).or_default(), process_sockets.entry(pid).or_default(),
); );
xous::try_send_message( xous::try_send_message(
@ -899,8 +906,8 @@ fn xmain() -> ! {
std_failure(msg, NetError::Invalid); std_failure(msg, NetError::Invalid);
continue; continue;
}; };
sockets.get::<UdpSocket>(handle).close(); iface.get_socket::<UdpSocket>(handle).close();
sockets.remove(handle); iface.remove_socket(handle);
if let Some(response) = msg.body.memory_message_mut() { if let Some(response) = msg.body.memory_message_mut() {
response.buf.as_slice_mut::<u8>()[0] = 0; response.buf.as_slice_mut::<u8>()[0] = 0;
} else if !msg.body.has_memory() && msg.body.is_blocking() { } else if !msg.body.has_memory() && msg.body.is_blocking() {
@ -966,15 +973,23 @@ fn xmain() -> ! {
let routes = Routes::new(BTreeMap::new()); let routes = Routes::new(BTreeMap::new());
let device = device::NetPhy::new(&xns); let device = device::NetPhy::new(&xns);
let medium = device.capabilities().medium; let medium = device.capabilities().medium;
let mut builder = InterfaceBuilder::new(device) let mut builder = InterfaceBuilder::new(device, vec![])
.ip_addrs(ip_addrs) .ip_addrs(ip_addrs)
.routes(routes); .routes(routes);
if medium == Medium::Ethernet { if medium == Medium::Ethernet {
builder = builder builder = builder
.ethernet_addr(mac) .hardware_addr(mac.into())
.neighbor_cache(neighbor_cache); .neighbor_cache(neighbor_cache);
} }
iface = builder.finalize(); iface = builder.finalize();
// reset all the associated connection state. Maybe consider bunching these into a struct so we don't forget any of them.
icmp_handle = setup_icmp(&mut iface);
process_sockets.clear();
tcp_rx_waiting.clear();
tcp_tx_waiting.clear();
tcp_connect_waiting.clear();
tcp_accept_waiting.clear();
udp_rx_waiting.clear();
let ip_addr = Ipv4Cidr::new( let ip_addr = Ipv4Cidr::new(
Ipv4Address::new( Ipv4Address::new(
@ -1081,7 +1096,7 @@ fn xmain() -> ! {
Some(Opcode::NetPump) => { Some(Opcode::NetPump) => {
let now = timer.elapsed_ms(); let now = timer.elapsed_ms();
let timestamp = Instant::from_millis(now as i64); let timestamp = Instant::from_millis(now as i64);
match iface.poll(&mut sockets, timestamp) { match iface.poll(timestamp) {
Ok(_) => {} Ok(_) => {}
Err(e) => { Err(e) => {
log::debug!("poll error: {}", e); log::debug!("poll error: {}", e);
@ -1090,6 +1105,7 @@ fn xmain() -> ! {
// Connect calls take time to establish. This block checks to see if connections // Connect calls take time to establish. This block checks to see if connections
// have been made and issues callbacks as necessary. // have been made and issues callbacks as necessary.
log::trace!("pump: tcpconnect");
for connection in tcp_connect_waiting.iter_mut() { for connection in tcp_connect_waiting.iter_mut() {
use smoltcp::socket::TcpState; use smoltcp::socket::TcpState;
let socket; let socket;
@ -1099,7 +1115,7 @@ fn xmain() -> ! {
match connection { match connection {
&mut None => continue, &mut None => continue,
Some(s) => { Some(s) => {
socket = sockets.get::<TcpSocket>(s.1); socket = iface.get_socket::<TcpSocket>(s.1);
if socket.state() == TcpState::SynSent if socket.state() == TcpState::SynSent
|| socket.state() == TcpState::SynReceived || socket.state() == TcpState::SynReceived
{ {
@ -1119,8 +1135,9 @@ fn xmain() -> ! {
} }
// This block handles TCP Rx for libstd callers // This block handles TCP Rx for libstd callers
log::trace!("pump: tcp rx");
for connection in tcp_rx_waiting.iter_mut() { for connection in tcp_rx_waiting.iter_mut() {
let mut socket; let socket;
let WaitingSocket { let WaitingSocket {
mut env, mut env,
handle: _, handle: _,
@ -1129,7 +1146,7 @@ fn xmain() -> ! {
match connection { match connection {
&mut None => continue, &mut None => continue,
Some(s) => { Some(s) => {
socket = sockets.get::<TcpSocket>(s.handle); socket = iface.get_socket::<TcpSocket>(s.handle);
if !socket.can_recv() { if !socket.can_recv() {
if let Some(trigger) = s.expiry { if let Some(trigger) = s.expiry {
if trigger.get() < now { if trigger.get() < now {
@ -1167,8 +1184,9 @@ fn xmain() -> ! {
} }
// This block handles TCP Tx for libstd callers // This block handles TCP Tx for libstd callers
log::trace!("pump: tcp tx");
for connection in tcp_tx_waiting.iter_mut() { for connection in tcp_tx_waiting.iter_mut() {
let mut socket; let socket;
let WaitingSocket { let WaitingSocket {
mut env, mut env,
handle: _, handle: _,
@ -1177,7 +1195,7 @@ fn xmain() -> ! {
match connection { match connection {
&mut None => continue, &mut None => continue,
Some(s) => { Some(s) => {
socket = sockets.get::<TcpSocket>(s.handle); socket = iface.get_socket::<TcpSocket>(s.handle);
if !socket.can_send() { if !socket.can_send() {
if let Some(trigger) = s.expiry { if let Some(trigger) = s.expiry {
if trigger.get() < now { if trigger.get() < now {
@ -1231,6 +1249,7 @@ fn xmain() -> ! {
} }
// this handles TCP std listeners // this handles TCP std listeners
log::trace!("pump: tcp listen");
for connection in tcp_accept_waiting.iter_mut() { for connection in tcp_accept_waiting.iter_mut() {
let ep: IpEndpoint; let ep: IpEndpoint;
let AcceptingSocket { let AcceptingSocket {
@ -1240,7 +1259,7 @@ fn xmain() -> ! {
} = match connection { } = match connection {
&mut None => continue, &mut None => continue,
Some(s) => { Some(s) => {
let socket = sockets.get::<TcpSocket>(s.handle); let socket = iface.get_socket::<TcpSocket>(s.handle);
if socket.is_active() { if socket.is_active() {
ep = socket.remote_endpoint(); ep = socket.remote_endpoint();
connection.take().unwrap() connection.take().unwrap()
@ -1256,8 +1275,9 @@ fn xmain() -> ! {
} }
// this block handles StdUdp // this block handles StdUdp
log::trace!("pump: udp");
for connection in udp_rx_waiting.iter_mut() { for connection in udp_rx_waiting.iter_mut() {
let mut socket; let socket;
let UdpStdState { let UdpStdState {
mut msg, mut msg,
handle: _, handle: _,
@ -1266,7 +1286,7 @@ fn xmain() -> ! {
match connection { match connection {
&mut None => continue, &mut None => continue,
Some(s) => { Some(s) => {
socket = sockets.get::<UdpSocket>(s.handle); socket = iface.get_socket::<UdpSocket>(s.handle);
if !socket.can_recv() { if !socket.can_recv() {
if let Some(trigger) = s.expiry { if let Some(trigger) = s.expiry {
if trigger < now { if trigger < now {
@ -1327,8 +1347,9 @@ fn xmain() -> ! {
} }
// this block contains the ICMP Rx handler. Tx is initiated by an incoming message to the Net crate. // this block contains the ICMP Rx handler. Tx is initiated by an incoming message to the Net crate.
log::debug!("pump: icmp");
{ {
let mut socket = sockets.get::<IcmpSocket>(icmp_handle); let socket = iface.get_socket::<IcmpSocket>(icmp_handle);
if !socket.is_open() { if !socket.is_open() {
log::error!("ICMP socket isn't open, something went wrong..."); log::error!("ICMP socket isn't open, something went wrong...");
} }
@ -1507,6 +1528,7 @@ fn xmain() -> ! {
} }
} }
// this block handles ICMP retirement; it runs everytime we pump the block // this block handles ICMP retirement; it runs everytime we pump the block
log::debug!("pump: icmp retirement");
{ {
let now = timer.elapsed_ms(); let now = timer.elapsed_ms();
// notify the callback to drop its connection, because the queue is now empty // notify the callback to drop its connection, because the queue is now empty
@ -1583,10 +1605,11 @@ fn xmain() -> ! {
} }
// establish our next check-up interval // establish our next check-up interval
log::debug!("pump: checkup");
if delay_threads.load(Ordering::SeqCst) < MAX_DELAY_THREADS { if delay_threads.load(Ordering::SeqCst) < MAX_DELAY_THREADS {
let now = timer.elapsed_ms(); let now = timer.elapsed_ms();
let timestamp = Instant::from_millis(now as i64); let timestamp = Instant::from_millis(now as i64);
if let Some(delay) = iface.poll_delay(&sockets, timestamp) { if let Some(delay) = iface.poll_delay(timestamp) {
const RANGE_MS: u64 = 5; const RANGE_MS: u64 = 5;
let wakeup = now + delay.total_millis(); let wakeup = now + delay.total_millis();
let no_wakeup_scheduled = wakeup_time.lock().unwrap().range(wakeup - RANGE_MS..wakeup + RANGE_MS).count() == 0; let no_wakeup_scheduled = wakeup_time.lock().unwrap().range(wakeup - RANGE_MS..wakeup + RANGE_MS).count() == 0;
@ -1717,15 +1740,24 @@ fn xmain() -> ! {
let routes = Routes::new(BTreeMap::new()); let routes = Routes::new(BTreeMap::new());
let device = device::NetPhy::new(&xns); let device = device::NetPhy::new(&xns);
let medium = device.capabilities().medium; let medium = device.capabilities().medium;
let mut builder = InterfaceBuilder::new(device) let mut builder = InterfaceBuilder::new(device, vec![])
.ip_addrs(ip_addrs) .ip_addrs(ip_addrs)
.routes(routes); .routes(routes);
if medium == Medium::Ethernet { if medium == Medium::Ethernet {
builder = builder builder = builder
.ethernet_addr(EthernetAddress::from_bytes(&[0; 6])) .hardware_addr(EthernetAddress::from_bytes(&[0; 6]).into())
.neighbor_cache(neighbor_cache); .neighbor_cache(neighbor_cache);
} }
iface = builder.finalize(); iface = builder.finalize();
// reset all the associated connection state. Maybe consider bunching these into a struct so we don't forget any of them.
icmp_handle = setup_icmp(&mut iface);
process_sockets.clear();
tcp_rx_waiting.clear();
tcp_tx_waiting.clear();
tcp_connect_waiting.clear();
tcp_accept_waiting.clear();
udp_rx_waiting.clear();
iface.routes_mut().remove_default_ipv4_route(); iface.routes_mut().remove_default_ipv4_route();
dns_allclear_hook.notify(); dns_allclear_hook.notify();
// question: do we need to clear the UDP and ICMP states? // question: do we need to clear the UDP and ICMP states?

View file

@ -1,9 +1,10 @@
use crate::*; use crate::*;
use crate::device::NetPhy;
use smoltcp::wire::{IpEndpoint, IpAddress}; use smoltcp::wire::{IpEndpoint, IpAddress};
pub(crate) fn std_tcp_listen( pub(crate) fn std_tcp_listen(
mut msg: xous::MessageEnvelope, mut msg: xous::MessageEnvelope,
sockets: &mut SocketSet, iface: &mut Interface::<NetPhy>,
our_sockets: &mut Vec<Option<SocketHandle>>, our_sockets: &mut Vec<Option<SocketHandle>>,
) { ) {
// Ignore nonblocking and scalar messages // Ignore nonblocking and scalar messages
@ -29,7 +30,9 @@ pub(crate) fn std_tcp_listen(
let tcp_rx_buffer = TcpSocketBuffer::new(vec![0; TCP_BUFFER_SIZE]); let tcp_rx_buffer = TcpSocketBuffer::new(vec![0; TCP_BUFFER_SIZE]);
let tcp_tx_buffer = TcpSocketBuffer::new(vec![0; TCP_BUFFER_SIZE]); let tcp_tx_buffer = TcpSocketBuffer::new(vec![0; TCP_BUFFER_SIZE]);
let mut tcp_socket = TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer); let tcp_socket = TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer);
let handle = iface.add_socket(tcp_socket);
let tcp_socket = iface.get_socket::<TcpSocket>(handle);
if let Err(e) = tcp_socket if let Err(e) = tcp_socket
.listen(local_port) .listen(local_port)
@ -44,8 +47,6 @@ pub(crate) fn std_tcp_listen(
return; return;
} }
let handle = sockets.add(tcp_socket);
// Add the socket into our process' list of sockets, and pass the index back as the `fd` parameter for future reference. // Add the socket into our process' list of sockets, and pass the index back as the `fd` parameter for future reference.
let fd = insert_or_append(our_sockets, handle) as u8; let fd = insert_or_append(our_sockets, handle) as u8;
@ -58,7 +59,7 @@ pub(crate) fn std_tcp_listen(
pub(crate) fn std_tcp_accept( pub(crate) fn std_tcp_accept(
mut msg: xous::MessageEnvelope, mut msg: xous::MessageEnvelope,
sockets: &mut SocketSet, iface: &mut Interface::<NetPhy>,
tcp_accept_waiting: &mut Vec<Option<AcceptingSocket>>, tcp_accept_waiting: &mut Vec<Option<AcceptingSocket>>,
our_sockets: &Vec<Option<SocketHandle>>, our_sockets: &Vec<Option<SocketHandle>>,
) { ) {
@ -85,7 +86,7 @@ pub(crate) fn std_tcp_accept(
let args = body.buf.as_slice::<u8>(); let args = body.buf.as_slice::<u8>();
let nonblocking = args[0] == 0; let nonblocking = args[0] == 0;
let socket = sockets.get::<TcpSocket>(*handle); let socket = iface.get_socket::<TcpSocket>(*handle);
if socket.is_active() { if socket.is_active() {
log::trace!("accept did not block; immediately returning TcpSocket"); log::trace!("accept did not block; immediately returning TcpSocket");

View file

@ -2,18 +2,18 @@ use ticktimer_server::Ticktimer;
use std::convert::TryInto; use std::convert::TryInto;
use smoltcp::socket::SocketSet;
use core::num::NonZeroU64; use core::num::NonZeroU64;
use smoltcp::socket::{ use smoltcp::socket::{
SocketHandle, TcpSocket, TcpSocketBuffer, TcpSocket, TcpSocketBuffer,
}; };
use smoltcp::iface::{Interface, SocketHandle};
use crate::*; use crate::*;
use crate::device::NetPhy;
pub(crate) fn std_tcp_connect( pub(crate) fn std_tcp_connect(
mut msg: xous::MessageEnvelope, mut msg: xous::MessageEnvelope,
local_port: u16, local_port: u16,
sockets: &mut SocketSet, iface: &mut Interface::<NetPhy>,
tcp_connect_waiting: &mut Vec<Option<(xous::MessageEnvelope, SocketHandle, u16, u16, u16)>>, tcp_connect_waiting: &mut Vec<Option<(xous::MessageEnvelope, SocketHandle, u16, u16, u16)>>,
our_sockets: &mut Vec<Option<SocketHandle>>, our_sockets: &mut Vec<Option<SocketHandle>>,
) { ) {
@ -41,14 +41,16 @@ pub(crate) fn std_tcp_connect(
// initiates a new connection to a remote server consisting of an (Address:Port) tuple. // initiates a new connection to a remote server consisting of an (Address:Port) tuple.
// multiple connections can exist to a server, and they are further differentiated by the return port // multiple connections can exist to a server, and they are further differentiated by the return port
let mut tcp_socket = TcpSocket::new( let tcp_socket = TcpSocket::new(
TcpSocketBuffer::new(vec![0; TCP_BUFFER_SIZE]), TcpSocketBuffer::new(vec![0; TCP_BUFFER_SIZE]),
TcpSocketBuffer::new(vec![0; TCP_BUFFER_SIZE]), TcpSocketBuffer::new(vec![0; TCP_BUFFER_SIZE]),
); );
let handle = iface.add_socket(tcp_socket);
let (tcp_socket, cx) = iface.get_socket_and_context::<TcpSocket>(handle);
// Attempt to connect, returning the error if there is one // Attempt to connect, returning the error if there is one
if let Err(e) = tcp_socket if let Err(e) = tcp_socket
.connect((address, remote_port), local_port) .connect(cx, (address, remote_port), local_port)
.map_err(|e| match e { .map_err(|e| match e {
smoltcp::Error::Illegal => NetError::SocketInUse, smoltcp::Error::Illegal => NetError::SocketInUse,
smoltcp::Error::Unaddressable => NetError::Unaddressable, smoltcp::Error::Unaddressable => NetError::Unaddressable,
@ -62,8 +64,6 @@ pub(crate) fn std_tcp_connect(
tcp_socket.set_timeout(timeout_ms.map(|t| Duration::from_millis(t.get()))); tcp_socket.set_timeout(timeout_ms.map(|t| Duration::from_millis(t.get())));
let handle = sockets.add(tcp_socket);
// Add the socket onto the list of sockets waiting to connect, since the connection will // Add the socket onto the list of sockets waiting to connect, since the connection will
// take time. // take time.
let idx = insert_or_append(our_sockets, handle) as u16; let idx = insert_or_append(our_sockets, handle) as u16;
@ -76,7 +76,7 @@ pub(crate) fn std_tcp_connect(
pub(crate) fn std_tcp_tx( pub(crate) fn std_tcp_tx(
mut msg: xous::MessageEnvelope, mut msg: xous::MessageEnvelope,
timer: &Ticktimer, timer: &Ticktimer,
sockets: &mut SocketSet, iface: &mut Interface::<NetPhy>,
tcp_tx_waiting: &mut Vec<Option<WaitingSocket>>, tcp_tx_waiting: &mut Vec<Option<WaitingSocket>>,
our_sockets: &Vec<Option<SocketHandle>>, our_sockets: &Vec<Option<SocketHandle>>,
) { ) {
@ -97,7 +97,7 @@ pub(crate) fn std_tcp_tx(
} }
}; };
let mut socket = sockets.get::<TcpSocket>(*handle); let socket = iface.get_socket::<TcpSocket>(*handle);
if !socket.can_send() { if !socket.can_send() {
log::trace!("tx can't send, will retry"); log::trace!("tx can't send, will retry");
let expiry = body let expiry = body
@ -148,7 +148,7 @@ pub(crate) fn std_tcp_tx(
pub(crate) fn std_tcp_rx( pub(crate) fn std_tcp_rx(
mut msg: xous::MessageEnvelope, mut msg: xous::MessageEnvelope,
timer: &Ticktimer, timer: &Ticktimer,
sockets: &mut SocketSet, iface: &mut Interface::<NetPhy>,
tcp_rx_waiting: &mut Vec<Option<WaitingSocket>>, tcp_rx_waiting: &mut Vec<Option<WaitingSocket>>,
our_sockets: &Vec<Option<SocketHandle>>, our_sockets: &Vec<Option<SocketHandle>>,
) { ) {
@ -172,7 +172,7 @@ pub(crate) fn std_tcp_rx(
} }
}; };
let mut socket = sockets.get::<TcpSocket>(*handle); let socket = iface.get_socket::<TcpSocket>(*handle);
if socket.can_recv() { if socket.can_recv() {
log::trace!("receiving data right away"); log::trace!("receiving data right away");
match socket.recv_slice(body.buf.as_slice_mut()) { match socket.recv_slice(body.buf.as_slice_mut()) {
@ -211,7 +211,7 @@ pub(crate) fn std_tcp_rx(
pub(crate) fn std_tcp_peek( pub(crate) fn std_tcp_peek(
mut msg: xous::MessageEnvelope, mut msg: xous::MessageEnvelope,
sockets: &mut SocketSet, iface: &mut Interface::<NetPhy>,
our_sockets: &Vec<Option<SocketHandle>>, our_sockets: &Vec<Option<SocketHandle>>,
) { ) {
let connection_handle_index = (msg.body.id() >> 16) & 0xffff; let connection_handle_index = (msg.body.id() >> 16) & 0xffff;
@ -234,7 +234,7 @@ pub(crate) fn std_tcp_peek(
} }
}; };
let mut socket = sockets.get::<TcpSocket>(*handle); let socket = iface.get_socket::<TcpSocket>(*handle);
if socket.can_recv() { if socket.can_recv() {
log::trace!("receiving data right away"); log::trace!("receiving data right away");
match socket.peek_slice(body.buf.as_slice_mut()) { match socket.peek_slice(body.buf.as_slice_mut()) {

View file

@ -1,4 +1,5 @@
use crate::*; use crate::*;
use crate::device::NetPhy;
use smoltcp::wire::{IpEndpoint, IpAddress}; use smoltcp::wire::{IpEndpoint, IpAddress};
use ticktimer_server::Ticktimer; use ticktimer_server::Ticktimer;
@ -11,7 +12,7 @@ const BUFLEN: usize = NET_MTU as usize;
pub(crate) fn std_udp_bind( pub(crate) fn std_udp_bind(
mut msg: xous::MessageEnvelope, mut msg: xous::MessageEnvelope,
sockets: &mut SocketSet, iface: &mut Interface::<NetPhy>,
our_sockets: &mut Vec<Option<SocketHandle>>, our_sockets: &mut Vec<Option<SocketHandle>>,
) { ) {
// Ignore nonblocking and scalar messages // Ignore nonblocking and scalar messages
@ -39,7 +40,9 @@ pub(crate) fn std_udp_bind(
UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; BUFLEN]); UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; BUFLEN]);
let udp_tx_buffer = let udp_tx_buffer =
UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; BUFLEN]); UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; BUFLEN]);
let mut udp_socket = UdpSocket::new(udp_rx_buffer, udp_tx_buffer); let udp_socket = UdpSocket::new(udp_rx_buffer, udp_tx_buffer);
let handle = iface.add_socket(udp_socket);
let udp_socket = iface.get_socket::<UdpSocket>(handle);
// Attempt to connect, returning the error if there is one // Attempt to connect, returning the error if there is one
if let Err(e) = udp_socket if let Err(e) = udp_socket
@ -55,8 +58,6 @@ pub(crate) fn std_udp_bind(
return; return;
} }
let handle = sockets.add(udp_socket);
// Add the socket into our process' list of sockets, and pass the index back as the `fd` parameter for future reference. // Add the socket into our process' list of sockets, and pass the index back as the `fd` parameter for future reference.
let idx = insert_or_append(our_sockets, handle) as u8; let idx = insert_or_append(our_sockets, handle) as u8;
@ -70,7 +71,7 @@ pub(crate) fn std_udp_bind(
pub(crate) fn std_udp_rx( pub(crate) fn std_udp_rx(
mut msg: xous::MessageEnvelope, mut msg: xous::MessageEnvelope,
timer: &Ticktimer, timer: &Ticktimer,
sockets: &mut SocketSet, iface: &mut Interface::<NetPhy>,
udp_rx_waiting: &mut Vec<Option<UdpStdState>>, udp_rx_waiting: &mut Vec<Option<UdpStdState>>,
our_sockets: &Vec<Option<SocketHandle>>, our_sockets: &Vec<Option<SocketHandle>>,
) { ) {
@ -108,7 +109,7 @@ pub(crate) fn std_udp_rx(
}; };
let do_peek = body.offset.is_some(); let do_peek = body.offset.is_some();
log::trace!("udp rx from fd {}", connection_handle_index); log::trace!("udp rx from fd {}", connection_handle_index);
let mut socket = sockets.get::<UdpSocket>(*handle); let socket = iface.get_socket::<UdpSocket>(*handle);
if socket.can_recv() { if socket.can_recv() {
log::trace!("receiving data right away"); log::trace!("receiving data right away");
if do_peek { if do_peek {
@ -158,7 +159,7 @@ pub(crate) fn std_udp_rx(
pub(crate) fn std_udp_tx( pub(crate) fn std_udp_tx(
mut msg: xous::MessageEnvelope, mut msg: xous::MessageEnvelope,
sockets: &mut SocketSet, iface: &mut Interface::<NetPhy>,
our_sockets: &Vec<Option<SocketHandle>>, our_sockets: &Vec<Option<SocketHandle>>,
) { ) {
// unpack meta // unpack meta
@ -192,7 +193,7 @@ pub(crate) fn std_udp_tx(
let len = u16::from_le_bytes([bytes[19], bytes[20]]); let len = u16::from_le_bytes([bytes[19], bytes[20]]);
// attempt the tx // attempt the tx
log::debug!("udp tx to fd {} -> {:?}:{} {:?}", connection_handle_index, address, remote_port, &bytes[21..21 + len as usize]); log::debug!("udp tx to fd {} -> {:?}:{} {:?}", connection_handle_index, address, remote_port, &bytes[21..21 + len as usize]);
let mut socket = sockets.get::<UdpSocket>(*handle); let socket = iface.get_socket::<UdpSocket>(*handle);
match socket.send_slice(&bytes[21..21 + len as usize], IpEndpoint::new(address, remote_port)) { match socket.send_slice(&bytes[21..21 + len as usize], IpEndpoint::new(address, remote_port)) {
Ok(_) => { Ok(_) => {
body.buf.as_slice_mut()[0] = 0; body.buf.as_slice_mut()[0] = 0;