Skip to content

Add support for SO_TXTIME #1409

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ compiler_builtins = { version = '0.1.49', optional = true }
# libc backend can be selected via adding `--cfg=rustix_use_libc` to
# `RUSTFLAGS` or enabling the `use-libc` cargo feature.
[target.'cfg(all(not(rustix_use_libc), not(miri), target_os = "linux", any(target_endian = "little", any(target_arch = "s390x", target_arch = "powerpc")), any(target_arch = "arm", all(target_arch = "aarch64", target_pointer_width = "64"), target_arch = "riscv64", all(rustix_use_experimental_asm, target_arch = "powerpc"), all(rustix_use_experimental_asm, target_arch = "powerpc64"), all(rustix_use_experimental_asm, target_arch = "s390x"), all(rustix_use_experimental_asm, target_arch = "mips"), all(rustix_use_experimental_asm, target_arch = "mips32r6"), all(rustix_use_experimental_asm, target_arch = "mips64"), all(rustix_use_experimental_asm, target_arch = "mips64r6"), target_arch = "x86", all(target_arch = "x86_64", target_pointer_width = "64"))))'.dependencies]
linux-raw-sys = { version = "0.9.2", default-features = false, features = ["general", "errno", "ioctl", "no_std", "elf"] }
linux-raw-sys = { version = "0.9.3", default-features = false, features = ["general", "errno", "ioctl", "no_std", "elf"] }
libc_errno = { package = "errno", version = "0.3.10", default-features = false, optional = true }
libc = { version = "0.2.168", default-features = false, optional = true }

Expand Down
33 changes: 33 additions & 0 deletions src/backend/libc/net/sockopt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,13 @@ use crate::net::Protocol;
use crate::net::RawProtocol;
#[cfg(any(linux_kernel, target_os = "fuchsia"))]
use crate::net::SocketAddrV4;
#[cfg(all(target_os = "linux", feature = "time"))]
use crate::net::TxTimeFlags;
use crate::net::{Ipv4Addr, Ipv6Addr, SocketType};
#[cfg(linux_kernel)]
use crate::net::{SocketAddrV6, UCred};
#[cfg(all(target_os = "linux", feature = "time"))]
use crate::time::ClockId;
use crate::utils::as_mut_ptr;
#[cfg(feature = "alloc")]
#[cfg(any(
Expand Down Expand Up @@ -1048,6 +1052,35 @@ pub(crate) fn socket_peercred(fd: BorrowedFd<'_>) -> io::Result<UCred> {
getsockopt(fd, c::SOL_SOCKET, c::SO_PEERCRED)
}

#[cfg(all(target_os = "linux", feature = "time"))]
#[inline]
pub(crate) fn set_txtime(
fd: BorrowedFd<'_>,
clockid: ClockId,
flags: TxTimeFlags,
) -> io::Result<()> {
setsockopt(
fd,
c::SOL_SOCKET,
c::SO_TXTIME,
c::sock_txtime {
clockid: clockid as _,
flags: flags.bits(),
},
)
}

#[cfg(all(target_os = "linux", feature = "time"))]
#[inline]
pub(crate) fn get_txtime(fd: BorrowedFd<'_>) -> io::Result<(ClockId, TxTimeFlags)> {
let txtime: c::sock_txtime = getsockopt(fd, c::SOL_SOCKET, c::SO_TXTIME)?;

Ok((
txtime.clockid.try_into().map_err(|_| io::Errno::RANGE)?,
TxTimeFlags::from_bits(txtime.flags).ok_or(io::Errno::RANGE)?,
))
}

#[cfg(target_os = "linux")]
#[inline]
pub(crate) fn set_xdp_umem_reg(fd: BorrowedFd<'_>, value: XdpUmemReg) -> io::Result<()> {
Expand Down
13 changes: 13 additions & 0 deletions src/backend/linux_raw/c.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,19 @@ pub(crate) use linux_raw_sys::{
},
};

#[cfg(feature = "time")]
pub use linux_raw_sys::general::__kernel_clockid_t as clockid_t;

#[cfg(all(feature = "net", feature = "time"))]
pub use linux_raw_sys::net::{sock_txtime, SCM_TXTIME, SO_TXTIME};

#[cfg(all(feature = "net", feature = "time"))]
pub(crate) const SOF_TXTIME_DEADLINE_MODE: u32 =
linux_raw_sys::net::txtime_flags::SOF_TXTIME_DEADLINE_MODE as _;
#[cfg(all(feature = "net", feature = "time"))]
pub(crate) const SOF_TXTIME_REPORT_ERRORS: u32 =
linux_raw_sys::net::txtime_flags::SOF_TXTIME_REPORT_ERRORS as _;

// Cast away bindgen's `enum` type to make these consistent with the other
// `setsockopt`/`getsockopt` level values.
#[cfg(feature = "net")]
Expand Down
33 changes: 33 additions & 0 deletions src/backend/linux_raw/net/sockopt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,17 @@

use crate::backend::c;
use crate::backend::conv::{by_mut, c_uint, ret, socklen_t};
#[cfg(all(target_os = "linux", feature = "time"))]
use crate::clockid::ClockId;
use crate::fd::BorrowedFd;
#[cfg(feature = "alloc")]
use crate::ffi::CStr;
use crate::io;
use crate::net::sockopt::Timeout;
#[cfg(target_os = "linux")]
use crate::net::xdp::{XdpMmapOffsets, XdpOptionsFlags, XdpRingOffset, XdpStatistics, XdpUmemReg};
#[cfg(all(target_os = "linux", feature = "time"))]
use crate::net::TxTimeFlags;
use crate::net::{
AddressFamily, Ipv4Addr, Ipv6Addr, Protocol, RawProtocol, SocketAddrBuf, SocketAddrV4,
SocketAddrV6, SocketType, UCred,
Expand Down Expand Up @@ -848,6 +852,35 @@ pub(crate) fn socket_peercred(fd: BorrowedFd<'_>) -> io::Result<UCred> {
getsockopt(fd, c::SOL_SOCKET, linux_raw_sys::net::SO_PEERCRED)
}

#[cfg(all(target_os = "linux", feature = "time"))]
#[inline]
pub(crate) fn set_txtime(
fd: BorrowedFd<'_>,
clockid: ClockId,
flags: TxTimeFlags,
) -> io::Result<()> {
setsockopt(
fd,
c::SOL_SOCKET,
c::SO_TXTIME,
c::sock_txtime {
clockid: clockid as _,
flags: flags.bits(),
},
)
}

#[cfg(all(target_os = "linux", feature = "time"))]
#[inline]
pub(crate) fn get_txtime(fd: BorrowedFd<'_>) -> io::Result<(ClockId, TxTimeFlags)> {
let txtime: c::sock_txtime = getsockopt(fd, c::SOL_SOCKET, c::SO_TXTIME)?;

Ok((
txtime.clockid.try_into().map_err(|_| io::Errno::RANGE)?,
TxTimeFlags::from_bits(txtime.flags).ok_or(io::Errno::RANGE)?,
))
}

#[cfg(target_os = "linux")]
#[inline]
pub(crate) fn set_xdp_umem_reg(fd: BorrowedFd<'_>, value: XdpUmemReg) -> io::Result<()> {
Expand Down
61 changes: 61 additions & 0 deletions src/clockid.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::backend::c;
use crate::fd::BorrowedFd;
use crate::io;

/// `CLOCK_*` constants for use with [`clock_gettime`].
///
Expand Down Expand Up @@ -97,6 +98,51 @@ pub enum ClockId {
BoottimeAlarm = bitcast!(c::CLOCK_BOOTTIME_ALARM),
}

#[cfg(not(any(apple, target_os = "wasi")))]
Copy link
Contributor Author

@colinmarc colinmarc Mar 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought this would be straightforward, but it's really not. libc has clockid_t, while linux-raw-sys has __kernel_clockid_t. Some platforms have neither. What's the best way to proceed with this? I need it for get_txtime, since the kernel returns the configured clock.

Nevermind, importing __kernel_clockid_t as clockid_t fixed it.

impl TryFrom<c::clockid_t> for ClockId {
type Error = io::Errno;

fn try_from(value: c::clockid_t) -> Result<Self, Self::Error> {
match value {
c::CLOCK_REALTIME => Ok(ClockId::Realtime),
c::CLOCK_MONOTONIC => Ok(ClockId::Monotonic),
#[cfg(any(freebsdlike, target_os = "openbsd"))]
c::CLOCK_UPTIME => Ok(ClockId::Uptime),
#[cfg(not(any(
solarish,
target_os = "horizon",
target_os = "netbsd",
target_os = "redox",
target_os = "vita"
)))]
c::CLOCK_PROCESS_CPUTIME_ID => Ok(ClockId::ProcessCPUTime),
#[cfg(not(any(
solarish,
target_os = "horizon",
target_os = "netbsd",
target_os = "redox",
target_os = "vita"
)))]
c::CLOCK_THREAD_CPUTIME_ID => Ok(ClockId::ThreadCPUTime),
#[cfg(any(linux_kernel, target_os = "freebsd"))]
c::CLOCK_REALTIME_COARSE => Ok(ClockId::RealtimeCoarse),
#[cfg(any(linux_kernel, target_os = "freebsd"))]
c::CLOCK_MONOTONIC_COARSE => Ok(ClockId::MonotonicCoarse),
#[cfg(linux_kernel)]
c::CLOCK_MONOTONIC_RAW => Ok(ClockId::MonotonicRaw),
#[cfg(linux_kernel)]
c::CLOCK_REALTIME_ALARM => Ok(ClockId::RealtimeAlarm),
#[cfg(all(linux_kernel, feature = "linux_4_11"))]
c::CLOCK_TAI => Ok(ClockId::Tai),
#[cfg(any(linux_kernel, target_os = "fuchsia", target_os = "openbsd"))]
c::CLOCK_BOOTTIME => Ok(ClockId::Boottime),
#[cfg(any(linux_kernel, target_os = "fuchsia"))]
c::CLOCK_BOOTTIME_ALARM => Ok(ClockId::BoottimeAlarm),
_ => Err(io::Errno::RANGE),
}
}
}

/// `CLOCK_*` constants for use with [`clock_gettime`].
///
/// These constants are always supported at runtime, so `clock_gettime` never
Expand Down Expand Up @@ -127,6 +173,21 @@ pub enum ClockId {
ThreadCPUTime = c::CLOCK_THREAD_CPUTIME_ID,
}

#[cfg(apple)]
impl TryFrom<c::clockid_t> for ClockId {
type Error = io::Errno;

fn try_from(value: c::clockid_t) -> Result<Self, Self::Error> {
match value {
c::CLOCK_REALTIME => Ok(ClockId::Realtime),
c::CLOCK_MONOTONIC => Ok(ClockId::Monotonic),
c::CLOCK_PROCESS_CPUTIME_ID => Ok(ClockId::ProcessCPUTime),
c::CLOCK_THREAD_CPUTIME_ID => Ok(ClockId::ThreadCPUTime),
_ => Err(io::Errno::RANGE),
}
}
}

/// `CLOCK_*` constants for use with [`clock_gettime_dynamic`].
///
/// These constants may be unsupported at runtime, depending on the OS version,
Expand Down
26 changes: 26 additions & 0 deletions src/net/send_recv/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ macro_rules! cmsg_space {
$len * ::core::mem::size_of::<$crate::net::UCred>(),
)
};
(TxTime($len:expr)) => {
$crate::net::__cmsg_space(
$len * ::core::mem::size_of::<u64>(),
)
};

// Combo Rules
($firstid:ident($firstex:expr), $($restid:ident($restex:expr)),*) => {{
Expand Down Expand Up @@ -94,6 +99,11 @@ macro_rules! cmsg_aligned_space {
$len * ::core::mem::size_of::<$crate::net::UCred>(),
)
};
(TxTime($len:expr)) => {
$crate::net::__cmsg_aligned_space(
$len * ::core::mem::size_of::<u64>(),
)
};

// Combo Rules
($firstid:ident($firstex:expr), $($restid:ident($restex:expr)),*) => {{
Expand Down Expand Up @@ -138,6 +148,13 @@ pub enum SendAncillaryMessage<'slice, 'fd> {
#[cfg(linux_kernel)]
#[doc(alias = "SCM_CREDENTIAL")]
ScmCredentials(UCred),
/// Transmission time, in nanoseconds. The value will be interpreted by
/// whichever clock was configured on the socket with [`set_txtime`].
///
/// [`set_txtime`]: crate::net::sockopt::set_txtime
#[cfg(target_os = "linux")]
#[doc(alias = "SCM_TXTIME")]
TxTime(u64),
}

impl SendAncillaryMessage<'_, '_> {
Expand All @@ -149,6 +166,8 @@ impl SendAncillaryMessage<'_, '_> {
Self::ScmRights(slice) => cmsg_space!(ScmRights(slice.len())),
#[cfg(linux_kernel)]
Self::ScmCredentials(_) => cmsg_space!(ScmCredentials(1)),
#[cfg(target_os = "linux")]
Self::TxTime(_) => cmsg_space!(TxTime(1)),
}
}
}
Expand Down Expand Up @@ -290,6 +309,13 @@ impl<'buf, 'slice, 'fd> SendAncillaryBuffer<'buf, 'slice, 'fd> {
};
self.push_ancillary(ucred_bytes, c::SOL_SOCKET as _, c::SCM_CREDENTIALS as _)
}
#[cfg(target_os = "linux")]
SendAncillaryMessage::TxTime(tx_time) => {
let tx_time_bytes = unsafe {
slice::from_raw_parts(addr_of!(tx_time).cast::<u8>(), size_of_val(&tx_time))
};
self.push_ancillary(tx_time_bytes, c::SOL_SOCKET as _, c::SO_TXTIME as _)
}
}
}

Expand Down
18 changes: 18 additions & 0 deletions src/net/sockopt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,8 @@
#![doc(alias = "getsockopt")]
#![doc(alias = "setsockopt")]

#[cfg(all(target_os = "linux", feature = "time"))]
use crate::clockid::ClockId;
#[cfg(target_os = "linux")]
use crate::net::xdp::{XdpMmapOffsets, XdpOptionsFlags, XdpStatistics, XdpUmemReg};
#[cfg(not(any(
Expand Down Expand Up @@ -172,6 +174,8 @@ use crate::net::Protocol;
use crate::net::SocketAddrV4;
#[cfg(linux_kernel)]
use crate::net::SocketAddrV6;
#[cfg(all(target_os = "linux", feature = "time"))]
use crate::net::TxTimeFlags;
use crate::net::{Ipv4Addr, Ipv6Addr, SocketType};
use crate::{backend, io};
#[cfg(feature = "alloc")]
Expand Down Expand Up @@ -1524,6 +1528,20 @@ pub fn socket_peercred<Fd: AsFd>(fd: Fd) -> io::Result<super::UCred> {
backend::net::sockopt::socket_peercred(fd.as_fd())
}

/// `getsockopt(fd, SOL_SOCKET, SO_TXTIME)` — Get transmission timing configuration.
#[cfg(all(target_os = "linux", feature = "time"))]
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this be #[cfg(linux_kernel)]? I don't get the distinction.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

linux_kernel is equivalent to any(target_os = "linux", target_os = "android")). If this feature compiles on Android, then we can enable it there too.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated with linux_kernel, so I guess we'll see what happens in CI :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, that's a no on android.

#[doc(alias = "SO_TXTIME")]
pub fn get_txtime<Fd: AsFd>(fd: Fd) -> io::Result<(ClockId, TxTimeFlags)> {
backend::net::sockopt::get_txtime(fd.as_fd())
}

/// `setsockopt(fd, SOL_SOCKET, SO_TXTIME)` — Configure transmission timing.
#[cfg(all(target_os = "linux", feature = "time"))]
#[doc(alias = "SO_TXTIME")]
pub fn set_txtime<Fd: AsFd>(fd: Fd, clockid: ClockId, flags: TxTimeFlags) -> io::Result<()> {
backend::net::sockopt::set_txtime(fd.as_fd(), clockid, flags)
}

/// `setsockopt(fd, SOL_XDP, XDP_UMEM_REG, value)`
///
/// On kernel versions only supporting v1, the flags are ignored.
Expand Down
15 changes: 15 additions & 0 deletions src/net/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1722,6 +1722,21 @@ bitflags! {
}
}

#[cfg(all(target_os = "linux", feature = "time"))]
bitflags! {
/// Flags for use with [`set_txtime`].
///
/// [`set_txtime`]: crate::net::sockopt::set_txtime
#[repr(transparent)]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct TxTimeFlags: u32 {
/// `SOF_TXTIME_DEADLINE_MODE`
const DEADLINE_MODE = bitcast!(c::SOF_TXTIME_DEADLINE_MODE);
/// `SOF_TXTIME_REPORT_ERRORS`
const REPORT_ERRORS = bitcast!(c::SOF_TXTIME_REPORT_ERRORS);
}
}

/// `AF_XDP` related types and constants.
#[cfg(target_os = "linux")]
pub mod xdp {
Expand Down
25 changes: 25 additions & 0 deletions tests/net/sockopt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ use rustix::io;
target_env = "newlib"
))]
use rustix::net::ipproto;
#[cfg(target_os = "linux")]
use rustix::net::TxTimeFlags;
use rustix::net::{sockopt, AddressFamily, SocketType};
#[cfg(target_os = "linux")]
use rustix::time::ClockId;
use std::net::Ipv4Addr;
use std::time::Duration;

Expand Down Expand Up @@ -625,3 +629,24 @@ fn test_sockopts_multicast_ifv6() {
Err(e) => panic!("{e}"),
}
}

#[test]
#[cfg(target_os = "linux")]
fn test_sockopts_txtime() {
crate::init();

let s = rustix::net::socket(AddressFamily::INET, SocketType::DGRAM, None).unwrap();

match sockopt::set_txtime(&s, ClockId::Monotonic, TxTimeFlags::DEADLINE_MODE) {
Ok(()) => {
assert_eq!(
sockopt::get_txtime(&s).unwrap(),
(ClockId::Monotonic, TxTimeFlags::DEADLINE_MODE)
);
}
Err(e) if e.to_string().contains("Protocol not available") => {
// Skip test on unsupported platforms
}
Err(e) => panic!("{e}"),
}
}
Loading
Loading