← Back to Pull requests

Add back `preadv2` optimization for `try_acquire` on Linux #90

Open
NobodyXu opened this pull request with 91 lines diff across 1 files
View on GitHub
NobodyXu NobodyXu commented on Apr 22, 2024 13:52 UTC
Author

Fixed #87

Diff: 91 lines (+91 / -0) across 1 files Reviewer: petrochenkov Review duration: 1377440m
All Vouch review confidence checks passed
Residual risk 0.04 = Change Risk (0.37) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.37 · 91 lines diff across 1 files
0.37
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.89 · 5 substantive comment(s)
0.89
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
88%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.271
Real PR Conversation Timeline
41 items
NobodyXu NobodyXu commented on Apr 22, 2024 13:52 UTC
Author

cc @the8472 can you check the syscall I added please?

I'm not sure if it is correct, thank you!

petrochenkov petrochenkov commented on code on Apr 22, 2024 14:32 UTC
Code Review
src/unix.rs:1
@@ -285,6 +285,33 @@ impl Client {
     pub fn try_acquire(&self) -> io::Result<Option<Acquired>> {
         let mut buf = [0];
 
+        // On Linux, we can use preadv2 to do non-blocking read,
+        // even if `O_NONBLOCK` is not set.
+        //
+        // TODO: musl libc supports preadv2 since 1.2.5, but `libc` crate
+        // hasn't yet added it.

The TODO is no longer relevant, since bare syscall is used.

petrochenkov petrochenkov commented on code on Apr 22, 2024 14:32 UTC
Code Review
src/unix.rs:1
@@ -368,6 +395,84 @@ impl Client {
     }
 }
 
+// This should be available for all linux targets,
+// though only [`non_blocking_read`] currently uses it so adding gnu cfg.

Another outdated comment.

petrochenkov petrochenkov commented on code on Apr 22, 2024 14:33 UTC
Code Review
src/unix.rs:1
@@ -368,6 +395,84 @@ impl Client {
     }
 }
 
+// This should be available for all linux targets,
+// though only [`non_blocking_read`] currently uses it so adding gnu cfg.
+#[cfg(any(target_os = "linux", target_os = "android"))]
+mod linux {
+    use super::*;
+
+    use libc::{iovec, off_t, ssize_t, syscall, SYS_preadv2};
+
+    const RWF_NOWAIT: c_int = 0x00000008;
+
+    fn cvt_ssize(t: ssize_t) -> io::Result<ssize_t> {
+        if t == -1 {
+            Err(io::Error::last_os_error())
+        } else {
+            Ok(t)
+        }
+    }
+
+    unsafe fn preadv2(
+        fd: c_int,
+        iov: *const iovec,
+        iovcnt: c_int,
+        offset: off_t,
+        flags: c_int,
+    ) -> ssize_t {
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
+        let res = syscall(SYS_preadv2, fd, iov, iovcnt, offset, 0, flags);
+
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))]
+        let res = syscall(SYS_preadv2, fd, iov, iovcnt, offset, 0, flags);

I don't see any difference between target_pointer_width 64 and 32.

the8472 the8472 commented on code on Apr 22, 2024 17:26 UTC
Code Review
src/unix.rs:1
@@ -368,6 +395,84 @@ impl Client {
     }
 }
 
+// This should be available for all linux targets,
+// though only [`non_blocking_read`] currently uses it so adding gnu cfg.
+#[cfg(any(target_os = "linux", target_os = "android"))]
+mod linux {
+    use super::*;
+
+    use libc::{iovec, off_t, ssize_t, syscall, SYS_preadv2};
+
+    const RWF_NOWAIT: c_int = 0x00000008;

That seems a little iffy. Theoretically the values could vary between architectures.
Musl added that flag recently. Can you leave a note to use that in the future once libc has it?

the8472 the8472 commented on Apr 22, 2024 17:28 UTC
Reviewer

Maybe we can simplify things by limiting to aarch64, x86_64 linux gnu? Those are probably the most common environments where stuff is _built_. And it's mostly a perf optimization, so we can be conservative in which platforms get it.

workingjubilee workingjubilee commented on code on Apr 23, 2024 00:07 UTC
Code Review
src/unix.rs:1
@@ -285,6 +285,33 @@ impl Client {
     pub fn try_acquire(&self) -> io::Result<Option<Acquired>> {
         let mut buf = [0];
 
+        // On Linux, we can use preadv2 to do non-blocking read,
+        // even if `O_NONBLOCK` is not set.
+        //
+        // TODO: musl libc supports preadv2 since 1.2.5, but `libc` crate
+        // hasn't yet added it.
+        #[cfg(any(target_os = "linux", target_os = "android"))]
+        {
+            let read = self.read().as_raw_fd();
+            loop {
+                match linux::non_blocking_read(read, &mut buf) {
+                    Ok(1) => return Ok(Some(Acquired { byte: buf[0] })),
+                    Ok(_) => {
+                        return Err(io::Error::new(
+                            io::ErrorKind::UnexpectedEof,
+                            "early EOF on jobserver pipe",
+                        ))
+                    }

Why would returning a value of 2 be interpreted as UnexpectedEof? Yes, this is only expecting a value of 1 or 0, but shouldn't the actual fallthrough case be unreachable!()?

workingjubilee workingjubilee commented on code on Apr 23, 2024 01:08 UTC
Code Review
src/unix.rs:1
@@ -368,6 +395,84 @@ impl Client {
     }
 }
 
+// This should be available for all linux targets,
+// though only [`non_blocking_read`] currently uses it so adding gnu cfg.
+#[cfg(any(target_os = "linux", target_os = "android"))]
+mod linux {
+    use super::*;
+
+    use libc::{iovec, off_t, ssize_t, syscall, SYS_preadv2};
+
+    const RWF_NOWAIT: c_int = 0x00000008;
+
+    fn cvt_ssize(t: ssize_t) -> io::Result<ssize_t> {
+        if t == -1 {
+            Err(io::Error::last_os_error())
+        } else {
+            Ok(t)
+        }
+    }
+
+    unsafe fn preadv2(
+        fd: c_int,
+        iov: *const iovec,
+        iovcnt: c_int,
+        offset: off_t,
+        flags: c_int,
+    ) -> ssize_t {
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
+        let res = syscall(SYS_preadv2, fd, iov, iovcnt, offset, 0, flags);
+
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))]
+        let res = syscall(SYS_preadv2, fd, iov, iovcnt, offset, 0, flags);
+
+        #[cfg(not(target_arch = "x86_64"))]
+        let res = syscall(
+            SYS_preadv2,
+            fd,
+            iov,
+            iovcnt,
+            offset as libc::c_long,
+            ((offset as u64) >> 32) as libc::c_long,
+            flags,
+        );
+
+        res.try_into().unwrap()
+    }
+
+    pub fn non_blocking_read(fd: c_int, buf: &mut [u8]) -> io::Result<usize> {
+        static IS_NONBLOCKING_READ_UNSUPPORTED: AtomicBool = AtomicBool::new(false);
+
+        if IS_NONBLOCKING_READ_UNSUPPORTED.load(Ordering::Relaxed) {
+            return Err(io::ErrorKind::Unsupported.into());
+        }
+
+        match cvt_ssize(unsafe {
+            preadv2(
+                fd,
+                &iovec {
+                    iov_base: buf.as_ptr() as *mut _,
+                    iov_len: buf.len(),
+                },
+                1,
+                -1,
+                RWF_NOWAIT,
+            )
+        }) {
+            Ok(cnt) => Ok(cnt.try_into().unwrap()),
+            Err(err) if err.raw_os_error() == Some(libc::EOPNOTSUPP) => {
+                IS_NONBLOCKING_READ_UNSUPPORTED.store(true, Ordering::Relaxed);
+                Err(io::ErrorKind::Unsupported.into())
+            }
+            Err(err) if err.kind() == io::ErrorKind::Unsupported => {
+                IS_NONBLOCKING_READ_UNSUPPORTED.store(true, Ordering::Relaxed);
+                Err(err)
+            }

can this just be

            Err(err) if matches!(err.raw_os_error(), Some(libc::EOPNOTSUPP | libc::ENOSYS)) => {
                IS_NONBLOCKING_READ_UNSUPPORTED.store(true, Ordering::Relaxed);
                Err(io::ErrorKind::Unsupported.into())
            }

workingjubilee workingjubilee commented on code on Apr 23, 2024 01:09 UTC
Code Review
src/unix.rs:1
@@ -368,6 +395,84 @@ impl Client {
     }
 }
 
+// This should be available for all linux targets,
+// though only [`non_blocking_read`] currently uses it so adding gnu cfg.
+#[cfg(any(target_os = "linux", target_os = "android"))]
+mod linux {
+    use super::*;
+
+    use libc::{iovec, off_t, ssize_t, syscall, SYS_preadv2};
+
+    const RWF_NOWAIT: c_int = 0x00000008;
+
+    fn cvt_ssize(t: ssize_t) -> io::Result<ssize_t> {
+        if t == -1 {
+            Err(io::Error::last_os_error())
+        } else {
+            Ok(t)
+        }
+    }
+
+    unsafe fn preadv2(
+        fd: c_int,
+        iov: *const iovec,
+        iovcnt: c_int,
+        offset: off_t,
+        flags: c_int,
+    ) -> ssize_t {
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
+        let res = syscall(SYS_preadv2, fd, iov, iovcnt, offset, 0, flags);
+
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))]
+        let res = syscall(SYS_preadv2, fd, iov, iovcnt, offset, 0, flags);
+
+        #[cfg(not(target_arch = "x86_64"))]
+        let res = syscall(
+            SYS_preadv2,
+            fd,
+            iov,
+            iovcnt,
+            offset as libc::c_long,
+            ((offset as u64) >> 32) as libc::c_long,
+            flags,
+        );
+
+        res.try_into().unwrap()
+    }

While this is a faithful implementation of preadv2, we _could_ simply ditch the args we don't ever use and use the opportunity to comment on why we always pass iovcnt: 1, offset: -1, flags: RWF_NOWAIT.

workingjubilee workingjubilee commented on Apr 23, 2024 01:09 UTC
Reviewer

what are the numbers on this optimization like?

NobodyXu NobodyXu commented on Apr 23, 2024 12:53 UTC
Author

what are the numbers on this optimization like?

It would enable try_acquire support on cases where:
- jobserver gets an annoymous pipe instead of named fifo
- procfs is not available
Without preadv2, try_acquire would return a not-supported error.

On performance, it's mostly for avoiding performance loss with acquire when jobserver receives a named fifo or procfs is available (which jobserver would use to convert pipe to fifo).

Without preadv2,try_acquire would set the fifo to non-blocking, which would cause acquire to enter poll + read if the fifo is empty, which is less efficient than a blocking read.

NobodyXu NobodyXu commented on Apr 23, 2024 12:58 UTC
Author

Maybe we can simplify things by limiting to aarch64, x86_64 linux gnu? Those are probably the most common environments where stuff is _built_.

Well, from the glibc implementation, it looks like there're only 3 versions for it, so maybe we can still bare with the cost?

And it's mostly a perf optimization, so we can be conservative in which platforms get it.

While it's mostly a perf optimization, there is situation where preadv2 actually enable try_acquire to work properly instead of returning a not-supported error:

- jobserver gets an annoymous pipe instead of named fifo
- procfs is not available
Without preadv2, try_acquire would return a not-supported error.

NobodyXu NobodyXu commented on code on Apr 25, 2024 11:43 UTC
Code Review
src/unix.rs:1
@@ -368,6 +395,84 @@ impl Client {
     }
 }
 
+// This should be available for all linux targets,
+// though only [`non_blocking_read`] currently uses it so adding gnu cfg.
+#[cfg(any(target_os = "linux", target_os = "android"))]
+mod linux {
+    use super::*;
+
+    use libc::{iovec, off_t, ssize_t, syscall, SYS_preadv2};
+
+    const RWF_NOWAIT: c_int = 0x00000008;
+
+    fn cvt_ssize(t: ssize_t) -> io::Result<ssize_t> {
+        if t == -1 {
+            Err(io::Error::last_os_error())
+        } else {
+            Ok(t)
+        }
+    }
+
+    unsafe fn preadv2(
+        fd: c_int,
+        iov: *const iovec,
+        iovcnt: c_int,
+        offset: off_t,
+        flags: c_int,
+    ) -> ssize_t {
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
+        let res = syscall(SYS_preadv2, fd, iov, iovcnt, offset, 0, flags);
+
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))]
+        let res = syscall(SYS_preadv2, fd, iov, iovcnt, offset, 0, flags);

Thanks, I made a mistake when copying the code.

weihanglo weihanglo commented on Apr 25, 2024 12:37 UTC
Contributor

> what are the numbers on this optimization like?

> It would enable try_acquire support on cases where:

> jobserver gets an annoymous pipe instead of named fifo

> procfs is not available

Without preadv2, try_acquire would return a not-supported error.

>

On performance, it's mostly for avoiding performance loss with acquire when jobserver receives a named fifo or procfs is available (which jobserver would use to convert pipe to fifo).

> Without preadv2,try_acquire would set the fifo to non-blocking, which would cause acquire to enter poll + read if the fifo is empty, which is less efficient than a blocking read.

Thanks @NobodyXu for the work. Believing that people already know the benefit of this for fixing unsupported situations. What Jubilee asked for are numbers. I think that's a reasonable request for a change aiming at optimization. Could you do some benchmark and show the number, so we can have a baseline in mind? It is also beneficial to prevent from future performance regression if we have the reproducible benchmark steps (if you don't mind sharing).

NobodyXu NobodyXu commented on code on Apr 25, 2024 12:40 UTC
Code Review
src/unix.rs:1
@@ -285,6 +285,33 @@ impl Client {
     pub fn try_acquire(&self) -> io::Result<Option<Acquired>> {
         let mut buf = [0];
 
+        // On Linux, we can use preadv2 to do non-blocking read,
+        // even if `O_NONBLOCK` is not set.
+        //
+        // TODO: musl libc supports preadv2 since 1.2.5, but `libc` crate
+        // hasn't yet added it.
+        #[cfg(any(target_os = "linux", target_os = "android"))]
+        {
+            let read = self.read().as_raw_fd();
+            loop {
+                match linux::non_blocking_read(read, &mut buf) {
+                    Ok(1) => return Ok(Some(Acquired { byte: buf[0] })),
+                    Ok(_) => {
+                        return Err(io::Error::new(
+                            io::ErrorKind::UnexpectedEof,
+                            "early EOF on jobserver pipe",
+                        ))
+                    }

It's actually trying to match situations Ok(0) here.

I wrote it like this because elsewhere matches the return value of read in the same way.

NobodyXu NobodyXu commented on code on Apr 25, 2024 12:50 UTC
Code Review
src/unix.rs:1
@@ -285,6 +285,33 @@ impl Client {
     pub fn try_acquire(&self) -> io::Result<Option<Acquired>> {
         let mut buf = [0];
 
+        // On Linux, we can use preadv2 to do non-blocking read,
+        // even if `O_NONBLOCK` is not set.
+        //
+        // TODO: musl libc supports preadv2 since 1.2.5, but `libc` crate
+        // hasn't yet added it.

Thanks, updated.

NobodyXu NobodyXu commented on code on Apr 25, 2024 12:50 UTC
Code Review
src/unix.rs:1
@@ -368,6 +395,84 @@ impl Client {
     }
 }
 
+// This should be available for all linux targets,
+// though only [`non_blocking_read`] currently uses it so adding gnu cfg.

Thanks, removed.

NobodyXu NobodyXu commented on code on Apr 25, 2024 12:50 UTC
Code Review
src/unix.rs:1
@@ -368,6 +395,84 @@ impl Client {
     }
 }
 
+// This should be available for all linux targets,
+// though only [`non_blocking_read`] currently uses it so adding gnu cfg.
+#[cfg(any(target_os = "linux", target_os = "android"))]
+mod linux {
+    use super::*;
+
+    use libc::{iovec, off_t, ssize_t, syscall, SYS_preadv2};
+
+    const RWF_NOWAIT: c_int = 0x00000008;
+
+    fn cvt_ssize(t: ssize_t) -> io::Result<ssize_t> {
+        if t == -1 {
+            Err(io::Error::last_os_error())
+        } else {
+            Ok(t)
+        }
+    }
+
+    unsafe fn preadv2(
+        fd: c_int,
+        iov: *const iovec,
+        iovcnt: c_int,
+        offset: off_t,
+        flags: c_int,
+    ) -> ssize_t {
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
+        let res = syscall(SYS_preadv2, fd, iov, iovcnt, offset, 0, flags);
+
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))]
+        let res = syscall(SYS_preadv2, fd, iov, iovcnt, offset, 0, flags);

Updated.

NobodyXu NobodyXu commented on code on Apr 25, 2024 12:50 UTC
Code Review
src/unix.rs:1
@@ -368,6 +395,84 @@ impl Client {
     }
 }
 
+// This should be available for all linux targets,
+// though only [`non_blocking_read`] currently uses it so adding gnu cfg.
+#[cfg(any(target_os = "linux", target_os = "android"))]
+mod linux {
+    use super::*;
+
+    use libc::{iovec, off_t, ssize_t, syscall, SYS_preadv2};
+
+    const RWF_NOWAIT: c_int = 0x00000008;

Thanks, added a TODO for this.

NobodyXu NobodyXu commented on code on Apr 25, 2024 12:51 UTC
Code Review
src/unix.rs:1
@@ -368,6 +395,84 @@ impl Client {
     }
 }
 
+// This should be available for all linux targets,
+// though only [`non_blocking_read`] currently uses it so adding gnu cfg.
+#[cfg(any(target_os = "linux", target_os = "android"))]
+mod linux {
+    use super::*;
+
+    use libc::{iovec, off_t, ssize_t, syscall, SYS_preadv2};
+
+    const RWF_NOWAIT: c_int = 0x00000008;
+
+    fn cvt_ssize(t: ssize_t) -> io::Result<ssize_t> {
+        if t == -1 {
+            Err(io::Error::last_os_error())
+        } else {
+            Ok(t)
+        }
+    }
+
+    unsafe fn preadv2(
+        fd: c_int,
+        iov: *const iovec,
+        iovcnt: c_int,
+        offset: off_t,
+        flags: c_int,
+    ) -> ssize_t {
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
+        let res = syscall(SYS_preadv2, fd, iov, iovcnt, offset, 0, flags);
+
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))]
+        let res = syscall(SYS_preadv2, fd, iov, iovcnt, offset, 0, flags);
+
+        #[cfg(not(target_arch = "x86_64"))]
+        let res = syscall(
+            SYS_preadv2,
+            fd,
+            iov,
+            iovcnt,
+            offset as libc::c_long,
+            ((offset as u64) >> 32) as libc::c_long,
+            flags,
+        );
+
+        res.try_into().unwrap()
+    }

Thanks, I've hardcoded these values and now it's more readable.

NobodyXu NobodyXu commented on Apr 25, 2024 12:53 UTC
Author

What Jubilee asked for are numbers. I think that's a reasonable request for a change aiming at optimization. Could you do some benchmark and show the number, so we can have a baseline in mind? It is also beneficial to prevent from future performance regression if we have the reproducible benchmark steps (if you don't mind sharing).

I could add one in benches/, it would first call try_acquire on Linux and then call acquire.
Might have to add criterion as a dev-dep though.

Edit:

Would do that tomorrow.

the8472 the8472 commented on Apr 25, 2024 15:49 UTC
Contributor

Note that using blocking reads in acquire is mostly beneficial when there are many concurrent waiters. A single waiter won't see much of a speedup (perhaps a little from the avoided syscalls).

See #30 and https://github.com/torvalds/linux/commit/0ddad21d3e99c743a3aa473121dc5561679e26bb, the latter one has numbers.

workingjubilee workingjubilee commented on Apr 27, 2024 03:43 UTC
Contributor

Oh, cute, so it is in fact a kernel optimization specifically for this protocol!

workingjubilee workingjubilee commented on code on Apr 27, 2024 04:06 UTC
Code Review
src/unix.rs:1
@@ -368,6 +392,83 @@ impl Client {
     }
 }
 
+#[cfg(any(target_os = "linux", target_os = "android"))]
+mod linux {
+    use super::*;
+
+    use libc::{iovec, off_t, ssize_t, syscall, SYS_preadv2};
+
+    // TODO: Replace this with libc::RWF_NOWAIT once they have it for musl
+    //  targets
+    const RWF_NOWAIT: c_int = 0x00000008;
+
+    fn cvt_ssize(t: ssize_t) -> io::Result<ssize_t> {
+        if t == -1 {
+            Err(io::Error::last_os_error())
+        } else {
+            Ok(t)
+        }
+    }
+
+    fn preadv2(fd: c_int, iov: &iovec) -> ssize_t {
+        let iovcnt: c_int = 1;
+

I meant something more like,

        let offset = -1; // "use and update current offset" as in readv, not preadv

bit of a magic number otherwise.

workingjubilee workingjubilee commented on code on Apr 27, 2024 04:06 UTC
Code Review
src/unix.rs:1
@@ -368,6 +392,83 @@ impl Client {
     }
 }
 
+#[cfg(any(target_os = "linux", target_os = "android"))]
+mod linux {
+    use super::*;
+
+    use libc::{iovec, off_t, ssize_t, syscall, SYS_preadv2};
+
+    // TODO: Replace this with libc::RWF_NOWAIT once they have it for musl
+    //  targets
+    const RWF_NOWAIT: c_int = 0x00000008;
+
+    fn cvt_ssize(t: ssize_t) -> io::Result<ssize_t> {
+        if t == -1 {
+            Err(io::Error::last_os_error())
+        } else {
+            Ok(t)
+        }
+    }
+
+    fn preadv2(fd: c_int, iov: &iovec) -> ssize_t {
+        let iovcnt: c_int = 1;
+
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
+        let res = unsafe {
+            syscall(
+                SYS_preadv2,
+                fd,
+                iov,
+                iovcnt,
+                -1 as off_t,

                offset as off_t,

workingjubilee workingjubilee commented on code on Apr 27, 2024 04:07 UTC
Code Review
src/unix.rs:1
@@ -368,6 +392,83 @@ impl Client {
     }
 }
 
+#[cfg(any(target_os = "linux", target_os = "android"))]
+mod linux {
+    use super::*;
+
+    use libc::{iovec, off_t, ssize_t, syscall, SYS_preadv2};
+
+    // TODO: Replace this with libc::RWF_NOWAIT once they have it for musl
+    //  targets
+    const RWF_NOWAIT: c_int = 0x00000008;
+
+    fn cvt_ssize(t: ssize_t) -> io::Result<ssize_t> {
+        if t == -1 {
+            Err(io::Error::last_os_error())
+        } else {
+            Ok(t)
+        }
+    }
+
+    fn preadv2(fd: c_int, iov: &iovec) -> ssize_t {
+        let iovcnt: c_int = 1;
+
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
+        let res = unsafe {
+            syscall(
+                SYS_preadv2,
+                fd,
+                iov,
+                iovcnt,
+                -1 as off_t,
+                0 as off_t,
+                RWF_NOWAIT,
+            )
+        };
+
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))]
+        let res = unsafe { syscall(SYS_preadv2, fd, iov, iovcnt, -1 as off_t, RWF_NOWAIT) };
+
+        #[cfg(not(target_arch = "x86_64"))]
+        let res = unsafe {
+            syscall(
+                SYS_preadv2,
+                fd,
+                iov,
+                iovcnt,
+                -1 as libc::c_long,

                offset as libc::c_long,

workingjubilee workingjubilee commented on code on Apr 27, 2024 04:07 UTC
Code Review
src/unix.rs:1
@@ -368,6 +392,83 @@ impl Client {
     }
 }
 
+#[cfg(any(target_os = "linux", target_os = "android"))]
+mod linux {
+    use super::*;
+
+    use libc::{iovec, off_t, ssize_t, syscall, SYS_preadv2};
+
+    // TODO: Replace this with libc::RWF_NOWAIT once they have it for musl
+    //  targets
+    const RWF_NOWAIT: c_int = 0x00000008;
+
+    fn cvt_ssize(t: ssize_t) -> io::Result<ssize_t> {
+        if t == -1 {
+            Err(io::Error::last_os_error())
+        } else {
+            Ok(t)
+        }
+    }
+
+    fn preadv2(fd: c_int, iov: &iovec) -> ssize_t {
+        let iovcnt: c_int = 1;
+
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
+        let res = unsafe {
+            syscall(
+                SYS_preadv2,
+                fd,
+                iov,
+                iovcnt,
+                -1 as off_t,
+                0 as off_t,
+                RWF_NOWAIT,
+            )
+        };
+
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))]
+        let res = unsafe { syscall(SYS_preadv2, fd, iov, iovcnt, -1 as off_t, RWF_NOWAIT) };

        let res = unsafe { syscall(SYS_preadv2, fd, iov, iovcnt, offset as off_t, RWF_NOWAIT) };

petrochenkov petrochenkov commented on Apr 27, 2024 12:19 UTC
Contributor

Can the code generally minimize amount of #[cfg(...)] in favor of cfg!(...)?
It will get more checking and less surprises on remaining platforms.
#[cfg(...)] is not really needed that often, only when some names are unavailable on some platforms (and even then they can sometimes be defined to dummies, see e.g. how type RawFd is defined).

NobodyXu NobodyXu commented on code on Apr 29, 2024 13:16 UTC
Code Review
src/unix.rs:1
@@ -368,6 +392,83 @@ impl Client {
     }
 }
 
+#[cfg(any(target_os = "linux", target_os = "android"))]
+mod linux {
+    use super::*;
+
+    use libc::{iovec, off_t, ssize_t, syscall, SYS_preadv2};
+
+    // TODO: Replace this with libc::RWF_NOWAIT once they have it for musl
+    //  targets
+    const RWF_NOWAIT: c_int = 0x00000008;
+
+    fn cvt_ssize(t: ssize_t) -> io::Result<ssize_t> {
+        if t == -1 {
+            Err(io::Error::last_os_error())
+        } else {
+            Ok(t)
+        }
+    }
+
+    fn preadv2(fd: c_int, iov: &iovec) -> ssize_t {
+        let iovcnt: c_int = 1;
+

Thanks, I've added the offset variable with the right typing.

NobodyXu NobodyXu commented on code on Apr 29, 2024 13:16 UTC
Code Review
src/unix.rs:1
@@ -368,6 +392,83 @@ impl Client {
     }
 }
 
+#[cfg(any(target_os = "linux", target_os = "android"))]
+mod linux {
+    use super::*;
+
+    use libc::{iovec, off_t, ssize_t, syscall, SYS_preadv2};
+
+    // TODO: Replace this with libc::RWF_NOWAIT once they have it for musl
+    //  targets
+    const RWF_NOWAIT: c_int = 0x00000008;
+
+    fn cvt_ssize(t: ssize_t) -> io::Result<ssize_t> {
+        if t == -1 {
+            Err(io::Error::last_os_error())
+        } else {
+            Ok(t)
+        }
+    }
+
+    fn preadv2(fd: c_int, iov: &iovec) -> ssize_t {
+        let iovcnt: c_int = 1;
+
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
+        let res = unsafe {
+            syscall(
+                SYS_preadv2,
+                fd,
+                iov,
+                iovcnt,
+                -1 as off_t,

Updated.

NobodyXu NobodyXu commented on code on Apr 29, 2024 13:16 UTC
Code Review
src/unix.rs:1
@@ -368,6 +392,83 @@ impl Client {
     }
 }
 
+#[cfg(any(target_os = "linux", target_os = "android"))]
+mod linux {
+    use super::*;
+
+    use libc::{iovec, off_t, ssize_t, syscall, SYS_preadv2};
+
+    // TODO: Replace this with libc::RWF_NOWAIT once they have it for musl
+    //  targets
+    const RWF_NOWAIT: c_int = 0x00000008;
+
+    fn cvt_ssize(t: ssize_t) -> io::Result<ssize_t> {
+        if t == -1 {
+            Err(io::Error::last_os_error())
+        } else {
+            Ok(t)
+        }
+    }
+
+    fn preadv2(fd: c_int, iov: &iovec) -> ssize_t {
+        let iovcnt: c_int = 1;
+
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
+        let res = unsafe {
+            syscall(
+                SYS_preadv2,
+                fd,
+                iov,
+                iovcnt,
+                -1 as off_t,
+                0 as off_t,
+                RWF_NOWAIT,
+            )
+        };
+
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))]
+        let res = unsafe { syscall(SYS_preadv2, fd, iov, iovcnt, -1 as off_t, RWF_NOWAIT) };
+
+        #[cfg(not(target_arch = "x86_64"))]
+        let res = unsafe {
+            syscall(
+                SYS_preadv2,
+                fd,
+                iov,
+                iovcnt,
+                -1 as libc::c_long,

Updated.

NobodyXu NobodyXu commented on code on Apr 29, 2024 13:16 UTC
Code Review
src/unix.rs:1
@@ -368,6 +392,83 @@ impl Client {
     }
 }
 
+#[cfg(any(target_os = "linux", target_os = "android"))]
+mod linux {
+    use super::*;
+
+    use libc::{iovec, off_t, ssize_t, syscall, SYS_preadv2};
+
+    // TODO: Replace this with libc::RWF_NOWAIT once they have it for musl
+    //  targets
+    const RWF_NOWAIT: c_int = 0x00000008;
+
+    fn cvt_ssize(t: ssize_t) -> io::Result<ssize_t> {
+        if t == -1 {
+            Err(io::Error::last_os_error())
+        } else {
+            Ok(t)
+        }
+    }
+
+    fn preadv2(fd: c_int, iov: &iovec) -> ssize_t {
+        let iovcnt: c_int = 1;
+
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
+        let res = unsafe {
+            syscall(
+                SYS_preadv2,
+                fd,
+                iov,
+                iovcnt,
+                -1 as off_t,
+                0 as off_t,
+                RWF_NOWAIT,
+            )
+        };
+
+        #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))]
+        let res = unsafe { syscall(SYS_preadv2, fd, iov, iovcnt, -1 as off_t, RWF_NOWAIT) };

Updated.

NobodyXu NobodyXu commented on Apr 29, 2024 13:17 UTC
Author

Can the code generally minimize amount of #[cfg(...)] in favor of cfg!(...)? It will get more checking and less surprises on remaining platforms.

Thanks, I've added the code in preadv2 to use cfg! instead of #[cfg(...)], it's actually more readable now.

the8472 the8472 commented on code on Jun 27, 2024 21:55 UTC
Code Review
src/unix.rs:1
@@ -285,6 +285,33 @@ impl Client {
     pub fn try_acquire(&self) -> io::Result<Option<Acquired>> {
         let mut buf = [0];
 
+        // On Linux, we can use preadv2 to do non-blocking read,
+        // even if `O_NONBLOCK` is not set.
+        //
+        // TODO: musl libc supports preadv2 since 1.2.5, but `libc` crate
+        // hasn't yet added it.
+        #[cfg(any(target_os = "linux", target_os = "android"))]
+        {
+            let read = self.read().as_raw_fd();
+            loop {
+                match linux::non_blocking_read(read, &mut buf) {
+                    Ok(1) => return Ok(Some(Acquired { byte: buf[0] })),
+                    Ok(_) => {
+                        return Err(io::Error::new(
+                            io::ErrorKind::UnexpectedEof,
+                            "early EOF on jobserver pipe",
+                        ))
+                    }

I agree with jubilee. The n > 1 case should be an extra case. preadv is tricky and there was a bug on older kernels where it returned wrong values. That shouldn't affect pipes since the support for those is more recent than the bug but it's still good to separate out the unexpected case.

the8472 the8472 commented on code on Jun 27, 2024 22:01 UTC
Code Review
src/unix.rs:1
@@ -368,6 +392,73 @@ impl Client {
     }
 }
 
+#[cfg(any(target_os = "linux", target_os = "android"))]
+mod linux {
+    use super::*;
+
+    use libc::{iovec, off_t, ssize_t, syscall, SYS_preadv2};
+
+    // TODO: Replace this with libc::RWF_NOWAIT once they have it for musl
+    //  targets
+    const RWF_NOWAIT: c_int = 0x00000008;
+
+    fn cvt_ssize(t: ssize_t) -> io::Result<ssize_t> {
+        if t == -1 {
+            Err(io::Error::last_os_error())
+        } else {
+            Ok(t)
+        }
+    }
+
+    fn preadv2(fd: c_int, iov: &iovec) -> ssize_t {
+        let iovcnt: c_int = 1;
+        let offset: off_t = -1;
+
+        if cfg!(all(target_arch = "x86_64", target_pointer_width = "64")) {

The branches here could use some comment. It's a bit surprising that 86-64 needs two special-cases but all other platforms (including powerpc, aarch64 and even i686) all go in the same bucket.

the8472 the8472 commented on Jun 27, 2024 22:03 UTC
Reviewer

Since this code path is trying to achieve something very specific - doing a non-blocking read without setting a pipe fd to O_NONBLOCK - there should be a platform-specific test that checks that this indeed does happen.

But even if we have tests CI only exercises x86-64. If we had targeted tests we could manually run it on the arm cloud machines at least.

My other concern is that the syscall code _looks_ correct but usually the devil is in the details. Having a targeted test would help with that too.

NobodyXu NobodyXu commented on Jun 28, 2024 03:11 UTC
Author

Yeah I would add one, I wish libc would support it for musl libc

Or perhaps we could wait till libc support it on musl @the8472 ?

the8472 the8472 commented on Jun 28, 2024 08:10 UTC
Contributor

Yeah it's not urgent. try_acquire is new and I assume not many things are using it yet so the negative performance impact of making the pipe non-blocking isn't important yet.

NobodyXu NobodyXu commented on Jun 28, 2024 08:45 UTC
Author

try_acquire is new and I assume not many things are using it yet so the negative performance impact of making the pipe non-blocking isn't important yet.

Well cc is using it so it does have some effect to the ecosystem as a whole, though depending on the project, it might not be that large as compiling is much more expensive.

NobodyXu NobodyXu commented on Jun 28, 2024 08:49 UTC
Author

Opened rust-lang/libc#3760

Reviewers
Assignees
NobodyXu NobodyXu
Labels
risk: low confidence: 88.6% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 37% (MEDIUM) · Higher = larger blast radius
37%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 88.6% · Lower = rushed or shallow review
88.6%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 4.2% · Safe to merge
4.2%