Skip to content

Commit ad47c23

Browse files
committed
Fall back to _SC_NPROCESSORS_ONLN if sched_getaffinity returns an empty mask
1 parent a6d8724 commit ad47c23

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

library/std/src/sys/unix/thread.rs

+18-6
Original file line numberDiff line numberDiff line change
@@ -316,25 +316,37 @@ pub fn available_parallelism() -> io::Result<NonZeroUsize> {
316316
target_os = "solaris",
317317
target_os = "illumos",
318318
))] {
319+
#[allow(unused_assignments)]
320+
let mut quota = usize::MAX;
321+
319322
#[cfg(any(target_os = "android", target_os = "linux"))]
320323
{
321-
let quota = cgroups::quota().max(1);
324+
quota = cgroups::quota().max(1);
322325
let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
323326
unsafe {
324327
if libc::sched_getaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mut set) == 0 {
325328
let count = libc::CPU_COUNT(&set) as usize;
326329
let count = count.min(quota);
327-
// reported to occur on MIPS kernels older than our minimum supported kernel version for those targets
328-
let count = NonZeroUsize::new(count)
329-
.expect("CPU count must be > 0. This may be a bug in sched_getaffinity(); try upgrading the kernel.");
330-
return Ok(count);
330+
331+
// According to sched_getaffinity's API it should always be non-zero, but
332+
// some old MIPS kernels were buggy and zero-initialized the mask if
333+
// none was explicitly set.
334+
// In that case we use the sysconf fallback.
335+
if let Some(count) = NonZeroUsize::new(count) {
336+
return Ok(count)
337+
}
331338
}
332339
}
333340
}
334341
match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
335342
-1 => Err(io::Error::last_os_error()),
336343
0 => Err(io::const_io_error!(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform")),
337-
cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) }),
344+
cpus => {
345+
let count = cpus as usize;
346+
// Cover the unusual situation where we were able to get the quota but not the affinity mask
347+
let count = count.min(quota);
348+
Ok(unsafe { NonZeroUsize::new_unchecked(count) })
349+
}
338350
}
339351
} else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd"))] {
340352
use crate::ptr;

0 commit comments

Comments
 (0)