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; #[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
41unsafe impl Send for Thread {}
44unsafe impl Sync for Thread {}
45
46impl Thread {
47 #[cfg_attr(miri, track_caller)] 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 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 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 assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0);
93
94 return if ret != 0 {
95 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 let _handler = stack_overflow::Handler::new();
108 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 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 const TASK_COMM_LEN: usize = 16;
148 let name = truncate_cstr::<{ TASK_COMM_LEN }>(name);
149 } else {
150 }
152 };
153 let res = libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());
156 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 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 #[no_sanitize(cfi)]
194 pub fn set_name(name: &CStr) {
195 weak! {
196 fn pthread_setname_np(
197 libc::pthread_t, *const libc::c_char
198 ) -> libc::c_int
199 }
200
201 if let Some(f) = pthread_setname_np.get() {
202 #[cfg(target_os = "nto")]
203 const THREAD_NAME_MAX: usize = libc::_NTO_THREAD_NAME_MAX as usize;
204 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
205 const THREAD_NAME_MAX: usize = 32;
206
207 let name = truncate_cstr::<{ THREAD_NAME_MAX }>(name);
208 let res = unsafe { f(libc::pthread_self(), name.as_ptr()) };
209 debug_assert_eq!(res, 0);
210 }
211 }
212
213 #[cfg(target_os = "fuchsia")]
214 pub fn set_name(name: &CStr) {
215 use self::zircon::*;
216 unsafe {
217 zx_object_set_property(
218 zx_thread_self(),
219 ZX_PROP_NAME,
220 name.as_ptr() as *const libc::c_void,
221 name.to_bytes().len(),
222 );
223 }
224 }
225
226 #[cfg(target_os = "haiku")]
227 pub fn set_name(name: &CStr) {
228 unsafe {
229 let thread_self = libc::find_thread(ptr::null_mut());
230 let res = libc::rename_thread(thread_self, name.as_ptr());
231 debug_assert_eq!(res, libc::B_OK);
233 }
234 }
235
236 #[cfg(target_os = "vxworks")]
237 pub fn set_name(name: &CStr) {
238 unsafe extern "C" {
240 fn taskNameSet(task_id: libc::TASK_ID, task_name: *mut libc::c_char) -> libc::c_int;
241 }
242
243 const VX_TASK_NAME_LEN: usize = 31;
245
246 let mut name = truncate_cstr::<{ VX_TASK_NAME_LEN }>(name);
247 let res = unsafe { taskNameSet(libc::taskIdSelf(), name.as_mut_ptr()) };
248 debug_assert_eq!(res, libc::OK);
249 }
250
251 #[cfg(any(
252 target_env = "newlib",
253 target_os = "l4re",
254 target_os = "emscripten",
255 target_os = "redox",
256 target_os = "hurd",
257 target_os = "aix",
258 ))]
259 pub fn set_name(_name: &CStr) {
260 }
262
263 #[cfg(not(target_os = "espidf"))]
264 pub fn sleep(dur: Duration) {
265 let mut secs = dur.as_secs();
266 let mut nsecs = dur.subsec_nanos() as _;
267
268 unsafe {
271 while secs > 0 || nsecs > 0 {
272 let mut ts = libc::timespec {
273 tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
274 tv_nsec: nsecs,
275 };
276 secs -= ts.tv_sec as u64;
277 let ts_ptr = &raw mut ts;
278 if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
279 assert_eq!(os::errno(), libc::EINTR);
280 secs += ts.tv_sec as u64;
281 nsecs = ts.tv_nsec;
282 } else {
283 nsecs = 0;
284 }
285 }
286 }
287 }
288
289 #[cfg(target_os = "espidf")]
290 pub fn sleep(dur: Duration) {
291 const MAX_MICROS: u32 = u32::MAX - 1_000_000 - 1;
301
302 let mut micros = dur.as_micros() + if dur.subsec_nanos() % 1_000 > 0 { 1 } else { 0 };
309
310 while micros > 0 {
311 let st = if micros > MAX_MICROS as u128 { MAX_MICROS } else { micros as u32 };
312 unsafe {
313 libc::usleep(st);
314 }
315
316 micros -= st as u128;
317 }
318 }
319
320 pub fn join(self) {
321 let id = self.into_id();
322 let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) };
323 assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
324 }
325
326 pub fn id(&self) -> libc::pthread_t {
327 self.id
328 }
329
330 pub fn into_id(self) -> libc::pthread_t {
331 ManuallyDrop::new(self).id
332 }
333}
334
335impl Drop for Thread {
336 fn drop(&mut self) {
337 let ret = unsafe { libc::pthread_detach(self.id) };
338 debug_assert_eq!(ret, 0);
339 }
340}
341
342#[cfg(any(
343 target_os = "linux",
344 target_os = "nto",
345 target_os = "solaris",
346 target_os = "illumos",
347 target_os = "vxworks",
348 target_vendor = "apple",
349))]
350fn truncate_cstr<const MAX_WITH_NUL: usize>(cstr: &CStr) -> [libc::c_char; MAX_WITH_NUL] {
351 let mut result = [0; MAX_WITH_NUL];
352 for (src, dst) in cstr.to_bytes().iter().zip(&mut result[..MAX_WITH_NUL - 1]) {
353 *dst = *src as libc::c_char;
354 }
355 result
356}
357
358pub fn available_parallelism() -> io::Result<NonZero<usize>> {
359 cfg_if::cfg_if! {
360 if #[cfg(any(
361 target_os = "android",
362 target_os = "emscripten",
363 target_os = "fuchsia",
364 target_os = "hurd",
365 target_os = "linux",
366 target_os = "aix",
367 target_vendor = "apple",
368 ))] {
369 #[allow(unused_assignments)]
370 #[allow(unused_mut)]
371 let mut quota = usize::MAX;
372
373 #[cfg(any(target_os = "android", target_os = "linux"))]
374 {
375 quota = cgroups::quota().max(1);
376 let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
377 unsafe {
378 if libc::sched_getaffinity(0, size_of::<libc::cpu_set_t>(), &mut set) == 0 {
379 let count = libc::CPU_COUNT(&set) as usize;
380 let count = count.min(quota);
381
382 if let Some(count) = NonZero::new(count) {
387 return Ok(count)
388 }
389 }
390 }
391 }
392 match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
393 -1 => Err(io::Error::last_os_error()),
394 0 => Err(io::Error::UNKNOWN_THREAD_COUNT),
395 cpus => {
396 let count = cpus as usize;
397 let count = count.min(quota);
399 Ok(unsafe { NonZero::new_unchecked(count) })
400 }
401 }
402 } else if #[cfg(any(
403 target_os = "freebsd",
404 target_os = "dragonfly",
405 target_os = "openbsd",
406 target_os = "netbsd",
407 ))] {
408 use crate::ptr;
409
410 #[cfg(target_os = "freebsd")]
411 {
412 let mut set: libc::cpuset_t = unsafe { mem::zeroed() };
413 unsafe {
414 if libc::cpuset_getaffinity(
415 libc::CPU_LEVEL_WHICH,
416 libc::CPU_WHICH_PID,
417 -1,
418 size_of::<libc::cpuset_t>(),
419 &mut set,
420 ) == 0 {
421 let count = libc::CPU_COUNT(&set) as usize;
422 if count > 0 {
423 return Ok(NonZero::new_unchecked(count));
424 }
425 }
426 }
427 }
428
429 #[cfg(target_os = "netbsd")]
430 {
431 unsafe {
432 let set = libc::_cpuset_create();
433 if !set.is_null() {
434 let mut count: usize = 0;
435 if libc::pthread_getaffinity_np(libc::pthread_self(), libc::_cpuset_size(set), set) == 0 {
436 for i in 0..libc::cpuid_t::MAX {
437 match libc::_cpuset_isset(i, set) {
438 -1 => break,
439 0 => continue,
440 _ => count = count + 1,
441 }
442 }
443 }
444 libc::_cpuset_destroy(set);
445 if let Some(count) = NonZero::new(count) {
446 return Ok(count);
447 }
448 }
449 }
450 }
451
452 let mut cpus: libc::c_uint = 0;
453 let mut cpus_size = size_of_val(&cpus);
454
455 unsafe {
456 cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
457 }
458
459 if cpus < 1 {
461 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
462 let res = unsafe {
463 libc::sysctl(
464 mib.as_mut_ptr(),
465 2,
466 (&raw mut cpus) as *mut _,
467 (&raw mut cpus_size) as *mut _,
468 ptr::null_mut(),
469 0,
470 )
471 };
472
473 if res == -1 {
475 return Err(io::Error::last_os_error());
476 } else if cpus == 0 {
477 return Err(io::Error::UNKNOWN_THREAD_COUNT);
478 }
479 }
480
481 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
482 } else if #[cfg(target_os = "nto")] {
483 unsafe {
484 use libc::_syspage_ptr;
485 if _syspage_ptr.is_null() {
486 Err(io::const_error!(io::ErrorKind::NotFound, "no syspage available"))
487 } else {
488 let cpus = (*_syspage_ptr).num_cpu;
489 NonZero::new(cpus as usize)
490 .ok_or(io::Error::UNKNOWN_THREAD_COUNT)
491 }
492 }
493 } else if #[cfg(any(target_os = "solaris", target_os = "illumos"))] {
494 let mut cpus = 0u32;
495 if unsafe { libc::pset_info(libc::PS_MYID, core::ptr::null_mut(), &mut cpus, core::ptr::null_mut()) } != 0 {
496 return Err(io::Error::UNKNOWN_THREAD_COUNT);
497 }
498 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
499 } else if #[cfg(target_os = "haiku")] {
500 unsafe {
503 let mut sinfo: libc::system_info = crate::mem::zeroed();
504 let res = libc::get_system_info(&mut sinfo);
505
506 if res != libc::B_OK {
507 return Err(io::Error::UNKNOWN_THREAD_COUNT);
508 }
509
510 Ok(NonZero::new_unchecked(sinfo.cpu_count as usize))
511 }
512 } else if #[cfg(target_os = "vxworks")] {
513 unsafe extern "C" {
516 fn vxCpuEnabledGet() -> libc::cpuset_t;
517 }
518
519 unsafe{
521 let set = vxCpuEnabledGet();
522 Ok(NonZero::new_unchecked(set.count_ones() as usize))
523 }
524 } else {
525 Err(io::const_error!(io::ErrorKind::Unsupported, "getting the number of hardware threads is not supported on the target platform"))
527 }
528 }
529}
530
531#[cfg(any(target_os = "android", target_os = "linux"))]
532mod cgroups {
533 use crate::borrow::Cow;
539 use crate::ffi::OsString;
540 use crate::fs::{File, exists};
541 use crate::io::{BufRead, Read};
542 use crate::os::unix::ffi::OsStringExt;
543 use crate::path::{Path, PathBuf};
544 use crate::str::from_utf8;
545
546 #[derive(PartialEq)]
547 enum Cgroup {
548 V1,
549 V2,
550 }
551
552 pub(super) fn quota() -> usize {
555 let mut quota = usize::MAX;
556 if cfg!(miri) {
557 return quota;
560 }
561
562 let _: Option<()> = try {
563 let mut buf = Vec::with_capacity(128);
564 File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
566 let (cgroup_path, version) =
567 buf.split(|&c| c == b'\n').fold(None, |previous, line| {
568 let mut fields = line.splitn(3, |&c| c == b':');
569 let version = match fields.nth(1) {
571 Some(b"") => Cgroup::V2,
572 Some(controllers)
573 if from_utf8(controllers)
574 .is_ok_and(|c| c.split(',').any(|c| c == "cpu")) =>
575 {
576 Cgroup::V1
577 }
578 _ => return previous,
579 };
580
581 if previous.is_some() && version == Cgroup::V2 {
583 return previous;
584 }
585
586 let path = fields.last()?;
587 Some((path[1..].to_owned(), version))
589 })?;
590 let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));
591
592 quota = match version {
593 Cgroup::V1 => quota_v1(cgroup_path),
594 Cgroup::V2 => quota_v2(cgroup_path),
595 };
596 };
597
598 quota
599 }
600
601 fn quota_v2(group_path: PathBuf) -> usize {
602 let mut quota = usize::MAX;
603
604 let mut path = PathBuf::with_capacity(128);
605 let mut read_buf = String::with_capacity(20);
606
607 let cgroup_mount = "/sys/fs/cgroup";
609
610 path.push(cgroup_mount);
611 path.push(&group_path);
612
613 path.push("cgroup.controllers");
614
615 if matches!(exists(&path), Err(_) | Ok(false)) {
617 return usize::MAX;
618 };
619
620 path.pop();
621
622 let _: Option<()> = try {
623 while path.starts_with(cgroup_mount) {
624 path.push("cpu.max");
625
626 read_buf.clear();
627
628 if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
629 let raw_quota = read_buf.lines().next()?;
630 let mut raw_quota = raw_quota.split(' ');
631 let limit = raw_quota.next()?;
632 let period = raw_quota.next()?;
633 match (limit.parse::<usize>(), period.parse::<usize>()) {
634 (Ok(limit), Ok(period)) if period > 0 => {
635 quota = quota.min(limit / period);
636 }
637 _ => {}
638 }
639 }
640
641 path.pop(); path.pop(); }
644 };
645
646 quota
647 }
648
649 fn quota_v1(group_path: PathBuf) -> usize {
650 let mut quota = usize::MAX;
651 let mut path = PathBuf::with_capacity(128);
652 let mut read_buf = String::with_capacity(20);
653
654 let mounts: &[fn(&Path) -> Option<(_, &Path)>] = &[
657 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu"), p)),
658 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu,cpuacct"), p)),
659 find_mountpoint,
663 ];
664
665 for mount in mounts {
666 let Some((mount, group_path)) = mount(&group_path) else { continue };
667
668 path.clear();
669 path.push(mount.as_ref());
670 path.push(&group_path);
671
672 if matches!(exists(&path), Err(_) | Ok(false)) {
674 continue;
675 }
676
677 while path.starts_with(mount.as_ref()) {
678 let mut parse_file = |name| {
679 path.push(name);
680 read_buf.clear();
681
682 let f = File::open(&path);
683 path.pop(); f.ok()?.read_to_string(&mut read_buf).ok()?;
685 let parsed = read_buf.trim().parse::<usize>().ok()?;
686
687 Some(parsed)
688 };
689
690 let limit = parse_file("cpu.cfs_quota_us");
691 let period = parse_file("cpu.cfs_period_us");
692
693 match (limit, period) {
694 (Some(limit), Some(period)) if period > 0 => quota = quota.min(limit / period),
695 _ => {}
696 }
697
698 path.pop();
699 }
700
701 break;
704 }
705
706 quota
707 }
708
709 fn find_mountpoint(group_path: &Path) -> Option<(Cow<'static, str>, &Path)> {
714 let mut reader = File::open_buffered("/proc/self/mountinfo").ok()?;
715 let mut line = String::with_capacity(256);
716 loop {
717 line.clear();
718 if reader.read_line(&mut line).ok()? == 0 {
719 break;
720 }
721
722 let line = line.trim();
723 let mut items = line.split(' ');
724
725 let sub_path = items.nth(3)?;
726 let mount_point = items.next()?;
727 let mount_opts = items.next_back()?;
728 let filesystem_type = items.nth_back(1)?;
729
730 if filesystem_type != "cgroup" || !mount_opts.split(',').any(|opt| opt == "cpu") {
731 continue;
733 }
734
735 let sub_path = Path::new(sub_path).strip_prefix("/").ok()?;
736
737 if !group_path.starts_with(sub_path) {
738 continue;
741 }
742
743 let trimmed_group_path = group_path.strip_prefix(sub_path).ok()?;
744
745 return Some((Cow::Owned(mount_point.to_owned()), trimmed_group_path));
746 }
747
748 None
749 }
750}
751
752#[cfg(all(target_os = "linux", target_env = "gnu"))]
758unsafe fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
759 dlsym!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
763
764 match __pthread_get_minstack.get() {
765 None => libc::PTHREAD_STACK_MIN,
766 Some(f) => unsafe { f(attr) },
767 }
768}
769
770#[cfg(all(
772 not(all(target_os = "linux", target_env = "gnu")),
773 not(any(target_os = "netbsd", target_os = "nuttx"))
774))]
775unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
776 libc::PTHREAD_STACK_MIN
777}
778
779#[cfg(any(target_os = "netbsd", target_os = "nuttx"))]
780unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
781 static STACK: crate::sync::OnceLock<usize> = crate::sync::OnceLock::new();
782
783 *STACK.get_or_init(|| {
784 let mut stack = unsafe { libc::sysconf(libc::_SC_THREAD_STACK_MIN) };
785 if stack < 0 {
786 stack = 2048; }
788
789 stack as usize
790 })
791}