1#[cfg(not(any(
2 target_env = "newlib",
3 target_os = "l4re",
4 target_os = "emscripten",
5 target_os = "redox",
6 target_os = "hurd",
7 target_os = "aix",
8 target_os = "wasi",
9)))]
10use crate::ffi::CStr;
11use crate::mem::{self, DropGuard, ManuallyDrop};
12use crate::num::NonZero;
13use crate::pin::pin;
14use crate::sys::helpers::COpaque;
15#[cfg(all(target_os = "linux", target_env = "gnu"))]
16use crate::sys::weak::dlsym;
17#[cfg(any(
18 target_os = "solaris",
19 target_os = "illumos",
20 target_os = "nto",
21 target_os = "qnx",
22))]
23use crate::sys::weak::weak;
24use crate::thread::ThreadInit;
25use crate::time::Duration;
26use crate::{cmp, io, ptr, sys};
27#[cfg(not(any(
28 target_os = "l4re",
29 target_os = "vxworks",
30 target_os = "espidf",
31 target_os = "nuttx"
32)))]
33pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
34#[cfg(target_os = "l4re")]
35pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024;
36#[cfg(target_os = "vxworks")]
37pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 1024;
38#[cfg(any(target_os = "espidf", target_os = "nuttx"))]
39pub const DEFAULT_MIN_STACK_SIZE: usize = 0; pub struct Thread {
42 id: libc::pthread_t,
43}
44
45unsafe impl Send for Thread {}
48unsafe impl Sync for Thread {}
49
50impl Thread {
51 #[cfg_attr(miri, track_caller)] pub unsafe fn new(stack: usize, init: Box<ThreadInit>) -> io::Result<Thread> {
54 let data = init;
55 let attr = pin!(COpaque::<libc::pthread_attr_t>::uninit());
56 let attr = attr.into_ref();
58
59 assert_eq!(libc::pthread_attr_init(attr.get()), 0);
60 let attr =
61 DropGuard::new(attr, |attr| assert_eq!(libc::pthread_attr_destroy(attr.get()), 0));
62
63 #[cfg(any(target_os = "espidf", target_os = "nuttx"))]
64 if stack > 0 {
65 assert_eq!(
68 libc::pthread_attr_setstacksize(
69 attr.get(),
70 cmp::max(stack, min_stack_size(attr.get()))
71 ),
72 0
73 );
74 }
75
76 #[cfg(not(any(target_os = "espidf", target_os = "nuttx")))]
77 {
78 let stack_size = cmp::max(stack, min_stack_size(attr.get()));
79
80 match libc::pthread_attr_setstacksize(attr.get(), stack_size) {
81 0 => {}
82 n => {
83 assert_eq!(n, libc::EINVAL);
84 let page_size = sys::pal::conf::page_size();
89 let stack_size =
90 (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
91
92 if libc::pthread_attr_setstacksize(attr.get(), stack_size) != 0 {
96 return Err(io::const_error!(
97 io::ErrorKind::InvalidInput,
98 "invalid stack size"
99 ));
100 }
101 }
102 };
103 }
104
105 let data = Box::into_raw(data);
106 let mut native: libc::pthread_t = mem::zeroed();
107 let ret = libc::pthread_create(&mut native, attr.get(), thread_start, data as *mut _);
108 return if ret == 0 {
109 Ok(Thread { id: native })
110 } else {
111 drop(Box::from_raw(data));
114 Err(io::Error::from_raw_os_error(ret))
115 };
116
117 extern "C" fn thread_start(data: *mut libc::c_void) -> *mut libc::c_void {
118 unsafe {
119 let init = Box::from_raw(data as *mut ThreadInit);
121 let rust_start = init.init();
122
123 let _handler = sys::stack_overflow::Handler::new();
126
127 rust_start();
128 }
129 ptr::null_mut()
130 }
131 }
132
133 pub fn join(self) {
134 let id = self.into_id();
135 let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) };
136 assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
137 }
138
139 #[cfg(not(target_os = "wasi"))]
140 pub fn id(&self) -> libc::pthread_t {
141 self.id
142 }
143
144 pub fn into_id(self) -> libc::pthread_t {
145 ManuallyDrop::new(self).id
146 }
147}
148
149impl Drop for Thread {
150 fn drop(&mut self) {
151 let ret = unsafe { libc::pthread_detach(self.id) };
152 debug_assert_eq!(ret, 0);
153 }
154}
155
156pub fn available_parallelism() -> io::Result<NonZero<usize>> {
157 cfg_select! {
158 any(
159 target_os = "android",
160 target_os = "emscripten",
161 target_os = "fuchsia",
162 target_os = "hurd",
163 target_os = "linux",
164 target_os = "aix",
165 target_os = "freebsd",
166 target_vendor = "apple",
167 target_os = "cygwin",
168 target_os = "redox",
169 target_os = "wasi",
170 ) => {
171 #[allow(unused_assignments)]
172 #[allow(unused_mut)]
173 let mut quota = usize::MAX;
174
175 #[cfg(any(target_os = "android", target_os = "linux"))]
176 {
177 quota = cgroups::quota().max(1);
178 }
179
180 #[cfg(any(target_os = "android", target_os = "linux", target_os = "freebsd"))]
181 {
182 #[cfg(not(target_os = "freebsd"))]
183 type Cpuset = libc::cpu_set_t;
184 #[cfg(target_os = "freebsd")]
185 type Cpuset = libc::cpuset_t;
186 let mut set: Cpuset = unsafe { mem::zeroed() };
187 unsafe {
188 if libc::sched_getaffinity(0, size_of::<Cpuset>(), &mut set) == 0 {
189 let count = libc::CPU_COUNT(&set) as usize;
190 let count = count.min(quota);
191
192 if let Some(count) = NonZero::new(count) {
197 return Ok(count);
198 }
199 }
200 }
201 }
202 match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
203 -1 => Err(io::Error::last_os_error()),
204 0 => Err(io::Error::UNKNOWN_THREAD_COUNT),
205 cpus => {
206 let count = cpus as usize;
207 let count = count.min(quota);
209 Ok(unsafe { NonZero::new_unchecked(count) })
210 }
211 }
212 }
213 any(target_os = "dragonfly", target_os = "openbsd", target_os = "netbsd") => {
214 use crate::ptr;
215
216 #[cfg(target_os = "netbsd")]
217 {
218 unsafe {
219 let set = libc::_cpuset_create();
220 if !set.is_null() {
221 let mut count: usize = 0;
222 if libc::pthread_getaffinity_np(
223 libc::pthread_self(),
224 libc::_cpuset_size(set),
225 set,
226 ) == 0
227 {
228 for i in 0..libc::cpuid_t::MAX {
229 match libc::_cpuset_isset(i, set) {
230 -1 => break,
231 0 => continue,
232 _ => count = count + 1,
233 }
234 }
235 }
236 libc::_cpuset_destroy(set);
237 if let Some(count) = NonZero::new(count) {
238 return Ok(count);
239 }
240 }
241 }
242 }
243
244 let mut cpus: libc::c_uint = 0;
245 let mut cpus_size = size_of_val(&cpus);
246
247 unsafe {
248 cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
249 }
250
251 if cpus < 1 {
253 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
254 let res = unsafe {
255 libc::sysctl(
256 mib.as_mut_ptr(),
257 2,
258 (&raw mut cpus) as *mut _,
259 (&raw mut cpus_size) as *mut _,
260 ptr::null_mut(),
261 0,
262 )
263 };
264
265 if res == -1 {
267 return Err(io::Error::last_os_error());
268 } else if cpus == 0 {
269 return Err(io::Error::UNKNOWN_THREAD_COUNT);
270 }
271 }
272
273 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
274 }
275 any(target_os = "nto", target_os = "qnx") => unsafe {
276 use libc::_syspage_ptr;
277 if _syspage_ptr.is_null() {
278 Err(io::const_error!(io::ErrorKind::NotFound, "no syspage available"))
279 } else {
280 let cpus = (*_syspage_ptr).num_cpu;
281 NonZero::new(cpus as usize).ok_or(io::Error::UNKNOWN_THREAD_COUNT)
282 }
283 },
284 any(target_os = "solaris", target_os = "illumos") => {
285 let mut cpus = 0u32;
286 if unsafe {
287 libc::pset_info(
288 libc::PS_MYID,
289 core::ptr::null_mut(),
290 &mut cpus,
291 core::ptr::null_mut(),
292 )
293 } != 0
294 {
295 return Err(io::Error::UNKNOWN_THREAD_COUNT);
296 }
297 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
298 }
299 target_os = "haiku" => {
300 unsafe {
303 let mut sinfo: libc::system_info = crate::mem::zeroed();
304 let res = libc::get_system_info(&mut sinfo);
305
306 if res != libc::B_OK {
307 return Err(io::Error::UNKNOWN_THREAD_COUNT);
308 }
309
310 Ok(NonZero::new_unchecked(sinfo.cpu_count as usize))
311 }
312 }
313 target_os = "vxworks" => {
314 unsafe {
319 let set = libc::vxCpuEnabledGet();
320 Ok(NonZero::new_unchecked(set.count_ones() as usize))
321 }
322 }
323 _ => {
324 Err(io::const_error!(
326 io::ErrorKind::Unsupported,
327 "getting the number of hardware threads is not supported on the target platform"
328 ))
329 }
330 }
331}
332
333pub fn current_os_id() -> Option<u64> {
334 cfg_select! {
340 any(target_os = "android", target_os = "linux") => {
342 use crate::sys::pal::weak::syscall;
343
344 syscall!(
347 fn gettid() -> libc::pid_t;
348 );
349
350 let id: libc::pid_t = unsafe { gettid() };
352 Some(id as u64)
353 }
354 any(target_os = "nto", target_os = "qnx") => {
355 let id: libc::pid_t = unsafe { libc::gettid() };
357 Some(id as u64)
358 }
359 target_os = "openbsd" => {
360 let id: libc::pid_t = unsafe { libc::getthrid() };
362 Some(id as u64)
363 }
364 target_os = "freebsd" => {
365 let id: libc::c_int = unsafe { libc::pthread_getthreadid_np() };
367 Some(id as u64)
368 }
369 target_os = "netbsd" => {
370 let id: libc::lwpid_t = unsafe { libc::_lwp_self() };
372 Some(id as u64)
373 }
374 any(target_os = "illumos", target_os = "solaris") => {
375 let id: libc::pthread_t = unsafe { libc::pthread_self() };
378 Some(id as u64)
379 }
380 target_vendor = "apple" => {
381 let mut id = 0u64;
383 let status: libc::c_int = unsafe { libc::pthread_threadid_np(0, &mut id) };
385 if status == 0 { Some(id) } else { None }
386 }
387 _ => None,
389 }
390}
391
392#[cfg(any(
393 target_os = "linux",
394 target_os = "nto",
395 target_os = "qnx",
396 target_os = "solaris",
397 target_os = "illumos",
398 target_os = "vxworks",
399 target_os = "cygwin",
400 target_vendor = "apple",
401 target_os = "netbsd",
402))]
403fn truncate_cstr<const MAX_WITH_NUL: usize>(cstr: &CStr) -> [libc::c_char; MAX_WITH_NUL] {
404 let mut result = [0; MAX_WITH_NUL];
405 for (src, dst) in cstr.to_bytes().iter().zip(&mut result[..MAX_WITH_NUL - 1]) {
406 *dst = *src as libc::c_char;
407 }
408 result
409}
410
411#[cfg(target_os = "android")]
412pub fn set_name(name: &CStr) {
413 const PR_SET_NAME: libc::c_int = 15;
414 unsafe {
415 let res = libc::prctl(
416 PR_SET_NAME,
417 name.as_ptr(),
418 0 as libc::c_ulong,
419 0 as libc::c_ulong,
420 0 as libc::c_ulong,
421 );
422 debug_assert_eq!(res, 0);
424 }
425}
426
427#[cfg(any(
428 target_os = "linux",
429 target_os = "freebsd",
430 target_os = "dragonfly",
431 target_os = "nuttx",
432 target_os = "cygwin"
433))]
434pub fn set_name(name: &CStr) {
435 unsafe {
436 cfg_select! {
437 any(target_os = "linux", target_os = "cygwin") => {
438 const TASK_COMM_LEN: usize = 16;
440 let name = truncate_cstr::<{ TASK_COMM_LEN }>(name);
441 }
442 _ => {
443 }
445 };
446 let res = libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());
449 debug_assert_eq!(res, 0);
451 }
452}
453
454#[cfg(target_os = "openbsd")]
455pub fn set_name(name: &CStr) {
456 unsafe {
457 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
458 }
459}
460
461#[cfg(target_vendor = "apple")]
462pub fn set_name(name: &CStr) {
463 unsafe {
464 let name = truncate_cstr::<{ libc::MAXTHREADNAMESIZE }>(name);
465 let res = libc::pthread_setname_np(name.as_ptr());
466 debug_assert_eq!(res, 0);
468 }
469}
470
471#[cfg(target_os = "netbsd")]
472pub fn set_name(name: &CStr) {
473 const PTHREAD_MAX_NAMELEN_NP: usize = 32;
476
477 unsafe {
478 let name = truncate_cstr::<{ PTHREAD_MAX_NAMELEN_NP }>(name);
479 let res = libc::pthread_setname_np(
480 libc::pthread_self(),
481 c"%s".as_ptr(),
482 name.as_ptr() as *mut libc::c_void,
483 );
484 debug_assert_eq!(res, 0);
485 }
486}
487
488#[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto", target_os = "qnx"))]
489pub fn set_name(name: &CStr) {
490 weak!(
491 fn pthread_setname_np(thread: libc::pthread_t, name: *const libc::c_char) -> libc::c_int;
492 );
493
494 if let Some(f) = pthread_setname_np.get() {
495 #[cfg(any(target_os = "nto", target_os = "qnx"))]
496 const THREAD_NAME_MAX: usize = libc::_NTO_THREAD_NAME_MAX as usize;
497 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
498 const THREAD_NAME_MAX: usize = 32;
499
500 let name = truncate_cstr::<{ THREAD_NAME_MAX }>(name);
501 let res = unsafe { f(libc::pthread_self(), name.as_ptr()) };
502 debug_assert_eq!(res, 0);
503 }
504}
505
506#[cfg(target_os = "fuchsia")]
507pub fn set_name(name: &CStr) {
508 use crate::sys::pal::fuchsia::*;
509 unsafe {
510 zx_object_set_property(
511 zx_thread_self(),
512 ZX_PROP_NAME,
513 name.as_ptr() as *const libc::c_void,
514 name.to_bytes().len(),
515 );
516 }
517}
518
519#[cfg(target_os = "haiku")]
520pub fn set_name(name: &CStr) {
521 unsafe {
522 let thread_self = libc::find_thread(ptr::null_mut());
523 let res = libc::rename_thread(thread_self, name.as_ptr());
524 debug_assert_eq!(res, libc::B_OK);
526 }
527}
528
529#[cfg(target_os = "vxworks")]
530pub fn set_name(name: &CStr) {
531 let mut name = truncate_cstr::<{ (libc::VX_TASK_RENAME_LENGTH - 1) as usize }>(name);
532 let res = unsafe { libc::taskNameSet(libc::taskIdSelf(), name.as_mut_ptr()) };
533 debug_assert_eq!(res, libc::OK);
534}
535
536#[cfg(not(target_os = "espidf"))]
537pub fn sleep(dur: Duration) {
538 cfg_select! {
539 any(
542 target_os = "freebsd",
543 target_os = "netbsd",
544 target_os = "linux",
545 target_os = "android",
546 target_os = "solaris",
547 target_os = "illumos",
548 target_os = "dragonfly",
549 target_os = "hurd",
550 target_os = "vxworks",
551 target_os = "wasi",
552 ) => {
553 unsafe fn nanosleep(
567 rqtp: *const libc::timespec,
568 rmtp: *mut libc::timespec,
569 ) -> libc::c_int {
570 unsafe { libc::clock_nanosleep(crate::sys::time::Instant::CLOCK_ID, 0, rqtp, rmtp) }
571 }
572 }
573 _ => {
574 unsafe fn nanosleep(
575 rqtp: *const libc::timespec,
576 rmtp: *mut libc::timespec,
577 ) -> libc::c_int {
578 let r = unsafe { libc::nanosleep(rqtp, rmtp) };
579 if r == 0 { 0 } else { sys::io::errno() }
582 }
583 }
584 }
585
586 let mut secs = dur.as_secs();
587 let mut nsecs = dur.subsec_nanos() as _;
588
589 unsafe {
592 while secs > 0 || nsecs > 0 {
593 let mut ts = libc::timespec::default();
594 ts.tv_sec = cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t;
595 ts.tv_nsec = nsecs;
596
597 secs -= ts.tv_sec as u64;
598 let ts_ptr = &raw mut ts;
599 let r = nanosleep(ts_ptr, ts_ptr);
600 if r != 0 {
601 assert_eq!(r, libc::EINTR);
602 secs += ts.tv_sec as u64;
603 nsecs = ts.tv_nsec;
604 } else {
605 nsecs = 0;
606 }
607 }
608 }
609}
610
611#[cfg(target_os = "espidf")]
612pub fn sleep(dur: Duration) {
613 const MAX_MICROS: u32 = u32::MAX - 1_000_000 - 1;
623
624 let mut micros = dur.as_micros() + if dur.subsec_nanos() % 1_000 > 0 { 1 } else { 0 };
631
632 while micros > 0 {
633 let st = if micros > MAX_MICROS as u128 { MAX_MICROS } else { micros as u32 };
634 unsafe {
635 libc::usleep(st);
636 }
637
638 micros -= st as u128;
639 }
640}
641
642#[cfg(any(
645 target_os = "freebsd",
646 target_os = "netbsd",
647 target_os = "linux",
648 target_os = "android",
649 target_os = "solaris",
650 target_os = "illumos",
651 target_os = "dragonfly",
652 target_os = "hurd",
653 target_os = "vxworks",
654 target_os = "wasi",
655))]
656pub fn sleep_until(deadline: crate::time::Instant) {
657 use crate::time::Instant;
658
659 let timespec = deadline.into_inner().into_timespec();
660 if timespec.tv_sec < 0 {
661 return;
677 }
678
679 #[cfg(all(
680 target_os = "linux",
681 target_env = "gnu",
682 target_pointer_width = "32",
683 not(target_arch = "riscv32")
684 ))]
685 {
686 use crate::sys::pal::time::__timespec64;
687 use crate::sys::pal::weak::weak;
688
689 weak! {
692 fn __clock_nanosleep_time64(
693 clock_id: libc::clockid_t,
694 flags: libc::c_int,
695 req: *const __timespec64,
696 rem: *mut __timespec64,
697 ) -> libc::c_int;
698 }
699
700 if let Some(clock_nanosleep) = __clock_nanosleep_time64.get() {
701 let ts = timespec.to_timespec64();
702 loop {
703 let r = unsafe {
704 clock_nanosleep(
705 crate::sys::time::Instant::CLOCK_ID,
706 libc::TIMER_ABSTIME,
707 &ts,
708 core::ptr::null_mut(),
709 )
710 };
711
712 match r {
713 0 => return,
714 libc::EINTR => continue,
715 _ => break,
724 }
725 }
726 }
727 }
728
729 let Some(ts) = timespec.to_timespec() else {
730 let now = Instant::now();
734 if let Some(delay) = deadline.checked_duration_since(now) {
735 sleep(delay);
736 }
737 return;
738 };
739
740 unsafe {
741 loop {
743 let res = libc::clock_nanosleep(
744 crate::sys::time::Instant::CLOCK_ID,
745 libc::TIMER_ABSTIME,
746 &ts,
747 core::ptr::null_mut(), );
749
750 if res == 0 {
751 break;
752 } else {
753 assert_eq!(
754 res,
755 libc::EINTR,
756 "timespec is in range,
757 clockid is valid and kernel should support it"
758 );
759 }
760 }
761 }
762}
763
764#[cfg(target_vendor = "apple")]
765pub fn sleep_until(deadline: crate::time::Instant) {
766 unsafe extern "C" {
767 safe fn mach_wait_until(deadline: u64) -> libc::kern_return_t;
775 }
776
777 let Some(deadline) = deadline.into_inner().into_mach_absolute_time_ceil() else {
780 return;
783 };
784
785 let deadline = deadline.try_into().unwrap_or(u64::MAX);
788 loop {
789 match mach_wait_until(deadline) {
790 libc::KERN_SUCCESS => break,
792 libc::KERN_ABORTED => continue,
798 error => {
800 let description = unsafe { CStr::from_ptr(libc::mach_error_string(error)) };
801 panic!("mach_wait_until failed: {} (code {error})", description.display())
802 }
803 }
804 }
805}
806
807#[cfg(target_os = "fuchsia")]
808pub fn sleep_until(deadline: crate::time::Instant) {
809 use crate::sys::pal::fuchsia::{zx_cvt, zx_nanosleep};
810
811 let deadline = deadline.into_inner().into_deadline();
812 if let Err(error) = zx_cvt(zx_nanosleep(deadline)) {
813 panic!("zx_nanosleep failed: {error}");
814 }
815}
816
817pub fn yield_now() {
818 let ret = unsafe { libc::sched_yield() };
819 debug_assert_eq!(ret, 0);
820}
821
822#[cfg(any(target_os = "android", target_os = "linux"))]
823mod cgroups {
824 use crate::borrow::Cow;
830 use crate::ffi::OsString;
831 use crate::fs::{File, exists};
832 use crate::io::{BufRead, Read};
833 use crate::os::unix::ffi::OsStringExt;
834 use crate::path::{Path, PathBuf};
835 use crate::str::from_utf8;
836
837 #[derive(PartialEq)]
838 enum Cgroup {
839 V1,
840 V2,
841 }
842
843 pub(super) fn quota() -> usize {
846 let mut quota = usize::MAX;
847 if cfg!(miri) {
848 return quota;
851 }
852
853 let _: Option<()> = try {
854 let mut buf = Vec::with_capacity(128);
855 File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
857 let (cgroup_path, version) =
858 buf.split(|&c| c == b'\n').fold(None, |previous, line| {
859 let mut fields = line.splitn(3, |&c| c == b':');
860 let version = match fields.nth(1) {
862 Some(b"") => Cgroup::V2,
863 Some(controllers)
864 if from_utf8(controllers)
865 .is_ok_and(|c| c.split(',').any(|c| c == "cpu")) =>
866 {
867 Cgroup::V1
868 }
869 _ => return previous,
870 };
871
872 if previous.is_some() && version == Cgroup::V2 {
874 return previous;
875 }
876
877 let path = fields.last()?;
878 Some((path[1..].to_owned(), version))
880 })?;
881 let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));
882
883 quota = match version {
884 Cgroup::V1 => quota_v1(cgroup_path),
885 Cgroup::V2 => quota_v2(cgroup_path),
886 };
887 };
888
889 quota
890 }
891
892 fn quota_v2(group_path: PathBuf) -> usize {
893 let mut quota = usize::MAX;
894
895 let mut path = PathBuf::with_capacity(128);
896 let mut read_buf = String::with_capacity(20);
897
898 let cgroup_mount = "/sys/fs/cgroup";
900
901 path.push(cgroup_mount);
902 path.push(&group_path);
903
904 path.push("cgroup.controllers");
905
906 if matches!(exists(&path), Err(_) | Ok(false)) {
908 return usize::MAX;
909 };
910
911 path.pop();
912
913 let _: Option<()> = try {
914 while path.starts_with(cgroup_mount) {
915 path.push("cpu.max");
916
917 read_buf.clear();
918
919 if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
920 let raw_quota = read_buf.lines().next()?;
921 let mut raw_quota = raw_quota.split(' ');
922 let limit = raw_quota.next()?;
923 let period = raw_quota.next()?;
924 match (limit.parse::<usize>(), period.parse::<usize>()) {
925 (Ok(limit), Ok(period)) if period > 0 => {
926 quota = quota.min(limit / period);
927 }
928 _ => {}
929 }
930 }
931
932 path.pop(); path.pop(); }
935 };
936
937 quota
938 }
939
940 fn quota_v1(group_path: PathBuf) -> usize {
941 let mut quota = usize::MAX;
942 let mut path = PathBuf::with_capacity(128);
943 let mut read_buf = String::with_capacity(20);
944
945 let mounts: &[fn(&Path) -> Option<(_, &Path)>] = &[
948 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu"), p)),
949 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu,cpuacct"), p)),
950 find_mountpoint,
954 ];
955
956 for mount in mounts {
957 let Some((mount, group_path)) = mount(&group_path) else { continue };
958
959 path.clear();
960 path.push(mount.as_ref());
961 path.push(&group_path);
962
963 if matches!(exists(&path), Err(_) | Ok(false)) {
965 continue;
966 }
967
968 while path.starts_with(mount.as_ref()) {
969 let mut parse_file = |name| {
970 path.push(name);
971 read_buf.clear();
972
973 let f = File::open(&path);
974 path.pop(); f.ok()?.read_to_string(&mut read_buf).ok()?;
976 let parsed = read_buf.trim().parse::<usize>().ok()?;
977
978 Some(parsed)
979 };
980
981 let limit = parse_file("cpu.cfs_quota_us");
982 let period = parse_file("cpu.cfs_period_us");
983
984 match (limit, period) {
985 (Some(limit), Some(period)) if period > 0 => quota = quota.min(limit / period),
986 _ => {}
987 }
988
989 path.pop();
990 }
991
992 break;
995 }
996
997 quota
998 }
999
1000 fn find_mountpoint(group_path: &Path) -> Option<(Cow<'static, str>, &Path)> {
1005 let mut reader = File::open_buffered("/proc/self/mountinfo").ok()?;
1006 let mut line = String::with_capacity(256);
1007 loop {
1008 line.clear();
1009 if reader.read_line(&mut line).ok()? == 0 {
1010 break;
1011 }
1012
1013 let line = line.trim();
1014 let mut items = line.split(' ');
1015
1016 let sub_path = items.nth(3)?;
1017 let mount_point = items.next()?;
1018 let mount_opts = items.next_back()?;
1019 let filesystem_type = items.nth_back(1)?;
1020
1021 if filesystem_type != "cgroup" || !mount_opts.split(',').any(|opt| opt == "cpu") {
1022 continue;
1024 }
1025
1026 let sub_path = Path::new(sub_path).strip_prefix("/").ok()?;
1027
1028 if !group_path.starts_with(sub_path) {
1029 continue;
1032 }
1033
1034 let trimmed_group_path = group_path.strip_prefix(sub_path).ok()?;
1035
1036 return Some((Cow::Owned(mount_point.to_owned()), trimmed_group_path));
1037 }
1038
1039 None
1040 }
1041}
1042
1043#[cfg(all(target_os = "linux", target_env = "gnu"))]
1049unsafe fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
1050 dlsym!(
1054 fn __pthread_get_minstack(attr: *const libc::pthread_attr_t) -> libc::size_t;
1055 );
1056
1057 match __pthread_get_minstack.get() {
1058 None => libc::PTHREAD_STACK_MIN,
1059 Some(f) => unsafe { f(attr) },
1060 }
1061}
1062
1063#[cfg(all(
1065 not(all(target_os = "linux", target_env = "gnu")),
1066 not(any(target_os = "netbsd", target_os = "nuttx"))
1067))]
1068unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
1069 libc::PTHREAD_STACK_MIN
1070}
1071
1072#[cfg(any(target_os = "netbsd", target_os = "nuttx"))]
1073unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
1074 static STACK: crate::sync::OnceLock<usize> = crate::sync::OnceLock::new();
1075
1076 *STACK.get_or_init(|| {
1077 let mut stack = unsafe { libc::sysconf(libc::_SC_THREAD_STACK_MIN) };
1078 if stack < 0 {
1079 stack = 2048; }
1081
1082 stack as usize
1083 })
1084}