Skip to content

Commit faf13dd

Browse files
authored
Rollup merge of #116038 - the8472:panic-on-sched_getaffinity-bug, r=cuviper
Fall back to _SC_NPROCESSORS_ONLN if sched_getaffinity returns an empty mask Followup to #115946 A gentler fix for #115868, one that doesn't panic, [suggested on zulip](https://rust-lang.zulipchat.com/#narrow/stream/259402-t-libs.2Fmeetings/topic/Meeting.202023-09-19/near/391942927) In that situation - on the buggy kernel versions - a zero-mask means no affinities have been set so `_SC_NPROCESSORS_ONLN` provides the right value.
2 parents 06608c7 + 31cfa4a commit faf13dd

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

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

+19-6
Original file line numberDiff line numberDiff line change
@@ -318,25 +318,38 @@ pub fn available_parallelism() -> io::Result<NonZeroUsize> {
318318
target_os = "solaris",
319319
target_os = "illumos",
320320
))] {
321+
#[allow(unused_assignments)]
322+
#[allow(unused_mut)]
323+
let mut quota = usize::MAX;
324+
321325
#[cfg(any(target_os = "android", target_os = "linux"))]
322326
{
323-
let quota = cgroups::quota().max(1);
327+
quota = cgroups::quota().max(1);
324328
let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
325329
unsafe {
326330
if libc::sched_getaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mut set) == 0 {
327331
let count = libc::CPU_COUNT(&set) as usize;
328332
let count = count.min(quota);
329-
// reported to occur on MIPS kernels older than our minimum supported kernel version for those targets
330-
let count = NonZeroUsize::new(count)
331-
.expect("CPU count must be > 0. This may be a bug in sched_getaffinity(); try upgrading the kernel.");
332-
return Ok(count);
333+
334+
// According to sched_getaffinity's API it should always be non-zero, but
335+
// some old MIPS kernels were buggy and zero-initialized the mask if
336+
// none was explicitly set.
337+
// In that case we use the sysconf fallback.
338+
if let Some(count) = NonZeroUsize::new(count) {
339+
return Ok(count)
340+
}
333341
}
334342
}
335343
}
336344
match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
337345
-1 => Err(io::Error::last_os_error()),
338346
0 => Err(io::const_io_error!(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform")),
339-
cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) }),
347+
cpus => {
348+
let count = cpus as usize;
349+
// Cover the unusual situation where we were able to get the quota but not the affinity mask
350+
let count = count.min(quota);
351+
Ok(unsafe { NonZeroUsize::new_unchecked(count) })
352+
}
340353
}
341354
} else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd"))] {
342355
use crate::ptr;

0 commit comments

Comments
 (0)