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
81 if libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size) != 0 {
85 assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0);
86 drop(Box::from_raw(data));
87 return Err(io::const_error!(
88 io::ErrorKind::InvalidInput,
89 "invalid stack size"
90 ));
91 }
92 }
93 };
94 }
95
96 let ret = libc::pthread_create(&mut native, attr.as_ptr(), thread_start, data as *mut _);
97 assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0);
101
102 return if ret != 0 {
103 drop(Box::from_raw(data));
106 Err(io::Error::from_raw_os_error(ret))
107 } else {
108 Ok(Thread { id: native })
109 };
110
111 extern "C" fn thread_start(data: *mut libc::c_void) -> *mut libc::c_void {
112 unsafe {
113 let data = Box::from_raw(data as *mut ThreadData);
114 let _handler = stack_overflow::Handler::new(data.name);
117 (data.f)();
119 }
120 ptr::null_mut()
121 }
122 }
123
124 pub fn yield_now() {
125 let ret = unsafe { libc::sched_yield() };
126 debug_assert_eq!(ret, 0);
127 }
128
129 #[cfg(target_os = "android")]
130 pub fn set_name(name: &CStr) {
131 const PR_SET_NAME: libc::c_int = 15;
132 unsafe {
133 let res = libc::prctl(
134 PR_SET_NAME,
135 name.as_ptr(),
136 0 as libc::c_ulong,
137 0 as libc::c_ulong,
138 0 as libc::c_ulong,
139 );
140 debug_assert_eq!(res, 0);
142 }
143 }
144
145 #[cfg(any(
146 target_os = "linux",
147 target_os = "freebsd",
148 target_os = "dragonfly",
149 target_os = "nuttx",
150 target_os = "cygwin"
151 ))]
152 pub fn set_name(name: &CStr) {
153 unsafe {
154 cfg_select! {
155 any(target_os = "linux", target_os = "cygwin") => {
156 const TASK_COMM_LEN: usize = 16;
158 let name = truncate_cstr::<{ TASK_COMM_LEN }>(name);
159 }
160 _ => {
161 }
163 };
164 let res = libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());
167 debug_assert_eq!(res, 0);
169 }
170 }
171
172 #[cfg(target_os = "openbsd")]
173 pub fn set_name(name: &CStr) {
174 unsafe {
175 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
176 }
177 }
178
179 #[cfg(target_vendor = "apple")]
180 pub fn set_name(name: &CStr) {
181 unsafe {
182 let name = truncate_cstr::<{ libc::MAXTHREADNAMESIZE }>(name);
183 let res = libc::pthread_setname_np(name.as_ptr());
184 debug_assert_eq!(res, 0);
186 }
187 }
188
189 #[cfg(target_os = "netbsd")]
190 pub fn set_name(name: &CStr) {
191 unsafe {
192 let res = libc::pthread_setname_np(
193 libc::pthread_self(),
194 c"%s".as_ptr(),
195 name.as_ptr() as *mut libc::c_void,
196 );
197 debug_assert_eq!(res, 0);
198 }
199 }
200
201 #[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto"))]
202 pub fn set_name(name: &CStr) {
203 weak!(
204 fn pthread_setname_np(
205 thread: libc::pthread_t,
206 name: *const libc::c_char,
207 ) -> libc::c_int;
208 );
209
210 if let Some(f) = pthread_setname_np.get() {
211 #[cfg(target_os = "nto")]
212 const THREAD_NAME_MAX: usize = libc::_NTO_THREAD_NAME_MAX as usize;
213 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
214 const THREAD_NAME_MAX: usize = 32;
215
216 let name = truncate_cstr::<{ THREAD_NAME_MAX }>(name);
217 let res = unsafe { f(libc::pthread_self(), name.as_ptr()) };
218 debug_assert_eq!(res, 0);
219 }
220 }
221
222 #[cfg(target_os = "fuchsia")]
223 pub fn set_name(name: &CStr) {
224 use super::fuchsia::*;
225 unsafe {
226 zx_object_set_property(
227 zx_thread_self(),
228 ZX_PROP_NAME,
229 name.as_ptr() as *const libc::c_void,
230 name.to_bytes().len(),
231 );
232 }
233 }
234
235 #[cfg(target_os = "haiku")]
236 pub fn set_name(name: &CStr) {
237 unsafe {
238 let thread_self = libc::find_thread(ptr::null_mut());
239 let res = libc::rename_thread(thread_self, name.as_ptr());
240 debug_assert_eq!(res, libc::B_OK);
242 }
243 }
244
245 #[cfg(target_os = "vxworks")]
246 pub fn set_name(name: &CStr) {
247 let mut name = truncate_cstr::<{ (libc::VX_TASK_RENAME_LENGTH - 1) as usize }>(name);
248 let res = unsafe { libc::taskNameSet(libc::taskIdSelf(), name.as_mut_ptr()) };
249 debug_assert_eq!(res, libc::OK);
250 }
251
252 #[cfg(any(
253 target_env = "newlib",
254 target_os = "l4re",
255 target_os = "emscripten",
256 target_os = "redox",
257 target_os = "hurd",
258 target_os = "aix",
259 ))]
260 pub fn set_name(_name: &CStr) {
261 }
263
264 #[cfg(not(target_os = "espidf"))]
265 pub fn sleep(dur: Duration) {
266 let mut secs = dur.as_secs();
267 let mut nsecs = dur.subsec_nanos() as _;
268
269 unsafe {
272 while secs > 0 || nsecs > 0 {
273 let mut ts = libc::timespec {
274 tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
275 tv_nsec: nsecs,
276 };
277 secs -= ts.tv_sec as u64;
278 let ts_ptr = &raw mut ts;
279 if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
280 assert_eq!(os::errno(), libc::EINTR);
281 secs += ts.tv_sec as u64;
282 nsecs = ts.tv_nsec;
283 } else {
284 nsecs = 0;
285 }
286 }
287 }
288 }
289
290 #[cfg(target_os = "espidf")]
291 pub fn sleep(dur: Duration) {
292 const MAX_MICROS: u32 = u32::MAX - 1_000_000 - 1;
302
303 let mut micros = dur.as_micros() + if dur.subsec_nanos() % 1_000 > 0 { 1 } else { 0 };
310
311 while micros > 0 {
312 let st = if micros > MAX_MICROS as u128 { MAX_MICROS } else { micros as u32 };
313 unsafe {
314 libc::usleep(st);
315 }
316
317 micros -= st as u128;
318 }
319 }
320
321 #[cfg(any(
324 target_os = "freebsd",
325 target_os = "netbsd",
326 target_os = "linux",
327 target_os = "android",
328 target_os = "solaris",
329 target_os = "illumos",
330 target_os = "dragonfly",
331 target_os = "hurd",
332 target_os = "fuchsia",
333 target_os = "vxworks",
334 ))]
335 pub fn sleep_until(deadline: Instant) {
336 let Some(ts) = deadline.into_inner().into_timespec().to_timespec() else {
337 let now = Instant::now();
341 if let Some(delay) = deadline.checked_duration_since(now) {
342 Self::sleep(delay);
343 }
344 return;
345 };
346
347 unsafe {
348 loop {
350 let res = libc::clock_nanosleep(
351 super::time::Instant::CLOCK_ID,
352 libc::TIMER_ABSTIME,
353 &ts,
354 core::ptr::null_mut(), );
356
357 if res == 0 {
358 break;
359 } else {
360 assert_eq!(
361 res,
362 libc::EINTR,
363 "timespec is in range,
364 clockid is valid and kernel should support it"
365 );
366 }
367 }
368 }
369 }
370
371 #[cfg(not(any(
373 target_os = "freebsd",
374 target_os = "netbsd",
375 target_os = "linux",
376 target_os = "android",
377 target_os = "solaris",
378 target_os = "illumos",
379 target_os = "dragonfly",
380 target_os = "hurd",
381 target_os = "fuchsia",
382 target_os = "vxworks",
383 )))]
384 pub fn sleep_until(deadline: Instant) {
385 let now = Instant::now();
386 if let Some(delay) = deadline.checked_duration_since(now) {
387 Self::sleep(delay);
388 }
389 }
390
391 pub fn join(self) {
392 let id = self.into_id();
393 let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) };
394 assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
395 }
396
397 pub fn id(&self) -> libc::pthread_t {
398 self.id
399 }
400
401 pub fn into_id(self) -> libc::pthread_t {
402 ManuallyDrop::new(self).id
403 }
404}
405
406impl Drop for Thread {
407 fn drop(&mut self) {
408 let ret = unsafe { libc::pthread_detach(self.id) };
409 debug_assert_eq!(ret, 0);
410 }
411}
412
413pub(crate) fn current_os_id() -> Option<u64> {
414 cfg_select! {
420 any(target_os = "android", target_os = "linux") => {
422 use crate::sys::weak::syscall;
423
424 syscall!(fn gettid() -> libc::pid_t;);
427
428 let id: libc::pid_t = unsafe { gettid() };
430 Some(id as u64)
431 }
432 target_os = "nto" => {
433 let id: libc::pid_t = unsafe { libc::gettid() };
435 Some(id as u64)
436 }
437 target_os = "openbsd" => {
438 let id: libc::pid_t = unsafe { libc::getthrid() };
440 Some(id as u64)
441 }
442 target_os = "freebsd" => {
443 let id: libc::c_int = unsafe { libc::pthread_getthreadid_np() };
445 Some(id as u64)
446 }
447 target_os = "netbsd" => {
448 let id: libc::lwpid_t = unsafe { libc::_lwp_self() };
450 Some(id as u64)
451 }
452 any(target_os = "illumos", target_os = "solaris") => {
453 let id: libc::pthread_t = unsafe { libc::pthread_self() };
456 Some(id as u64)
457 }
458 target_vendor = "apple" => {
459 let mut id = 0u64;
461 let status: libc::c_int = unsafe { libc::pthread_threadid_np(0, &mut id) };
463 if status == 0 {
464 Some(id)
465 } else {
466 None
467 }
468 }
469 _ => None,
471 }
472}
473
474#[cfg(any(
475 target_os = "linux",
476 target_os = "nto",
477 target_os = "solaris",
478 target_os = "illumos",
479 target_os = "vxworks",
480 target_os = "cygwin",
481 target_vendor = "apple",
482))]
483fn truncate_cstr<const MAX_WITH_NUL: usize>(cstr: &CStr) -> [libc::c_char; MAX_WITH_NUL] {
484 let mut result = [0; MAX_WITH_NUL];
485 for (src, dst) in cstr.to_bytes().iter().zip(&mut result[..MAX_WITH_NUL - 1]) {
486 *dst = *src as libc::c_char;
487 }
488 result
489}
490
491pub fn available_parallelism() -> io::Result<NonZero<usize>> {
492 cfg_select! {
493 any(
494 target_os = "android",
495 target_os = "emscripten",
496 target_os = "fuchsia",
497 target_os = "hurd",
498 target_os = "linux",
499 target_os = "aix",
500 target_vendor = "apple",
501 target_os = "cygwin",
502 ) => {
503 #[allow(unused_assignments)]
504 #[allow(unused_mut)]
505 let mut quota = usize::MAX;
506
507 #[cfg(any(target_os = "android", target_os = "linux"))]
508 {
509 quota = cgroups::quota().max(1);
510 let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
511 unsafe {
512 if libc::sched_getaffinity(0, size_of::<libc::cpu_set_t>(), &mut set) == 0 {
513 let count = libc::CPU_COUNT(&set) as usize;
514 let count = count.min(quota);
515
516 if let Some(count) = NonZero::new(count) {
521 return Ok(count)
522 }
523 }
524 }
525 }
526 match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
527 -1 => Err(io::Error::last_os_error()),
528 0 => Err(io::Error::UNKNOWN_THREAD_COUNT),
529 cpus => {
530 let count = cpus as usize;
531 let count = count.min(quota);
533 Ok(unsafe { NonZero::new_unchecked(count) })
534 }
535 }
536 }
537 any(
538 target_os = "freebsd",
539 target_os = "dragonfly",
540 target_os = "openbsd",
541 target_os = "netbsd",
542 ) => {
543 use crate::ptr;
544
545 #[cfg(target_os = "freebsd")]
546 {
547 let mut set: libc::cpuset_t = unsafe { mem::zeroed() };
548 unsafe {
549 if libc::cpuset_getaffinity(
550 libc::CPU_LEVEL_WHICH,
551 libc::CPU_WHICH_PID,
552 -1,
553 size_of::<libc::cpuset_t>(),
554 &mut set,
555 ) == 0 {
556 let count = libc::CPU_COUNT(&set) as usize;
557 if count > 0 {
558 return Ok(NonZero::new_unchecked(count));
559 }
560 }
561 }
562 }
563
564 #[cfg(target_os = "netbsd")]
565 {
566 unsafe {
567 let set = libc::_cpuset_create();
568 if !set.is_null() {
569 let mut count: usize = 0;
570 if libc::pthread_getaffinity_np(libc::pthread_self(), libc::_cpuset_size(set), set) == 0 {
571 for i in 0..libc::cpuid_t::MAX {
572 match libc::_cpuset_isset(i, set) {
573 -1 => break,
574 0 => continue,
575 _ => count = count + 1,
576 }
577 }
578 }
579 libc::_cpuset_destroy(set);
580 if let Some(count) = NonZero::new(count) {
581 return Ok(count);
582 }
583 }
584 }
585 }
586
587 let mut cpus: libc::c_uint = 0;
588 let mut cpus_size = size_of_val(&cpus);
589
590 unsafe {
591 cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
592 }
593
594 if cpus < 1 {
596 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
597 let res = unsafe {
598 libc::sysctl(
599 mib.as_mut_ptr(),
600 2,
601 (&raw mut cpus) as *mut _,
602 (&raw mut cpus_size) as *mut _,
603 ptr::null_mut(),
604 0,
605 )
606 };
607
608 if res == -1 {
610 return Err(io::Error::last_os_error());
611 } else if cpus == 0 {
612 return Err(io::Error::UNKNOWN_THREAD_COUNT);
613 }
614 }
615
616 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
617 }
618 target_os = "nto" => {
619 unsafe {
620 use libc::_syspage_ptr;
621 if _syspage_ptr.is_null() {
622 Err(io::const_error!(io::ErrorKind::NotFound, "no syspage available"))
623 } else {
624 let cpus = (*_syspage_ptr).num_cpu;
625 NonZero::new(cpus as usize)
626 .ok_or(io::Error::UNKNOWN_THREAD_COUNT)
627 }
628 }
629 }
630 any(target_os = "solaris", target_os = "illumos") => {
631 let mut cpus = 0u32;
632 if unsafe { libc::pset_info(libc::PS_MYID, core::ptr::null_mut(), &mut cpus, core::ptr::null_mut()) } != 0 {
633 return Err(io::Error::UNKNOWN_THREAD_COUNT);
634 }
635 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
636 }
637 target_os = "haiku" => {
638 unsafe {
641 let mut sinfo: libc::system_info = crate::mem::zeroed();
642 let res = libc::get_system_info(&mut sinfo);
643
644 if res != libc::B_OK {
645 return Err(io::Error::UNKNOWN_THREAD_COUNT);
646 }
647
648 Ok(NonZero::new_unchecked(sinfo.cpu_count as usize))
649 }
650 }
651 target_os = "vxworks" => {
652 unsafe extern "C" {
655 fn vxCpuEnabledGet() -> libc::cpuset_t;
656 }
657
658 unsafe{
660 let set = vxCpuEnabledGet();
661 Ok(NonZero::new_unchecked(set.count_ones() as usize))
662 }
663 }
664 _ => {
665 Err(io::const_error!(io::ErrorKind::Unsupported, "getting the number of hardware threads is not supported on the target platform"))
667 }
668 }
669}
670
671#[cfg(any(target_os = "android", target_os = "linux"))]
672mod cgroups {
673 use crate::borrow::Cow;
679 use crate::ffi::OsString;
680 use crate::fs::{File, exists};
681 use crate::io::{BufRead, Read};
682 use crate::os::unix::ffi::OsStringExt;
683 use crate::path::{Path, PathBuf};
684 use crate::str::from_utf8;
685
686 #[derive(PartialEq)]
687 enum Cgroup {
688 V1,
689 V2,
690 }
691
692 pub(super) fn quota() -> usize {
695 let mut quota = usize::MAX;
696 if cfg!(miri) {
697 return quota;
700 }
701
702 let _: Option<()> = try {
703 let mut buf = Vec::with_capacity(128);
704 File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
706 let (cgroup_path, version) =
707 buf.split(|&c| c == b'\n').fold(None, |previous, line| {
708 let mut fields = line.splitn(3, |&c| c == b':');
709 let version = match fields.nth(1) {
711 Some(b"") => Cgroup::V2,
712 Some(controllers)
713 if from_utf8(controllers)
714 .is_ok_and(|c| c.split(',').any(|c| c == "cpu")) =>
715 {
716 Cgroup::V1
717 }
718 _ => return previous,
719 };
720
721 if previous.is_some() && version == Cgroup::V2 {
723 return previous;
724 }
725
726 let path = fields.last()?;
727 Some((path[1..].to_owned(), version))
729 })?;
730 let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));
731
732 quota = match version {
733 Cgroup::V1 => quota_v1(cgroup_path),
734 Cgroup::V2 => quota_v2(cgroup_path),
735 };
736 };
737
738 quota
739 }
740
741 fn quota_v2(group_path: PathBuf) -> usize {
742 let mut quota = usize::MAX;
743
744 let mut path = PathBuf::with_capacity(128);
745 let mut read_buf = String::with_capacity(20);
746
747 let cgroup_mount = "/sys/fs/cgroup";
749
750 path.push(cgroup_mount);
751 path.push(&group_path);
752
753 path.push("cgroup.controllers");
754
755 if matches!(exists(&path), Err(_) | Ok(false)) {
757 return usize::MAX;
758 };
759
760 path.pop();
761
762 let _: Option<()> = try {
763 while path.starts_with(cgroup_mount) {
764 path.push("cpu.max");
765
766 read_buf.clear();
767
768 if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
769 let raw_quota = read_buf.lines().next()?;
770 let mut raw_quota = raw_quota.split(' ');
771 let limit = raw_quota.next()?;
772 let period = raw_quota.next()?;
773 match (limit.parse::<usize>(), period.parse::<usize>()) {
774 (Ok(limit), Ok(period)) if period > 0 => {
775 quota = quota.min(limit / period);
776 }
777 _ => {}
778 }
779 }
780
781 path.pop(); path.pop(); }
784 };
785
786 quota
787 }
788
789 fn quota_v1(group_path: PathBuf) -> usize {
790 let mut quota = usize::MAX;
791 let mut path = PathBuf::with_capacity(128);
792 let mut read_buf = String::with_capacity(20);
793
794 let mounts: &[fn(&Path) -> Option<(_, &Path)>] = &[
797 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu"), p)),
798 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu,cpuacct"), p)),
799 find_mountpoint,
803 ];
804
805 for mount in mounts {
806 let Some((mount, group_path)) = mount(&group_path) else { continue };
807
808 path.clear();
809 path.push(mount.as_ref());
810 path.push(&group_path);
811
812 if matches!(exists(&path), Err(_) | Ok(false)) {
814 continue;
815 }
816
817 while path.starts_with(mount.as_ref()) {
818 let mut parse_file = |name| {
819 path.push(name);
820 read_buf.clear();
821
822 let f = File::open(&path);
823 path.pop(); f.ok()?.read_to_string(&mut read_buf).ok()?;
825 let parsed = read_buf.trim().parse::<usize>().ok()?;
826
827 Some(parsed)
828 };
829
830 let limit = parse_file("cpu.cfs_quota_us");
831 let period = parse_file("cpu.cfs_period_us");
832
833 match (limit, period) {
834 (Some(limit), Some(period)) if period > 0 => quota = quota.min(limit / period),
835 _ => {}
836 }
837
838 path.pop();
839 }
840
841 break;
844 }
845
846 quota
847 }
848
849 fn find_mountpoint(group_path: &Path) -> Option<(Cow<'static, str>, &Path)> {
854 let mut reader = File::open_buffered("/proc/self/mountinfo").ok()?;
855 let mut line = String::with_capacity(256);
856 loop {
857 line.clear();
858 if reader.read_line(&mut line).ok()? == 0 {
859 break;
860 }
861
862 let line = line.trim();
863 let mut items = line.split(' ');
864
865 let sub_path = items.nth(3)?;
866 let mount_point = items.next()?;
867 let mount_opts = items.next_back()?;
868 let filesystem_type = items.nth_back(1)?;
869
870 if filesystem_type != "cgroup" || !mount_opts.split(',').any(|opt| opt == "cpu") {
871 continue;
873 }
874
875 let sub_path = Path::new(sub_path).strip_prefix("/").ok()?;
876
877 if !group_path.starts_with(sub_path) {
878 continue;
881 }
882
883 let trimmed_group_path = group_path.strip_prefix(sub_path).ok()?;
884
885 return Some((Cow::Owned(mount_point.to_owned()), trimmed_group_path));
886 }
887
888 None
889 }
890}
891
892#[cfg(all(target_os = "linux", target_env = "gnu"))]
898unsafe fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
899 dlsym!(
903 fn __pthread_get_minstack(attr: *const libc::pthread_attr_t) -> libc::size_t;
904 );
905
906 match __pthread_get_minstack.get() {
907 None => libc::PTHREAD_STACK_MIN,
908 Some(f) => unsafe { f(attr) },
909 }
910}
911
912#[cfg(all(
914 not(all(target_os = "linux", target_env = "gnu")),
915 not(any(target_os = "netbsd", target_os = "nuttx"))
916))]
917unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
918 libc::PTHREAD_STACK_MIN
919}
920
921#[cfg(any(target_os = "netbsd", target_os = "nuttx"))]
922unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
923 static STACK: crate::sync::OnceLock<usize> = crate::sync::OnceLock::new();
924
925 *STACK.get_or_init(|| {
926 let mut stack = unsafe { libc::sysconf(libc::_SC_THREAD_STACK_MIN) };
927 if stack < 0 {
928 stack = 2048; }
930
931 stack as usize
932 })
933}