diff --git a/embassy-net-adin1110/Cargo.toml b/embassy-net-adin1110/Cargo.toml index 028e8a72f4d..771df1e957a 100644 --- a/embassy-net-adin1110/Cargo.toml +++ b/embassy-net-adin1110/Cargo.toml @@ -20,7 +20,7 @@ embassy-net-driver-channel = { version = "0.4.0", path = "../embassy-net-driver- embassy-time = { version = "0.5.1", path = "../embassy-time" } embassy-futures = { version = "0.1.2", path = "../embassy-futures" } bitfield = "0.14.0" -xarxa-driver = { git = "https://github.com/embassy-rs/xarxa", rev = "93228f1ec64720122016be52be4671e413fa92a9", optional = true, features = ["async"] } +xarxa-driver = { git = "https://github.com/embassy-rs/xarxa", rev = "8f6f33b131deb9ff3290e0e01079537e1ed7b2ad", optional = true, features = ["async"] } [dev-dependencies] embedded-hal-mock = { version = "0.10.0", features = ["embedded-hal-async", "eh1"] } @@ -28,7 +28,7 @@ crc = "3.0.1" env_logger = "0.10" critical-section = { version = "1.1.2", features = ["std"] } futures-test = "0.3.28" -xarxa = { git = "https://github.com/embassy-rs/xarxa", rev = "93228f1ec64720122016be52be4671e413fa92a9" } +xarxa = { git = "https://github.com/embassy-rs/xarxa", rev = "8f6f33b131deb9ff3290e0e01079537e1ed7b2ad" } [features] default = ["generic-spi"] diff --git a/embassy-net-driver-channel/Cargo.toml b/embassy-net-driver-channel/Cargo.toml index 1a849f36042..28e2d854b03 100644 --- a/embassy-net-driver-channel/Cargo.toml +++ b/embassy-net-driver-channel/Cargo.toml @@ -27,7 +27,7 @@ log = { version = "0.4.14", optional = true } embassy-sync = { version = "0.8.0", path = "../embassy-sync" } embassy-futures = { version = "0.1.2", path = "../embassy-futures" } -xarxa-driver = { git = "https://github.com/embassy-rs/xarxa", rev = "93228f1ec64720122016be52be4671e413fa92a9", features = ["async"] } +xarxa-driver = { git = "https://github.com/embassy-rs/xarxa", rev = "8f6f33b131deb9ff3290e0e01079537e1ed7b2ad", features = ["async"] } [features] defmt = ["dep:defmt", "xarxa-driver/defmt"] diff --git a/embassy-net-enc28j60/Cargo.toml b/embassy-net-enc28j60/Cargo.toml index f2f75ad6872..1f9f9fe6732 100644 --- a/embassy-net-enc28j60/Cargo.toml +++ b/embassy-net-enc28j60/Cargo.toml @@ -12,7 +12,7 @@ documentation = "https://docs.embassy.dev/embassy-net-enc28j60" [dependencies] embedded-hal = { version = "1.0" } embedded-hal-async = { version = "1.0" } -xarxa-driver = { git = "https://github.com/embassy-rs/xarxa", rev = "93228f1ec64720122016be52be4671e413fa92a9", features = ["async"] } +xarxa-driver = { git = "https://github.com/embassy-rs/xarxa", rev = "8f6f33b131deb9ff3290e0e01079537e1ed7b2ad", features = ["async"] } embassy-time = { version = "0.5.1", path = "../embassy-time" } embassy-futures = { version = "0.1.2", path = "../embassy-futures" } diff --git a/embassy-net-tuntap/Cargo.toml b/embassy-net-tuntap/Cargo.toml index 020b958c85d..2b935ed25fe 100644 --- a/embassy-net-tuntap/Cargo.toml +++ b/embassy-net-tuntap/Cargo.toml @@ -10,7 +10,7 @@ repository = "https://github.com/embassy-rs/embassy" documentation = "https://docs.embassy.dev/embassy-net-tuntap" [dependencies] -xarxa-driver = { git = "https://github.com/embassy-rs/xarxa", rev = "93228f1ec64720122016be52be4671e413fa92a9", features = ["async"] } +xarxa-driver = { git = "https://github.com/embassy-rs/xarxa", rev = "8f6f33b131deb9ff3290e0e01079537e1ed7b2ad", features = ["async"] } async-io = "2.6.0" log = "0.4.14" libc = "0.2.101" diff --git a/embassy-net/Cargo.toml b/embassy-net/Cargo.toml index e27fb0c4783..b2e76a04c48 100644 --- a/embassy-net/Cargo.toml +++ b/embassy-net/Cargo.toml @@ -145,8 +145,8 @@ packet-log = ["xarxa/packet-log"] defmt = { version = "1.0.1", optional = true } log = { version = "0.4.14", optional = true } -xarxa = { git = "https://github.com/embassy-rs/xarxa", rev = "93228f1ec64720122016be52be4671e413fa92a9", default-features = false, features = ["async"] } -xarxa-driver = { git = "https://github.com/embassy-rs/xarxa", rev = "93228f1ec64720122016be52be4671e413fa92a9", default-features = false, features = ["async"] } +xarxa = { git = "https://github.com/embassy-rs/xarxa", rev = "8f6f33b131deb9ff3290e0e01079537e1ed7b2ad", default-features = false, features = ["async"] } +xarxa-driver = { git = "https://github.com/embassy-rs/xarxa", rev = "8f6f33b131deb9ff3290e0e01079537e1ed7b2ad", default-features = false, features = ["async"] } embassy-time = { version = "0.5.1", path = "../embassy-time" } embassy-futures = { version = "0.1.2", path = "../embassy-futures" } embassy-sync = { version = "0.8.0", path = "../embassy-sync" } diff --git a/embassy-net/src/raw.rs b/embassy-net/src/raw.rs index c5e99bbd1bf..74acb0a5ab5 100644 --- a/embassy-net/src/raw.rs +++ b/embassy-net/src/raw.rs @@ -25,7 +25,7 @@ pub use xarxa::wire::EthernetProtocol; pub use xarxa::wire::{IpProtocol, IpVersion}; use crate::error::Full; -use crate::{NoWake, Stack, TryError, Wake, WakeRunner, wake_if}; +use crate::{NoWake, Stack, TryError, Wake, WakeRunner, wake_if, wake_if_ok}; /// Error returned by [`RawSocket::bind`]. #[derive(PartialEq, Eq, Clone, Copy, Debug)] @@ -417,20 +417,38 @@ impl<'d> RawSocket<'d> { }) } - /// Make one send attempt with `f`, without waiting. Like - /// [`poll_send`](Self::poll_send), only a packet that went out wakes the runner. - fn try_send_inner( - &self, - f: impl FnOnce(&mut raw::RawSocket<'_, 'd>) -> Result, - ) -> Result> { - self.with(|s| match f(s) { - Ok(r) => (Ok(r), Wake), - Err(raw::SendError::DeviceBusy | raw::SendError::NoBuffer) => (Err(TryError::WouldBlock), NoWake), - Err(raw::SendError::BufferFull) => (Err(TryError::Other(SendError::BufferFull)), NoWake), - Err(raw::SendError::InvalidState) => (Err(TryError::Other(SendError::InvalidState)), NoWake), - Err(raw::SendError::Unaddressable) => (Err(TryError::Other(SendError::Unaddressable)), NoWake), - Err(raw::SendError::Malformed) => (Err(TryError::Other(SendError::Malformed)), NoWake), + /// Send an owned packet, preserving its packet metadata. + /// + /// The buffer contains a complete Ethernet frame or IP packet, according to + /// the socket's mode, as in [`send_with`](Self::send_with). Use + /// [`try_alloc`](Self::try_alloc) to allocate a buffer with suitable headroom. + /// + /// Errors also return the buffer unchanged. + /// + /// See [`try_send_packet`](Self::try_send_packet) for errors. + pub async fn send_packet(&self, buf: PacketBuf) -> Result<(), (SendError, PacketBuf)> { + // Each pending attempt restores the packet; success transfers it once. + let mut buf = Some(buf); + poll_fn(|cx| { + self.poll_send(cx, |s| { + s.send_packet(unwrap!(buf.take())).map_err(|(err, packet)| { + buf = Some(packet); + err + }) + }) }) + .await + .map_err(|err| (err, unwrap!(buf))) + } + + /// Try to send an owned packet without waiting or allocating a replacement + /// payload buffer. + /// + /// See [`send_packet`](Self::send_packet) for buffer layout and ownership. + /// Every error returns the buffer unchanged. `WouldBlock` means transmission + /// is temporarily blocked; other errors match [`send_with`](Self::send_with). + pub fn try_send_packet(&self, buf: PacketBuf) -> Result<(), (TryError, PacketBuf)> { + self.with(|s| wake_if_ok(s.send_packet(buf).map_err(|(err, buf)| (err.into(), buf)))) } /// Send a packet, copying it from a slice. @@ -464,7 +482,7 @@ impl<'d> RawSocket<'d> { /// - `WouldBlock`: if every packet buffer is in use, or the interface the /// packet would go out of has no room for it right now. pub fn try_send(&self, buf: &[u8]) -> Result<(), TryError> { - self.try_send_inner(|s| s.send_slice(buf)) + self.with(|s| wake_if_ok(s.send_slice(buf).map_err(Into::into))) } /// Send a packet with the given [`PacketMeta`] attached, copying it from a slice. @@ -523,19 +541,28 @@ impl<'d> RawSocket<'d> { max_size: usize, f: impl FnOnce(&mut [u8]) -> (usize, R), ) -> Result { - let mut f = Some(f); - poll_fn(move |cx| { - self.poll_send(cx, |s| { - let mut ret = None; - s.send_with(max_size, |buf| { - let (size, r) = unwrap!(f.take())(buf); - ret = Some(r); - size - }) - .map(|()| unwrap!(ret)) - }) + if !self.is_open() { + return Err(SendError::InvalidState); + } + let mut buf = poll_fn(|cx| match self.try_alloc() { + Some(buf) => Poll::Ready(buf), + None => { + // Yield to let other tasks release buffers. + cx.waker().wake_by_ref(); + Poll::Pending + } }) - .await + .await; + if max_size > buf.tailroom() { + return Err(SendError::BufferFull); + } + buf.set_len(max_size); + let (size, ret) = f(&mut buf); + assert!(size <= max_size); + buf.set_len(size); + + self.send_packet(buf).await.map_err(|(err, _)| err)?; + Ok(ret) } /// Check whether the socket is open (bound to a mode). @@ -556,6 +583,14 @@ impl<'d> RawSocket<'d> { ((), wake_if(freed)) }) } + + /// Allocate an empty packet buffer with headroom for this socket. + /// + /// Allocation works before binding. Returns `None` if every packet buffer + /// is in use. Set the payload length with [`PacketBuf::set_len`] before writing. + pub fn try_alloc(&self) -> Option { + self.with(|s| (s.alloc(), NoWake)) + } } impl Drop for RawSocket<'_> { @@ -568,6 +603,18 @@ impl Drop for RawSocket<'_> { } } +impl From for TryError { + fn from(err: raw::SendError) -> TryError { + match err { + raw::SendError::DeviceBusy | raw::SendError::NoBuffer => TryError::WouldBlock, + raw::SendError::BufferFull => TryError::Other(SendError::BufferFull), + raw::SendError::InvalidState => TryError::Other(SendError::InvalidState), + raw::SendError::Unaddressable => TryError::Other(SendError::Unaddressable), + raw::SendError::Malformed => TryError::Other(SendError::Malformed), + } + } +} + impl core::fmt::Display for SendError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { diff --git a/embassy-net/src/udp.rs b/embassy-net/src/udp.rs index 55c080fd7f1..5621359221f 100644 --- a/embassy-net/src/udp.rs +++ b/embassy-net/src/udp.rs @@ -9,6 +9,7 @@ use core::future::{Future, poll_fn}; use core::task::{Context, Poll}; +use xarxa::driver::PacketBuf; pub use xarxa::driver::PacketMeta; use xarxa::error::InvalidHopLimit; #[cfg(feature = "iface-bind")] @@ -19,7 +20,7 @@ use xarxa::wire::ListenSocketAddr; use crate::error::Full; use crate::wire::SocketAddr; -use crate::{NoWake, Stack, TryError, Wake, WakeRunner, wake_if}; +use crate::{NoWake, Stack, TryError, Wake, WakeRunner, wake_if, wake_if_ok}; /// Error returned by [`UdpSocket::bind`]. #[derive(PartialEq, Eq, Clone, Copy, Debug)] @@ -545,13 +546,50 @@ impl<'d> UdpSocket<'d> { &self, f: impl FnOnce(&mut udp::UdpSocket<'_, 'd>) -> Result, ) -> Result> { - self.with(|s| match f(s) { - Ok(r) => (Ok(r), Wake), - Err(udp::SendError::DeviceBusy | udp::SendError::NoBuffer) => (Err(TryError::WouldBlock), NoWake), - Err(udp::SendError::BufferFull) => (Err(TryError::Other(SendError::BufferFull)), NoWake), - Err(udp::SendError::InvalidState) => (Err(TryError::Other(SendError::InvalidState)), NoWake), - Err(udp::SendError::Unaddressable) => (Err(TryError::Other(SendError::Unaddressable)), NoWake), + self.with(|s| wake_if_ok(f(s).map_err(Into::into))) + } + + /// Send an owned UDP payload, adding the UDP, IP, and link headers. + /// + /// The buffer contains only the payload, without a UDP header. Use + /// [`try_alloc`](Self::try_alloc) to allocate a buffer with suitable headroom. + /// `remote` selects addresses and replaces the buffer's packet metadata, + /// as in [`send_to_with`](Self::send_to_with). + /// + /// Errors also return the buffer unchanged. + pub async fn send_packet_to( + &self, + buf: PacketBuf, + remote: impl Into, + ) -> Result<(), (SendError, PacketBuf)> { + let remote = remote.into(); + // Each pending attempt restores the packet; success transfers it once. + let mut buf = Some(buf); + poll_fn(|cx| { + self.poll_send(cx, |s| { + s.send_packet(unwrap!(buf.take()), remote).map_err(|(err, packet)| { + buf = Some(packet); + err + }) + }) }) + .await + .map_err(|err| (err, unwrap!(buf))) + } + + /// Try to send an owned packet without waiting or allocating a replacement + /// payload buffer. + /// + /// See [`send_packet_to`](Self::send_packet_to) for buffer layout and ownership. + /// Every error returns the buffer unchanged. `WouldBlock` means transmission + /// is temporarily blocked; other errors match [`try_send_to`](Self::try_send_to). + pub fn try_send_packet_to( + &self, + buf: PacketBuf, + remote: impl Into, + ) -> Result<(), (TryError, PacketBuf)> { + let remote = remote.into(); + self.with(|s| wake_if_ok(s.send_packet(buf, remote).map_err(|(err, buf)| (err.into(), buf)))) } /// Send a datagram to the given remote address, copying the payload from a slice. @@ -648,14 +686,15 @@ impl<'d> UdpSocket<'d> { pub async fn send_to_with( &mut self, max_size: usize, - remote: impl Into + Copy, + remote: impl Into, f: impl FnOnce(&mut [u8]) -> (usize, R), ) -> Result { + let remote = remote.into(); let mut f = Some(f); poll_fn(move |cx| { self.poll_send(cx, |s| { let mut ret = None; - s.send_with(max_size, remote.into(), |buf| { + s.send_with(max_size, remote, |buf| { let (size, r) = unwrap!(f.take())(buf); ret = Some(r); size @@ -770,6 +809,14 @@ impl<'d> UdpSocket<'d> { pub fn set_hop_limit(&mut self, hop_limit: Option) -> Result<(), InvalidHopLimit> { self.with(|s| (s.set_hop_limit(hop_limit), NoWake)) } + + /// Allocate an empty UDP payload buffer with headroom for the headers. + /// + /// Allocation works before binding. Returns `None` if every packet buffer + /// is in use. Set the payload length with [`PacketBuf::set_len`] before writing. + pub fn try_alloc(&self) -> Option { + self.with(|s| (s.alloc(), NoWake)) + } } impl Drop for UdpSocket<'_> { @@ -782,6 +829,17 @@ impl Drop for UdpSocket<'_> { } } +impl From for TryError { + fn from(err: udp::SendError) -> TryError { + match err { + udp::SendError::DeviceBusy | udp::SendError::NoBuffer => TryError::WouldBlock, + udp::SendError::BufferFull => TryError::Other(SendError::BufferFull), + udp::SendError::InvalidState => TryError::Other(SendError::InvalidState), + udp::SendError::Unaddressable => TryError::Other(SendError::Unaddressable), + } + } +} + impl core::fmt::Display for SendError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { diff --git a/embassy-stm32-wpan/Cargo.toml b/embassy-stm32-wpan/Cargo.toml index df1fb7d0db0..9fbe0e4815e 100644 --- a/embassy-stm32-wpan/Cargo.toml +++ b/embassy-stm32-wpan/Cargo.toml @@ -37,7 +37,7 @@ embassy-embedded-hal = { version = "0.6.0", path = "../embassy-embedded-hal" } embassy-net-driver-channel = { version = "0.4.0", path = "../embassy-net-driver-channel", optional=true} stm32-bindings = { version = "0.3.1", optional=true, default-features = false } -xarxa = { git = "https://github.com/embassy-rs/xarxa", rev = "93228f1ec64720122016be52be4671e413fa92a9", optional = true, default-features = false } +xarxa = { git = "https://github.com/embassy-rs/xarxa", rev = "8f6f33b131deb9ff3290e0e01079537e1ed7b2ad", optional = true, default-features = false } defmt = { version = "1.0.1", optional = true } log = { version = "0.4.17", optional = true } diff --git a/embassy-stm32/Cargo.toml b/embassy-stm32/Cargo.toml index 1c1bbde91a6..04f1982ec05 100644 --- a/embassy-stm32/Cargo.toml +++ b/embassy-stm32/Cargo.toml @@ -163,7 +163,7 @@ embassy-time-queue-utils = { version = "0.3.2", path = "../embassy-time-queue-ut embassy-futures = { version = "0.1.2", path = "../embassy-futures" } embassy-hal-internal = { version = "0.5.0", path = "../embassy-hal-internal", features = ["cortex-m", "prio-bits-4"] } embassy-embedded-hal = { version = "0.6.0", path = "../embassy-embedded-hal", default-features = false } -xarxa-driver = { git = "https://github.com/embassy-rs/xarxa", rev = "93228f1ec64720122016be52be4671e413fa92a9", features = ["async"] } +xarxa-driver = { git = "https://github.com/embassy-rs/xarxa", rev = "8f6f33b131deb9ff3290e0e01079537e1ed7b2ad", features = ["async"] } embassy-crypto = { version = "0.1.0", path = "../embassy-crypto", features = ["large-contexts"] } crypto-bigint = { version = "0.7.5", default-features = false, optional = true } embassy-ptp-driver = { version = "0.1.0", path = "../embassy-ptp-driver", optional = true } diff --git a/tests/stm32/Cargo.toml b/tests/stm32/Cargo.toml index 892730c2520..8c1c8ee7df7 100644 --- a/tests/stm32/Cargo.toml +++ b/tests/stm32/Cargo.toml @@ -139,7 +139,7 @@ embassy-crypto-test = { version = "0.1.0", path = "../../embassy-crypto-test", f embassy-stm32-wpan = { version = "0.1.0", path = "../../embassy-stm32-wpan", optional = true, features = ["defmt"] } embassy-net = { version = "0.9.1", path = "../../embassy-net", features = ["defmt", "tcp", "udp", "dhcpv4", "medium-ethernet"] } perf-client = { path = "../perf-client" } -xarxa = { git = "https://github.com/embassy-rs/xarxa", rev = "93228f1ec64720122016be52be4671e413fa92a9", default-features = false } +xarxa = { git = "https://github.com/embassy-rs/xarxa", rev = "8f6f33b131deb9ff3290e0e01079537e1ed7b2ad", default-features = false } # mcu-crypto-asm = { git = "https://github.com/kokroo/mcu-crypto-asm", rev = "20201d1aa07d525553c73a1280165813ada2b2e4", features = ["embassy-crypto-p256-ecdh", "embassy-crypto-p256-ecdsa", "embassy-crypto-p384-arith", "embassy-crypto-p384-ecdh", "embassy-crypto-p384-ecdsa"], optional = true } embassy-crypto-rustcrypto = { version = "0.1.0", path = "../../embassy-crypto-rustcrypto", features = ["embassy-crypto-p256-ecdh", "embassy-crypto-p256-ecdsa", "embassy-crypto-p384-arith", "embassy-crypto-p384-ecdh", "embassy-crypto-p384-ecdsa"], optional = true } # Same crate, software AES-128-GCM only; a separate instance (via a shim