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, Instant};
10use crate::{cmp, io, ptr};
11#[cfg(not(any(
12 target_os = "l4re",
13 target_os = "vxworks",
14 target_os = "espidf",
15 target_os = "nuttx"
16)))]
17pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
18#[cfg(target_os = "l4re")]
19pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024;
20#[cfg(target_os = "vxworks")]
21pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 1024;
22#[cfg(any(target_os = "espidf", target_os = "nuttx"))]
23pub const DEFAULT_MIN_STACK_SIZE: usize = 0; struct ThreadData {
26 name: Option<Box<str>>,
27 f: Box<dyn FnOnce()>,
28}
29
30pub struct Thread {
31 id: libc::pthread_t,
32}
33
34unsafe impl Send for Thread {}
37unsafe impl Sync for Thread {}
38
39impl Thread {
40 #[cfg_attr(miri, track_caller)] pub unsafe fn new(
43 stack: usize,
44 name: Option<&str>,
45 f: Box<dyn FnOnce()>,
46 ) -> io::Result<Thread> {
47 let data = Box::into_raw(Box::new(ThreadData { name: name.map(Box::from), f }));
48 let mut native: libc::pthread_t = mem::zeroed();
49 let mut attr: mem::MaybeUninit<libc::pthread_attr_t> = mem::MaybeUninit::uninit();
50 assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0);
51
52 #[cfg(any(target_os = "espidf", target_os = "nuttx"))]
53 if stack > 0 {
54 assert_eq!(
57 libc::pthread_attr_setstacksize(
58 attr.as_mut_ptr(),
59 cmp::max(stack, min_stack_size(attr.as_ptr()))
60 ),
61 0
62 );
63 }
64
65 #[cfg(not(any(target_os = "espidf", target_os = "nuttx")))]
66 {
67 let stack_size = cmp::max(stack, min_stack_size(attr.as_ptr()));
68
69 match libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size) {
70 0 => {}
71 n => {
72 assert_eq!(n, libc::EINVAL);
73 let page_size = os::page_size();
78 let stack_size =
79 (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
80 assert_eq!(libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size), 0);
81 }
82 };
83 }
84
85 let ret = libc::pthread_create(&mut native, attr.as_ptr(), thread_start, data as *mut _);
86 assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0);
90
91 return if ret != 0 {
92 drop(Box::from_raw(data));
95 Err(io::Error::from_raw_os_error(ret))
96 } else {
97 Ok(Thread { id: native })
98 };
99
100 extern "C" fn thread_start(data: *mut libc::c_void) -> *mut libc::c_void {
101 unsafe {
102 let data = Box::from_raw(data as *mut ThreadData);
103 let _handler = stack_overflow::Handler::new(data.name);
106 (data.f)();
108 }
109 ptr::null_mut()
110 }
111 }
112
113 pub fn yield_now() {
114 let ret = unsafe { libc::sched_yield() };
115 debug_assert_eq!(ret, 0);
116 }
117
118 #[cfg(target_os = "android")]
119 pub fn set_name(name: &CStr) {
120 const PR_SET_NAME: libc::c_int = 15;
121 unsafe {
122 let res = libc::prctl(
123 PR_SET_NAME,
124 name.as_ptr(),
125 0 as libc::c_ulong,
126 0 as libc::c_ulong,
127 0 as libc::c_ulong,
128 );
129 debug_assert_eq!(res, 0);
131 }
132 }
133
134 #[cfg(any(
135 target_os = "linux",
136 target_os = "freebsd",
137 target_os = "dragonfly",
138 target_os = "nuttx",
139 target_os = "cygwin"
140 ))]
141 pub fn set_name(name: &CStr) {
142 unsafe {
143 cfg_if::cfg_if! {
144 if #[cfg(any(target_os = "linux", target_os = "cygwin"))] {
145 const TASK_COMM_LEN: usize = 16;
147 let name = truncate_cstr::<{ TASK_COMM_LEN }>(name);
148 } else {
149 }
151 };
152 let res = libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());
155 debug_assert_eq!(res, 0);
157 }
158 }
159
160 #[cfg(target_os = "openbsd")]
161 pub fn set_name(name: &CStr) {
162 unsafe {
163 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
164 }
165 }
166
167 #[cfg(target_vendor = "apple")]
168 pub fn set_name(name: &CStr) {
169 unsafe {
170 let name = truncate_cstr::<{ libc::MAXTHREADNAMESIZE }>(name);
171 let res = libc::pthread_setname_np(name.as_ptr());
172 debug_assert_eq!(res, 0);
174 }
175 }
176
177 #[cfg(target_os = "netbsd")]
178 pub fn set_name(name: &CStr) {
179 unsafe {
180 let res = libc::pthread_setname_np(
181 libc::pthread_self(),
182 c"%s".as_ptr(),
183 name.as_ptr() as *mut libc::c_void,
184 );
185 debug_assert_eq!(res, 0);
186 }
187 }
188
189 #[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto"))]
190 pub fn set_name(name: &CStr) {
191 weak!(
192 fn pthread_setname_np(
193 thread: libc::pthread_t,
194 name: *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 super::fuchsia::*;
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 debug_assert_eq!(res, libc::B_OK);
230 }
231 }
232
233 #[cfg(target_os = "vxworks")]
234 pub fn set_name(name: &CStr) {
235 let mut name = truncate_cstr::<{ (libc::VX_TASK_RENAME_LENGTH - 1) as usize }>(name);
236 let res = unsafe { libc::taskNameSet(libc::taskIdSelf(), name.as_mut_ptr()) };
237 debug_assert_eq!(res, libc::OK);
238 }
239
240 #[cfg(any(
241 target_env = "newlib",
242 target_os = "l4re",
243 target_os = "emscripten",
244 target_os = "redox",
245 target_os = "hurd",
246 target_os = "aix",
247 ))]
248 pub fn set_name(_name: &CStr) {
249 }
251
252 #[cfg(not(target_os = "espidf"))]
253 pub fn sleep(dur: Duration) {
254 let mut secs = dur.as_secs();
255 let mut nsecs = dur.subsec_nanos() as _;
256
257 unsafe {
260 while secs > 0 || nsecs > 0 {
261 let mut ts = libc::timespec {
262 tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
263 tv_nsec: nsecs,
264 };
265 secs -= ts.tv_sec as u64;
266 let ts_ptr = &raw mut ts;
267 if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
268 assert_eq!(os::errno(), libc::EINTR);
269 secs += ts.tv_sec as u64;
270 nsecs = ts.tv_nsec;
271 } else {
272 nsecs = 0;
273 }
274 }
275 }
276 }
277
278 #[cfg(target_os = "espidf")]
279 pub fn sleep(dur: Duration) {
280 const MAX_MICROS: u32 = u32::MAX - 1_000_000 - 1;
290
291 let mut micros = dur.as_micros() + if dur.subsec_nanos() % 1_000 > 0 { 1 } else { 0 };
298
299 while micros > 0 {
300 let st = if micros > MAX_MICROS as u128 { MAX_MICROS } else { micros as u32 };
301 unsafe {
302 libc::usleep(st);
303 }
304
305 micros -= st as u128;
306 }
307 }
308
309 #[cfg(any(
312 target_os = "freebsd",
313 target_os = "netbsd",
314 target_os = "linux",
315 target_os = "android",
316 target_os = "solaris",
317 target_os = "illumos",
318 target_os = "dragonfly",
319 target_os = "hurd",
320 target_os = "fuchsia",
321 target_os = "vxworks",
322 ))]
323 pub fn sleep_until(deadline: Instant) {
324 let Some(ts) = deadline.into_inner().into_timespec().to_timespec() else {
325 let now = Instant::now();
329 if let Some(delay) = deadline.checked_duration_since(now) {
330 Self::sleep(delay);
331 }
332 return;
333 };
334
335 unsafe {
336 loop {
338 let res = libc::clock_nanosleep(
339 super::time::Instant::CLOCK_ID,
340 libc::TIMER_ABSTIME,
341 &ts,
342 core::ptr::null_mut(), );
344
345 if res == 0 {
346 break;
347 } else {
348 assert_eq!(
349 res,
350 libc::EINTR,
351 "timespec is in range,
352 clockid is valid and kernel should support it"
353 );
354 }
355 }
356 }
357 }
358
359 #[cfg(not(any(
361 target_os = "freebsd",
362 target_os = "netbsd",
363 target_os = "linux",
364 target_os = "android",
365 target_os = "solaris",
366 target_os = "illumos",
367 target_os = "dragonfly",
368 target_os = "hurd",
369 target_os = "fuchsia",
370 target_os = "vxworks",
371 )))]
372 pub fn sleep_until(deadline: Instant) {
373 let now = Instant::now();
374 if let Some(delay) = deadline.checked_duration_since(now) {
375 Self::sleep(delay);
376 }
377 }
378
379 pub fn join(self) {
380 let id = self.into_id();
381 let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) };
382 assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
383 }
384
385 pub fn id(&self) -> libc::pthread_t {
386 self.id
387 }
388
389 pub fn into_id(self) -> libc::pthread_t {
390 ManuallyDrop::new(self).id
391 }
392}
393
394impl Drop for Thread {
395 fn drop(&mut self) {
396 let ret = unsafe { libc::pthread_detach(self.id) };
397 debug_assert_eq!(ret, 0);
398 }
399}
400
401pub(crate) fn current_os_id() -> Option<u64> {
402 cfg_if::cfg_if! {
408 if #[cfg(any(target_os = "android", target_os = "linux"))] {
410 use crate::sys::weak::syscall;
411
412 syscall!(fn gettid() -> libc::pid_t;);
415
416 let id: libc::pid_t = unsafe { gettid() };
418 Some(id as u64)
419 } else if #[cfg(target_os = "nto")] {
420 let id: libc::pid_t = unsafe { libc::gettid() };
422 Some(id as u64)
423 } else if #[cfg(target_os = "openbsd")] {
424 let id: libc::pid_t = unsafe { libc::getthrid() };
426 Some(id as u64)
427 } else if #[cfg(target_os = "freebsd")] {
428 let id: libc::c_int = unsafe { libc::pthread_getthreadid_np() };
430 Some(id as u64)
431 } else if #[cfg(target_os = "netbsd")] {
432 let id: libc::lwpid_t = unsafe { libc::_lwp_self() };
434 Some(id as u64)
435 } else if #[cfg(any(target_os = "illumos", target_os = "solaris"))] {
436 let id: libc::pthread_t = unsafe { libc::pthread_self() };
439 Some(id as u64)
440 } else if #[cfg(target_vendor = "apple")] {
441 let mut id = 0u64;
443 let status: libc::c_int = unsafe { libc::pthread_threadid_np(0, &mut id) };
445 if status == 0 {
446 Some(id)
447 } else {
448 None
449 }
450 } else {
451 None
453 }
454 }
455}
456
457#[cfg(any(
458 target_os = "linux",
459 target_os = "nto",
460 target_os = "solaris",
461 target_os = "illumos",
462 target_os = "vxworks",
463 target_os = "cygwin",
464 target_vendor = "apple",
465))]
466fn truncate_cstr<const MAX_WITH_NUL: usize>(cstr: &CStr) -> [libc::c_char; MAX_WITH_NUL] {
467 let mut result = [0; MAX_WITH_NUL];
468 for (src, dst) in cstr.to_bytes().iter().zip(&mut result[..MAX_WITH_NUL - 1]) {
469 *dst = *src as libc::c_char;
470 }
471 result
472}
473
474pub fn available_parallelism() -> io::Result<NonZero<usize>> {
475 cfg_if::cfg_if! {
476 if #[cfg(any(
477 target_os = "android",
478 target_os = "emscripten",
479 target_os = "fuchsia",
480 target_os = "hurd",
481 target_os = "linux",
482 target_os = "aix",
483 target_vendor = "apple",
484 target_os = "cygwin",
485 ))] {
486 #[allow(unused_assignments)]
487 #[allow(unused_mut)]
488 let mut quota = usize::MAX;
489
490 #[cfg(any(target_os = "android", target_os = "linux"))]
491 {
492 quota = cgroups::quota().max(1);
493 let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
494 unsafe {
495 if libc::sched_getaffinity(0, size_of::<libc::cpu_set_t>(), &mut set) == 0 {
496 let count = libc::CPU_COUNT(&set) as usize;
497 let count = count.min(quota);
498
499 if let Some(count) = NonZero::new(count) {
504 return Ok(count)
505 }
506 }
507 }
508 }
509 match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
510 -1 => Err(io::Error::last_os_error()),
511 0 => Err(io::Error::UNKNOWN_THREAD_COUNT),
512 cpus => {
513 let count = cpus as usize;
514 let count = count.min(quota);
516 Ok(unsafe { NonZero::new_unchecked(count) })
517 }
518 }
519 } else if #[cfg(any(
520 target_os = "freebsd",
521 target_os = "dragonfly",
522 target_os = "openbsd",
523 target_os = "netbsd",
524 ))] {
525 use crate::ptr;
526
527 #[cfg(target_os = "freebsd")]
528 {
529 let mut set: libc::cpuset_t = unsafe { mem::zeroed() };
530 unsafe {
531 if libc::cpuset_getaffinity(
532 libc::CPU_LEVEL_WHICH,
533 libc::CPU_WHICH_PID,
534 -1,
535 size_of::<libc::cpuset_t>(),
536 &mut set,
537 ) == 0 {
538 let count = libc::CPU_COUNT(&set) as usize;
539 if count > 0 {
540 return Ok(NonZero::new_unchecked(count));
541 }
542 }
543 }
544 }
545
546 #[cfg(target_os = "netbsd")]
547 {
548 unsafe {
549 let set = libc::_cpuset_create();
550 if !set.is_null() {
551 let mut count: usize = 0;
552 if libc::pthread_getaffinity_np(libc::pthread_self(), libc::_cpuset_size(set), set) == 0 {
553 for i in 0..libc::cpuid_t::MAX {
554 match libc::_cpuset_isset(i, set) {
555 -1 => break,
556 0 => continue,
557 _ => count = count + 1,
558 }
559 }
560 }
561 libc::_cpuset_destroy(set);
562 if let Some(count) = NonZero::new(count) {
563 return Ok(count);
564 }
565 }
566 }
567 }
568
569 let mut cpus: libc::c_uint = 0;
570 let mut cpus_size = size_of_val(&cpus);
571
572 unsafe {
573 cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
574 }
575
576 if cpus < 1 {
578 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
579 let res = unsafe {
580 libc::sysctl(
581 mib.as_mut_ptr(),
582 2,
583 (&raw mut cpus) as *mut _,
584 (&raw mut cpus_size) as *mut _,
585 ptr::null_mut(),
586 0,
587 )
588 };
589
590 if res == -1 {
592 return Err(io::Error::last_os_error());
593 } else if cpus == 0 {
594 return Err(io::Error::UNKNOWN_THREAD_COUNT);
595 }
596 }
597
598 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
599 } else if #[cfg(target_os = "nto")] {
600 unsafe {
601 use libc::_syspage_ptr;
602 if _syspage_ptr.is_null() {
603 Err(io::const_error!(io::ErrorKind::NotFound, "no syspage available"))
604 } else {
605 let cpus = (*_syspage_ptr).num_cpu;
606 NonZero::new(cpus as usize)
607 .ok_or(io::Error::UNKNOWN_THREAD_COUNT)
608 }
609 }
610 } else if #[cfg(any(target_os = "solaris", target_os = "illumos"))] {
611 let mut cpus = 0u32;
612 if unsafe { libc::pset_info(libc::PS_MYID, core::ptr::null_mut(), &mut cpus, core::ptr::null_mut()) } != 0 {
613 return Err(io::Error::UNKNOWN_THREAD_COUNT);
614 }
615 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
616 } else if #[cfg(target_os = "haiku")] {
617 unsafe {
620 let mut sinfo: libc::system_info = crate::mem::zeroed();
621 let res = libc::get_system_info(&mut sinfo);
622
623 if res != libc::B_OK {
624 return Err(io::Error::UNKNOWN_THREAD_COUNT);
625 }
626
627 Ok(NonZero::new_unchecked(sinfo.cpu_count as usize))
628 }
629 } else if #[cfg(target_os = "vxworks")] {
630 unsafe extern "C" {
633 fn vxCpuEnabledGet() -> libc::cpuset_t;
634 }
635
636 unsafe{
638 let set = vxCpuEnabledGet();
639 Ok(NonZero::new_unchecked(set.count_ones() as usize))
640 }
641 } else {
642 Err(io::const_error!(io::ErrorKind::Unsupported, "getting the number of hardware threads is not supported on the target platform"))
644 }
645 }
646}
647
648#[cfg(any(target_os = "android", target_os = "linux"))]
649mod cgroups {
650 use crate::borrow::Cow;
656 use crate::ffi::OsString;
657 use crate::fs::{File, exists};
658 use crate::io::{BufRead, Read};
659 use crate::os::unix::ffi::OsStringExt;
660 use crate::path::{Path, PathBuf};
661 use crate::str::from_utf8;
662
663 #[derive(PartialEq)]
664 enum Cgroup {
665 V1,
666 V2,
667 }
668
669 pub(super) fn quota() -> usize {
672 let mut quota = usize::MAX;
673 if cfg!(miri) {
674 return quota;
677 }
678
679 let _: Option<()> = try {
680 let mut buf = Vec::with_capacity(128);
681 File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
683 let (cgroup_path, version) =
684 buf.split(|&c| c == b'\n').fold(None, |previous, line| {
685 let mut fields = line.splitn(3, |&c| c == b':');
686 let version = match fields.nth(1) {
688 Some(b"") => Cgroup::V2,
689 Some(controllers)
690 if from_utf8(controllers)
691 .is_ok_and(|c| c.split(',').any(|c| c == "cpu")) =>
692 {
693 Cgroup::V1
694 }
695 _ => return previous,
696 };
697
698 if previous.is_some() && version == Cgroup::V2 {
700 return previous;
701 }
702
703 let path = fields.last()?;
704 Some((path[1..].to_owned(), version))
706 })?;
707 let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));
708
709 quota = match version {
710 Cgroup::V1 => quota_v1(cgroup_path),
711 Cgroup::V2 => quota_v2(cgroup_path),
712 };
713 };
714
715 quota
716 }
717
718 fn quota_v2(group_path: PathBuf) -> usize {
719 let mut quota = usize::MAX;
720
721 let mut path = PathBuf::with_capacity(128);
722 let mut read_buf = String::with_capacity(20);
723
724 let cgroup_mount = "/sys/fs/cgroup";
726
727 path.push(cgroup_mount);
728 path.push(&group_path);
729
730 path.push("cgroup.controllers");
731
732 if matches!(exists(&path), Err(_) | Ok(false)) {
734 return usize::MAX;
735 };
736
737 path.pop();
738
739 let _: Option<()> = try {
740 while path.starts_with(cgroup_mount) {
741 path.push("cpu.max");
742
743 read_buf.clear();
744
745 if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
746 let raw_quota = read_buf.lines().next()?;
747 let mut raw_quota = raw_quota.split(' ');
748 let limit = raw_quota.next()?;
749 let period = raw_quota.next()?;
750 match (limit.parse::<usize>(), period.parse::<usize>()) {
751 (Ok(limit), Ok(period)) if period > 0 => {
752 quota = quota.min(limit / period);
753 }
754 _ => {}
755 }
756 }
757
758 path.pop(); path.pop(); }
761 };
762
763 quota
764 }
765
766 fn quota_v1(group_path: PathBuf) -> usize {
767 let mut quota = usize::MAX;
768 let mut path = PathBuf::with_capacity(128);
769 let mut read_buf = String::with_capacity(20);
770
771 let mounts: &[fn(&Path) -> Option<(_, &Path)>] = &[
774 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu"), p)),
775 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu,cpuacct"), p)),
776 find_mountpoint,
780 ];
781
782 for mount in mounts {
783 let Some((mount, group_path)) = mount(&group_path) else { continue };
784
785 path.clear();
786 path.push(mount.as_ref());
787 path.push(&group_path);
788
789 if matches!(exists(&path), Err(_) | Ok(false)) {
791 continue;
792 }
793
794 while path.starts_with(mount.as_ref()) {
795 let mut parse_file = |name| {
796 path.push(name);
797 read_buf.clear();
798
799 let f = File::open(&path);
800 path.pop(); f.ok()?.read_to_string(&mut read_buf).ok()?;
802 let parsed = read_buf.trim().parse::<usize>().ok()?;
803
804 Some(parsed)
805 };
806
807 let limit = parse_file("cpu.cfs_quota_us");
808 let period = parse_file("cpu.cfs_period_us");
809
810 match (limit, period) {
811 (Some(limit), Some(period)) if period > 0 => quota = quota.min(limit / period),
812 _ => {}
813 }
814
815 path.pop();
816 }
817
818 break;
821 }
822
823 quota
824 }
825
826 fn find_mountpoint(group_path: &Path) -> Option<(Cow<'static, str>, &Path)> {
831 let mut reader = File::open_buffered("/proc/self/mountinfo").ok()?;
832 let mut line = String::with_capacity(256);
833 loop {
834 line.clear();
835 if reader.read_line(&mut line).ok()? == 0 {
836 break;
837 }
838
839 let line = line.trim();
840 let mut items = line.split(' ');
841
842 let sub_path = items.nth(3)?;
843 let mount_point = items.next()?;
844 let mount_opts = items.next_back()?;
845 let filesystem_type = items.nth_back(1)?;
846
847 if filesystem_type != "cgroup" || !mount_opts.split(',').any(|opt| opt == "cpu") {
848 continue;
850 }
851
852 let sub_path = Path::new(sub_path).strip_prefix("/").ok()?;
853
854 if !group_path.starts_with(sub_path) {
855 continue;
858 }
859
860 let trimmed_group_path = group_path.strip_prefix(sub_path).ok()?;
861
862 return Some((Cow::Owned(mount_point.to_owned()), trimmed_group_path));
863 }
864
865 None
866 }
867}
868
869#[cfg(all(target_os = "linux", target_env = "gnu"))]
875unsafe fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
876 dlsym!(
880 fn __pthread_get_minstack(attr: *const libc::pthread_attr_t) -> libc::size_t;
881 );
882
883 match __pthread_get_minstack.get() {
884 None => libc::PTHREAD_STACK_MIN,
885 Some(f) => unsafe { f(attr) },
886 }
887}
888
889#[cfg(all(
891 not(all(target_os = "linux", target_env = "gnu")),
892 not(any(target_os = "netbsd", target_os = "nuttx"))
893))]
894unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
895 libc::PTHREAD_STACK_MIN
896}
897
898#[cfg(any(target_os = "netbsd", target_os = "nuttx"))]
899unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
900 static STACK: crate::sync::OnceLock<usize> = crate::sync::OnceLock::new();
901
902 *STACK.get_or_init(|| {
903 let mut stack = unsafe { libc::sysconf(libc::_SC_THREAD_STACK_MIN) };
904 if stack < 0 {
905 stack = 2048; }
907
908 stack as usize
909 })
910}