From 8e1277887947a5dd612eff263a3e08076a7d1f66 Mon Sep 17 00:00:00 2001 From: David Carlier Date: Fri, 2 Feb 2024 20:55:44 +0000 Subject: [PATCH] std::thread::available_parallelism merging linux/android/freebsd version FreeBSD 13.1 had introduced a sched cpu affinity compatibility layer with Linux. 13.0 and even 13.1 being EOL, we can simplify here. --- library/std/src/sys/pal/unix/thread.rs | 46 +++++++++----------------- 1 file changed, 16 insertions(+), 30 deletions(-) diff --git a/library/std/src/sys/pal/unix/thread.rs b/library/std/src/sys/pal/unix/thread.rs index 7e4a01a5ecd33..6f79f1cc6e8f7 100644 --- a/library/std/src/sys/pal/unix/thread.rs +++ b/library/std/src/sys/pal/unix/thread.rs @@ -320,19 +320,22 @@ pub fn available_parallelism() -> io::Result { target_os = "solaris", target_os = "illumos", target_os = "aix", + target_os = "freebsd", ))] { - #[allow(unused_assignments)] - #[allow(unused_mut)] - let mut quota = usize::MAX; - - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(any(target_os = "android", target_os = "linux", target_os = "freebsd"))] { - quota = cgroups::quota().max(1); - let mut set: libc::cpu_set_t = unsafe { mem::zeroed() }; + #[cfg(not(target_os = "freebsd"))] + type cpuset = libc::cpu_set_t; + #[cfg(target_os = "freebsd")] + type cpuset = libc::cpuset_t; + let mut set: cpuset = unsafe { mem::zeroed() }; unsafe { - if libc::sched_getaffinity(0, mem::size_of::(), &mut set) == 0 { + if libc::sched_getaffinity(0, mem::size_of::(), &mut set) == 0 { let count = libc::CPU_COUNT(&set) as usize; - let count = count.min(quota); + #[cfg(not(target_os = "freebsd"))] + let count = count.min(cgroups::quota().max(1)); + #[cfg(target_os = "freebsd")] + let count = count.min(usize::MAX); // According to sched_getaffinity's API it should always be non-zero, but // some old MIPS kernels were buggy and zero-initialized the mask if @@ -350,37 +353,20 @@ pub fn available_parallelism() -> io::Result { cpus => { let count = cpus as usize; // Cover the unusual situation where we were able to get the quota but not the affinity mask - let count = count.min(quota); + #[cfg(any(target_os = "linux", target_os = "android"))] + let count = count.min(cgroups::quota().max(1)); + #[cfg(not(any(target_os = "linux", target_os = "android")))] + let count = count.min(usize::MAX); Ok(unsafe { NonZeroUsize::new_unchecked(count) }) } } } else if #[cfg(any( - target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd", target_os = "netbsd", ))] { use crate::ptr; - #[cfg(target_os = "freebsd")] - { - let mut set: libc::cpuset_t = unsafe { mem::zeroed() }; - unsafe { - if libc::cpuset_getaffinity( - libc::CPU_LEVEL_WHICH, - libc::CPU_WHICH_PID, - -1, - mem::size_of::(), - &mut set, - ) == 0 { - let count = libc::CPU_COUNT(&set) as usize; - if count > 0 { - return Ok(NonZeroUsize::new_unchecked(count)); - } - } - } - } - #[cfg(target_os = "netbsd")] { unsafe {