@@ -316,25 +316,37 @@ pub fn available_parallelism() -> io::Result<NonZeroUsize> {
316
316
target_os = "solaris" ,
317
317
target_os = "illumos" ,
318
318
) ) ] {
319
+ #[ allow( unused_assignments) ]
320
+ let mut quota = usize :: MAX ;
321
+
319
322
#[ cfg( any( target_os = "android" , target_os = "linux" ) ) ]
320
323
{
321
- let quota = cgroups:: quota( ) . max( 1 ) ;
324
+ quota = cgroups:: quota( ) . max( 1 ) ;
322
325
let mut set: libc:: cpu_set_t = unsafe { mem:: zeroed( ) } ;
323
326
unsafe {
324
327
if libc:: sched_getaffinity( 0 , mem:: size_of:: <libc:: cpu_set_t>( ) , & mut set) == 0 {
325
328
let count = libc:: CPU_COUNT ( & set) as usize ;
326
329
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
+ }
331
338
}
332
339
}
333
340
}
334
341
match unsafe { libc:: sysconf( libc:: _SC_NPROCESSORS_ONLN) } {
335
342
-1 => Err ( io:: Error :: last_os_error( ) ) ,
336
343
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
+ }
338
350
}
339
351
} else if #[ cfg( any( target_os = "freebsd" , target_os = "dragonfly" , target_os = "netbsd" ) ) ] {
340
352
use crate :: ptr;
0 commit comments