std/sys/pal/unix/
thread.rs

1use crate::ffi::CStr;
2use crate::mem::{self, ManuallyDrop};
3use crate::num::NonZero;
4#[cfg(all(target_os = "linux", target_env = "gnu"))]
5use crate::sys::weak::dlsym;
6#[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto",))]
7use crate::sys::weak::weak;
8use crate::sys::{os, stack_overflow};
9use crate::time::Duration;
10use crate::{cmp, io, ptr};
11#[cfg(not(any(target_os = "l4re", target_os = "vxworks", target_os = "espidf")))]
12pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
13#[cfg(target_os = "l4re")]
14pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024;
15#[cfg(target_os = "vxworks")]
16pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 1024;
17#[cfg(target_os = "espidf")]
18pub const DEFAULT_MIN_STACK_SIZE: usize = 0; // 0 indicates that the stack size configured in the ESP-IDF menuconfig system should be used
19
20#[cfg(target_os = "fuchsia")]
21mod zircon {
22    type zx_handle_t = u32;
23    type zx_status_t = i32;
24    pub const ZX_PROP_NAME: u32 = 3;
25
26    unsafe extern "C" {
27        pub fn zx_object_set_property(
28            handle: zx_handle_t,
29            property: u32,
30            value: *const libc::c_void,
31            value_size: libc::size_t,
32        ) -> zx_status_t;
33        pub fn zx_thread_self() -> zx_handle_t;
34    }
35}
36
37pub struct Thread {
38    id: libc::pthread_t,
39}
40
41// Some platforms may have pthread_t as a pointer in which case we still want
42// a thread to be Send/Sync
43unsafe impl Send for Thread {}
44unsafe impl Sync for Thread {}
45
46impl Thread {
47    // unsafe: see thread::Builder::spawn_unchecked for safety requirements
48    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
49    pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
50        let p = Box::into_raw(Box::new(p));
51        let mut native: libc::pthread_t = mem::zeroed();
52        let mut attr: mem::MaybeUninit<libc::pthread_attr_t> = mem::MaybeUninit::uninit();
53        assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0);
54
55        #[cfg(target_os = "espidf")]
56        if stack > 0 {
57            // Only set the stack if a non-zero value is passed
58            // 0 is used as an indication that the default stack size configured in the ESP-IDF menuconfig system should be used
59            assert_eq!(
60                libc::pthread_attr_setstacksize(
61                    attr.as_mut_ptr(),
62                    cmp::max(stack, min_stack_size(attr.as_ptr()))
63                ),
64                0
65            );
66        }
67
68        #[cfg(not(target_os = "espidf"))]
69        {
70            let stack_size = cmp::max(stack, min_stack_size(attr.as_ptr()));
71
72            match libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size) {
73                0 => {}
74                n => {
75                    assert_eq!(n, libc::EINVAL);
76                    // EINVAL means |stack_size| is either too small or not a
77                    // multiple of the system page size. Because it's definitely
78                    // >= PTHREAD_STACK_MIN, it must be an alignment issue.
79                    // Round up to the nearest page and try again.
80                    let page_size = os::page_size();
81                    let stack_size =
82                        (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
83                    assert_eq!(libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size), 0);
84                }
85            };
86        }
87
88        let ret = libc::pthread_create(&mut native, attr.as_ptr(), thread_start, p as *mut _);
89        // Note: if the thread creation fails and this assert fails, then p will
90        // be leaked. However, an alternative design could cause double-free
91        // which is clearly worse.
92        assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0);
93
94        return if ret != 0 {
95            // The thread failed to start and as a result p was not consumed. Therefore, it is
96            // safe to reconstruct the box so that it gets deallocated.
97            drop(Box::from_raw(p));
98            Err(io::Error::from_raw_os_error(ret))
99        } else {
100            Ok(Thread { id: native })
101        };
102
103        extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
104            unsafe {
105                // Next, set up our stack overflow handler which may get triggered if we run
106                // out of stack.
107                let _handler = stack_overflow::Handler::new();
108                // Finally, let's run some code.
109                Box::from_raw(main as *mut Box<dyn FnOnce()>)();
110            }
111            ptr::null_mut()
112        }
113    }
114
115    pub fn yield_now() {
116        let ret = unsafe { libc::sched_yield() };
117        debug_assert_eq!(ret, 0);
118    }
119
120    #[cfg(target_os = "android")]
121    pub fn set_name(name: &CStr) {
122        const PR_SET_NAME: libc::c_int = 15;
123        unsafe {
124            let res = libc::prctl(
125                PR_SET_NAME,
126                name.as_ptr(),
127                0 as libc::c_ulong,
128                0 as libc::c_ulong,
129                0 as libc::c_ulong,
130            );
131            // We have no good way of propagating errors here, but in debug-builds let's check that this actually worked.
132            debug_assert_eq!(res, 0);
133        }
134    }
135
136    #[cfg(any(
137        target_os = "linux",
138        target_os = "freebsd",
139        target_os = "dragonfly",
140        target_os = "nuttx"
141    ))]
142    pub fn set_name(name: &CStr) {
143        unsafe {
144            cfg_if::cfg_if! {
145                if #[cfg(target_os = "linux")] {
146                    // Linux limits the allowed length of the name.
147                    const TASK_COMM_LEN: usize = 16;
148                    let name = truncate_cstr::<{ TASK_COMM_LEN }>(name);
149                } else {
150                    // FreeBSD, DragonFly BSD and NuttX do not enforce length limits.
151                }
152            };
153            // Available since glibc 2.12, musl 1.1.16, and uClibc 1.0.20 for Linux,
154            // FreeBSD 12.2 and 13.0, and DragonFly BSD 6.0.
155            let res = libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());
156            // We have no good way of propagating errors here, but in debug-builds let's check that this actually worked.
157            debug_assert_eq!(res, 0);
158        }
159    }
160
161    #[cfg(target_os = "openbsd")]
162    pub fn set_name(name: &CStr) {
163        unsafe {
164            libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
165        }
166    }
167
168    #[cfg(target_vendor = "apple")]
169    pub fn set_name(name: &CStr) {
170        unsafe {
171            let name = truncate_cstr::<{ libc::MAXTHREADNAMESIZE }>(name);
172            let res = libc::pthread_setname_np(name.as_ptr());
173            // We have no good way of propagating errors here, but in debug-builds let's check that this actually worked.
174            debug_assert_eq!(res, 0);
175        }
176    }
177
178    #[cfg(target_os = "netbsd")]
179    pub fn set_name(name: &CStr) {
180        unsafe {
181            let res = libc::pthread_setname_np(
182                libc::pthread_self(),
183                c"%s".as_ptr(),
184                name.as_ptr() as *mut libc::c_void,
185            );
186            debug_assert_eq!(res, 0);
187        }
188    }
189
190    #[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto"))]
191    pub fn set_name(name: &CStr) {
192        weak! {
193            fn pthread_setname_np(
194                libc::pthread_t, *const libc::c_char
195            ) -> libc::c_int
196        }
197
198        if let Some(f) = pthread_setname_np.get() {
199            #[cfg(target_os = "nto")]
200            const THREAD_NAME_MAX: usize = libc::_NTO_THREAD_NAME_MAX as usize;
201            #[cfg(any(target_os = "solaris", target_os = "illumos"))]
202            const THREAD_NAME_MAX: usize = 32;
203
204            let name = truncate_cstr::<{ THREAD_NAME_MAX }>(name);
205            let res = unsafe { f(libc::pthread_self(), name.as_ptr()) };
206            debug_assert_eq!(res, 0);
207        }
208    }
209
210    #[cfg(target_os = "fuchsia")]
211    pub fn set_name(name: &CStr) {
212        use self::zircon::*;
213        unsafe {
214            zx_object_set_property(
215                zx_thread_self(),
216                ZX_PROP_NAME,
217                name.as_ptr() as *const libc::c_void,
218                name.to_bytes().len(),
219            );
220        }
221    }
222
223    #[cfg(target_os = "haiku")]
224    pub fn set_name(name: &CStr) {
225        unsafe {
226            let thread_self = libc::find_thread(ptr::null_mut());
227            let res = libc::rename_thread(thread_self, name.as_ptr());
228            // We have no good way of propagating errors here, but in debug-builds let's check that this actually worked.
229            debug_assert_eq!(res, libc::B_OK);
230        }
231    }
232
233    #[cfg(target_os = "vxworks")]
234    pub fn set_name(name: &CStr) {
235        // FIXME(libc): adding real STATUS, ERROR type eventually.
236        unsafe extern "C" {
237            fn taskNameSet(task_id: libc::TASK_ID, task_name: *mut libc::c_char) -> libc::c_int;
238        }
239
240        //  VX_TASK_NAME_LEN is 31 in VxWorks 7.
241        const VX_TASK_NAME_LEN: usize = 31;
242
243        let mut name = truncate_cstr::<{ VX_TASK_NAME_LEN }>(name);
244        let res = unsafe { taskNameSet(libc::taskIdSelf(), name.as_mut_ptr()) };
245        debug_assert_eq!(res, libc::OK);
246    }
247
248    #[cfg(any(
249        target_env = "newlib",
250        target_os = "l4re",
251        target_os = "emscripten",
252        target_os = "redox",
253        target_os = "hurd",
254        target_os = "aix",
255    ))]
256    pub fn set_name(_name: &CStr) {
257        // Newlib and Emscripten have no way to set a thread name.
258    }
259
260    #[cfg(not(target_os = "espidf"))]
261    pub fn sleep(dur: Duration) {
262        let mut secs = dur.as_secs();
263        let mut nsecs = dur.subsec_nanos() as _;
264
265        // If we're awoken with a signal then the return value will be -1 and
266        // nanosleep will fill in `ts` with the remaining time.
267        unsafe {
268            while secs > 0 || nsecs > 0 {
269                let mut ts = libc::timespec {
270                    tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
271                    tv_nsec: nsecs,
272                };
273                secs -= ts.tv_sec as u64;
274                let ts_ptr = &raw mut ts;
275                if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
276                    assert_eq!(os::errno(), libc::EINTR);
277                    secs += ts.tv_sec as u64;
278                    nsecs = ts.tv_nsec;
279                } else {
280                    nsecs = 0;
281                }
282            }
283        }
284    }
285
286    #[cfg(target_os = "espidf")]
287    pub fn sleep(dur: Duration) {
288        // ESP-IDF does not have `nanosleep`, so we use `usleep` instead.
289        // As per the documentation of `usleep`, it is expected to support
290        // sleep times as big as at least up to 1 second.
291        //
292        // ESP-IDF does support almost up to `u32::MAX`, but due to a potential integer overflow in its
293        // `usleep` implementation
294        // (https://github.com/espressif/esp-idf/blob/d7ca8b94c852052e3bc33292287ef4dd62c9eeb1/components/newlib/time.c#L210),
295        // we limit the sleep time to the maximum one that would not cause the underlying `usleep` implementation to overflow
296        // (`portTICK_PERIOD_MS` can be anything between 1 to 1000, and is 10 by default).
297        const MAX_MICROS: u32 = u32::MAX - 1_000_000 - 1;
298
299        // Add any nanoseconds smaller than a microsecond as an extra microsecond
300        // so as to comply with the `std::thread::sleep` contract which mandates
301        // implementations to sleep for _at least_ the provided `dur`.
302        // We can't overflow `micros` as it is a `u128`, while `Duration` is a pair of
303        // (`u64` secs, `u32` nanos), where the nanos are strictly smaller than 1 second
304        // (i.e. < 1_000_000_000)
305        let mut micros = dur.as_micros() + if dur.subsec_nanos() % 1_000 > 0 { 1 } else { 0 };
306
307        while micros > 0 {
308            let st = if micros > MAX_MICROS as u128 { MAX_MICROS } else { micros as u32 };
309            unsafe {
310                libc::usleep(st);
311            }
312
313            micros -= st as u128;
314        }
315    }
316
317    pub fn join(self) {
318        let id = self.into_id();
319        let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) };
320        assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
321    }
322
323    pub fn id(&self) -> libc::pthread_t {
324        self.id
325    }
326
327    pub fn into_id(self) -> libc::pthread_t {
328        ManuallyDrop::new(self).id
329    }
330}
331
332impl Drop for Thread {
333    fn drop(&mut self) {
334        let ret = unsafe { libc::pthread_detach(self.id) };
335        debug_assert_eq!(ret, 0);
336    }
337}
338
339#[cfg(any(
340    target_os = "linux",
341    target_os = "nto",
342    target_os = "solaris",
343    target_os = "illumos",
344    target_os = "vxworks",
345    target_vendor = "apple",
346))]
347fn truncate_cstr<const MAX_WITH_NUL: usize>(cstr: &CStr) -> [libc::c_char; MAX_WITH_NUL] {
348    let mut result = [0; MAX_WITH_NUL];
349    for (src, dst) in cstr.to_bytes().iter().zip(&mut result[..MAX_WITH_NUL - 1]) {
350        *dst = *src as libc::c_char;
351    }
352    result
353}
354
355pub fn available_parallelism() -> io::Result<NonZero<usize>> {
356    cfg_if::cfg_if! {
357        if #[cfg(any(
358            target_os = "android",
359            target_os = "emscripten",
360            target_os = "fuchsia",
361            target_os = "hurd",
362            target_os = "linux",
363            target_os = "aix",
364            target_vendor = "apple",
365        ))] {
366            #[allow(unused_assignments)]
367            #[allow(unused_mut)]
368            let mut quota = usize::MAX;
369
370            #[cfg(any(target_os = "android", target_os = "linux"))]
371            {
372                quota = cgroups::quota().max(1);
373                let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
374                unsafe {
375                    if libc::sched_getaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mut set) == 0 {
376                        let count = libc::CPU_COUNT(&set) as usize;
377                        let count = count.min(quota);
378
379                        // According to sched_getaffinity's API it should always be non-zero, but
380                        // some old MIPS kernels were buggy and zero-initialized the mask if
381                        // none was explicitly set.
382                        // In that case we use the sysconf fallback.
383                        if let Some(count) = NonZero::new(count) {
384                            return Ok(count)
385                        }
386                    }
387                }
388            }
389            match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
390                -1 => Err(io::Error::last_os_error()),
391                0 => Err(io::Error::UNKNOWN_THREAD_COUNT),
392                cpus => {
393                    let count = cpus as usize;
394                    // Cover the unusual situation where we were able to get the quota but not the affinity mask
395                    let count = count.min(quota);
396                    Ok(unsafe { NonZero::new_unchecked(count) })
397                }
398            }
399        } else if #[cfg(any(
400                   target_os = "freebsd",
401                   target_os = "dragonfly",
402                   target_os = "openbsd",
403                   target_os = "netbsd",
404               ))] {
405            use crate::ptr;
406
407            #[cfg(target_os = "freebsd")]
408            {
409                let mut set: libc::cpuset_t = unsafe { mem::zeroed() };
410                unsafe {
411                    if libc::cpuset_getaffinity(
412                        libc::CPU_LEVEL_WHICH,
413                        libc::CPU_WHICH_PID,
414                        -1,
415                        mem::size_of::<libc::cpuset_t>(),
416                        &mut set,
417                    ) == 0 {
418                        let count = libc::CPU_COUNT(&set) as usize;
419                        if count > 0 {
420                            return Ok(NonZero::new_unchecked(count));
421                        }
422                    }
423                }
424            }
425
426            #[cfg(target_os = "netbsd")]
427            {
428                unsafe {
429                    let set = libc::_cpuset_create();
430                    if !set.is_null() {
431                        let mut count: usize = 0;
432                        if libc::pthread_getaffinity_np(libc::pthread_self(), libc::_cpuset_size(set), set) == 0 {
433                            for i in 0..libc::cpuid_t::MAX {
434                                match libc::_cpuset_isset(i, set) {
435                                    -1 => break,
436                                    0 => continue,
437                                    _ => count = count + 1,
438                                }
439                            }
440                        }
441                        libc::_cpuset_destroy(set);
442                        if let Some(count) = NonZero::new(count) {
443                            return Ok(count);
444                        }
445                    }
446                }
447            }
448
449            let mut cpus: libc::c_uint = 0;
450            let mut cpus_size = crate::mem::size_of_val(&cpus);
451
452            unsafe {
453                cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
454            }
455
456            // Fallback approach in case of errors or no hardware threads.
457            if cpus < 1 {
458                let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
459                let res = unsafe {
460                    libc::sysctl(
461                        mib.as_mut_ptr(),
462                        2,
463                        (&raw mut cpus) as *mut _,
464                        (&raw mut cpus_size) as *mut _,
465                        ptr::null_mut(),
466                        0,
467                    )
468                };
469
470                // Handle errors if any.
471                if res == -1 {
472                    return Err(io::Error::last_os_error());
473                } else if cpus == 0 {
474                    return Err(io::Error::UNKNOWN_THREAD_COUNT);
475                }
476            }
477
478            Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
479        } else if #[cfg(target_os = "nto")] {
480            unsafe {
481                use libc::_syspage_ptr;
482                if _syspage_ptr.is_null() {
483                    Err(io::const_error!(io::ErrorKind::NotFound, "no syspage available"))
484                } else {
485                    let cpus = (*_syspage_ptr).num_cpu;
486                    NonZero::new(cpus as usize)
487                        .ok_or(io::Error::UNKNOWN_THREAD_COUNT)
488                }
489            }
490        } else if #[cfg(any(target_os = "solaris", target_os = "illumos"))] {
491            let mut cpus = 0u32;
492            if unsafe { libc::pset_info(libc::PS_MYID, core::ptr::null_mut(), &mut cpus, core::ptr::null_mut()) } != 0 {
493                return Err(io::Error::UNKNOWN_THREAD_COUNT);
494            }
495            Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
496        } else if #[cfg(target_os = "haiku")] {
497            // system_info cpu_count field gets the static data set at boot time with `smp_set_num_cpus`
498            // `get_system_info` calls then `smp_get_num_cpus`
499            unsafe {
500                let mut sinfo: libc::system_info = crate::mem::zeroed();
501                let res = libc::get_system_info(&mut sinfo);
502
503                if res != libc::B_OK {
504                    return Err(io::Error::UNKNOWN_THREAD_COUNT);
505                }
506
507                Ok(NonZero::new_unchecked(sinfo.cpu_count as usize))
508            }
509        } else if #[cfg(target_os = "vxworks")] {
510            // Note: there is also `vxCpuConfiguredGet`, closer to _SC_NPROCESSORS_CONF
511            // expectations than the actual cores availability.
512            unsafe extern "C" {
513                fn vxCpuEnabledGet() -> libc::cpuset_t;
514            }
515
516            // SAFETY: `vxCpuEnabledGet` always fetches a mask with at least one bit set
517            unsafe{
518                let set = vxCpuEnabledGet();
519                Ok(NonZero::new_unchecked(set.count_ones() as usize))
520            }
521        } else {
522            // FIXME: implement on Redox, l4re
523            Err(io::const_error!(io::ErrorKind::Unsupported, "getting the number of hardware threads is not supported on the target platform"))
524        }
525    }
526}
527
528#[cfg(any(target_os = "android", target_os = "linux"))]
529mod cgroups {
530    //! Currently not covered
531    //! * cgroup v2 in non-standard mountpoints
532    //! * paths containing control characters or spaces, since those would be escaped in procfs
533    //!   output and we don't unescape
534
535    use crate::borrow::Cow;
536    use crate::ffi::OsString;
537    use crate::fs::{File, exists};
538    use crate::io::{BufRead, Read};
539    use crate::os::unix::ffi::OsStringExt;
540    use crate::path::{Path, PathBuf};
541    use crate::str::from_utf8;
542
543    #[derive(PartialEq)]
544    enum Cgroup {
545        V1,
546        V2,
547    }
548
549    /// Returns cgroup CPU quota in core-equivalents, rounded down or usize::MAX if the quota cannot
550    /// be determined or is not set.
551    pub(super) fn quota() -> usize {
552        let mut quota = usize::MAX;
553        if cfg!(miri) {
554            // Attempting to open a file fails under default flags due to isolation.
555            // And Miri does not have parallelism anyway.
556            return quota;
557        }
558
559        let _: Option<()> = try {
560            let mut buf = Vec::with_capacity(128);
561            // find our place in the cgroup hierarchy
562            File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
563            let (cgroup_path, version) =
564                buf.split(|&c| c == b'\n').fold(None, |previous, line| {
565                    let mut fields = line.splitn(3, |&c| c == b':');
566                    // 2nd field is a list of controllers for v1 or empty for v2
567                    let version = match fields.nth(1) {
568                        Some(b"") => Cgroup::V2,
569                        Some(controllers)
570                            if from_utf8(controllers)
571                                .is_ok_and(|c| c.split(',').any(|c| c == "cpu")) =>
572                        {
573                            Cgroup::V1
574                        }
575                        _ => return previous,
576                    };
577
578                    // already-found v1 trumps v2 since it explicitly specifies its controllers
579                    if previous.is_some() && version == Cgroup::V2 {
580                        return previous;
581                    }
582
583                    let path = fields.last()?;
584                    // skip leading slash
585                    Some((path[1..].to_owned(), version))
586                })?;
587            let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));
588
589            quota = match version {
590                Cgroup::V1 => quota_v1(cgroup_path),
591                Cgroup::V2 => quota_v2(cgroup_path),
592            };
593        };
594
595        quota
596    }
597
598    fn quota_v2(group_path: PathBuf) -> usize {
599        let mut quota = usize::MAX;
600
601        let mut path = PathBuf::with_capacity(128);
602        let mut read_buf = String::with_capacity(20);
603
604        // standard mount location defined in file-hierarchy(7) manpage
605        let cgroup_mount = "/sys/fs/cgroup";
606
607        path.push(cgroup_mount);
608        path.push(&group_path);
609
610        path.push("cgroup.controllers");
611
612        // skip if we're not looking at cgroup2
613        if matches!(exists(&path), Err(_) | Ok(false)) {
614            return usize::MAX;
615        };
616
617        path.pop();
618
619        let _: Option<()> = try {
620            while path.starts_with(cgroup_mount) {
621                path.push("cpu.max");
622
623                read_buf.clear();
624
625                if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
626                    let raw_quota = read_buf.lines().next()?;
627                    let mut raw_quota = raw_quota.split(' ');
628                    let limit = raw_quota.next()?;
629                    let period = raw_quota.next()?;
630                    match (limit.parse::<usize>(), period.parse::<usize>()) {
631                        (Ok(limit), Ok(period)) if period > 0 => {
632                            quota = quota.min(limit / period);
633                        }
634                        _ => {}
635                    }
636                }
637
638                path.pop(); // pop filename
639                path.pop(); // pop dir
640            }
641        };
642
643        quota
644    }
645
646    fn quota_v1(group_path: PathBuf) -> usize {
647        let mut quota = usize::MAX;
648        let mut path = PathBuf::with_capacity(128);
649        let mut read_buf = String::with_capacity(20);
650
651        // Hardcode commonly used locations mentioned in the cgroups(7) manpage
652        // if that doesn't work scan mountinfo and adjust `group_path` for bind-mounts
653        let mounts: &[fn(&Path) -> Option<(_, &Path)>] = &[
654            |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu"), p)),
655            |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu,cpuacct"), p)),
656            // this can be expensive on systems with tons of mountpoints
657            // but we only get to this point when /proc/self/cgroups explicitly indicated
658            // this process belongs to a cpu-controller cgroup v1 and the defaults didn't work
659            find_mountpoint,
660        ];
661
662        for mount in mounts {
663            let Some((mount, group_path)) = mount(&group_path) else { continue };
664
665            path.clear();
666            path.push(mount.as_ref());
667            path.push(&group_path);
668
669            // skip if we guessed the mount incorrectly
670            if matches!(exists(&path), Err(_) | Ok(false)) {
671                continue;
672            }
673
674            while path.starts_with(mount.as_ref()) {
675                let mut parse_file = |name| {
676                    path.push(name);
677                    read_buf.clear();
678
679                    let f = File::open(&path);
680                    path.pop(); // restore buffer before any early returns
681                    f.ok()?.read_to_string(&mut read_buf).ok()?;
682                    let parsed = read_buf.trim().parse::<usize>().ok()?;
683
684                    Some(parsed)
685                };
686
687                let limit = parse_file("cpu.cfs_quota_us");
688                let period = parse_file("cpu.cfs_period_us");
689
690                match (limit, period) {
691                    (Some(limit), Some(period)) if period > 0 => quota = quota.min(limit / period),
692                    _ => {}
693                }
694
695                path.pop();
696            }
697
698            // we passed the try_exists above so we should have traversed the correct hierarchy
699            // when reaching this line
700            break;
701        }
702
703        quota
704    }
705
706    /// Scan mountinfo for cgroup v1 mountpoint with a cpu controller
707    ///
708    /// If the cgroupfs is a bind mount then `group_path` is adjusted to skip
709    /// over the already-included prefix
710    fn find_mountpoint(group_path: &Path) -> Option<(Cow<'static, str>, &Path)> {
711        let mut reader = File::open_buffered("/proc/self/mountinfo").ok()?;
712        let mut line = String::with_capacity(256);
713        loop {
714            line.clear();
715            if reader.read_line(&mut line).ok()? == 0 {
716                break;
717            }
718
719            let line = line.trim();
720            let mut items = line.split(' ');
721
722            let sub_path = items.nth(3)?;
723            let mount_point = items.next()?;
724            let mount_opts = items.next_back()?;
725            let filesystem_type = items.nth_back(1)?;
726
727            if filesystem_type != "cgroup" || !mount_opts.split(',').any(|opt| opt == "cpu") {
728                // not a cgroup / not a cpu-controller
729                continue;
730            }
731
732            let sub_path = Path::new(sub_path).strip_prefix("/").ok()?;
733
734            if !group_path.starts_with(sub_path) {
735                // this is a bind-mount and the bound subdirectory
736                // does not contain the cgroup this process belongs to
737                continue;
738            }
739
740            let trimmed_group_path = group_path.strip_prefix(sub_path).ok()?;
741
742            return Some((Cow::Owned(mount_point.to_owned()), trimmed_group_path));
743        }
744
745        None
746    }
747}
748
749// glibc >= 2.15 has a __pthread_get_minstack() function that returns
750// PTHREAD_STACK_MIN plus bytes needed for thread-local storage.
751// We need that information to avoid blowing up when a small stack
752// is created in an application with big thread-local storage requirements.
753// See #6233 for rationale and details.
754#[cfg(all(target_os = "linux", target_env = "gnu"))]
755unsafe fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
756    // We use dlsym to avoid an ELF version dependency on GLIBC_PRIVATE. (#23628)
757    // We shouldn't really be using such an internal symbol, but there's currently
758    // no other way to account for the TLS size.
759    dlsym!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
760
761    match __pthread_get_minstack.get() {
762        None => libc::PTHREAD_STACK_MIN,
763        Some(f) => unsafe { f(attr) },
764    }
765}
766
767// No point in looking up __pthread_get_minstack() on non-glibc platforms.
768#[cfg(all(
769    not(all(target_os = "linux", target_env = "gnu")),
770    not(any(target_os = "netbsd", target_os = "nuttx"))
771))]
772unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
773    libc::PTHREAD_STACK_MIN
774}
775
776#[cfg(any(target_os = "netbsd", target_os = "nuttx"))]
777unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
778    static STACK: crate::sync::OnceLock<usize> = crate::sync::OnceLock::new();
779
780    *STACK.get_or_init(|| {
781        let mut stack = unsafe { libc::sysconf(libc::_SC_THREAD_STACK_MIN) };
782        if stack < 0 {
783            stack = 2048; // just a guess
784        }
785
786        stack as usize
787    })
788}