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 target_os = "cygwin"
142 ))]
143 pub fn set_name(name: &CStr) {
144 unsafe {
145 cfg_if::cfg_if! {
146 if #[cfg(target_os = "linux")] {
147 const TASK_COMM_LEN: usize = 16;
149 let name = truncate_cstr::<{ TASK_COMM_LEN }>(name);
150 } else {
151 }
153 };
154 let res = libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());
157 debug_assert_eq!(res, 0);
159 }
160 }
161
162 #[cfg(target_os = "openbsd")]
163 pub fn set_name(name: &CStr) {
164 unsafe {
165 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
166 }
167 }
168
169 #[cfg(target_vendor = "apple")]
170 pub fn set_name(name: &CStr) {
171 unsafe {
172 let name = truncate_cstr::<{ libc::MAXTHREADNAMESIZE }>(name);
173 let res = libc::pthread_setname_np(name.as_ptr());
174 debug_assert_eq!(res, 0);
176 }
177 }
178
179 #[cfg(target_os = "netbsd")]
180 pub fn set_name(name: &CStr) {
181 unsafe {
182 let res = libc::pthread_setname_np(
183 libc::pthread_self(),
184 c"%s".as_ptr(),
185 name.as_ptr() as *mut libc::c_void,
186 );
187 debug_assert_eq!(res, 0);
188 }
189 }
190
191 #[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto"))]
192 #[no_sanitize(cfi)]
195 pub fn set_name(name: &CStr) {
196 weak! {
197 fn pthread_setname_np(
198 libc::pthread_t, *const libc::c_char
199 ) -> libc::c_int
200 }
201
202 if let Some(f) = pthread_setname_np.get() {
203 #[cfg(target_os = "nto")]
204 const THREAD_NAME_MAX: usize = libc::_NTO_THREAD_NAME_MAX as usize;
205 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
206 const THREAD_NAME_MAX: usize = 32;
207
208 let name = truncate_cstr::<{ THREAD_NAME_MAX }>(name);
209 let res = unsafe { f(libc::pthread_self(), name.as_ptr()) };
210 debug_assert_eq!(res, 0);
211 }
212 }
213
214 #[cfg(target_os = "fuchsia")]
215 pub fn set_name(name: &CStr) {
216 use self::zircon::*;
217 unsafe {
218 zx_object_set_property(
219 zx_thread_self(),
220 ZX_PROP_NAME,
221 name.as_ptr() as *const libc::c_void,
222 name.to_bytes().len(),
223 );
224 }
225 }
226
227 #[cfg(target_os = "haiku")]
228 pub fn set_name(name: &CStr) {
229 unsafe {
230 let thread_self = libc::find_thread(ptr::null_mut());
231 let res = libc::rename_thread(thread_self, name.as_ptr());
232 debug_assert_eq!(res, libc::B_OK);
234 }
235 }
236
237 #[cfg(target_os = "vxworks")]
238 pub fn set_name(name: &CStr) {
239 unsafe extern "C" {
241 fn taskNameSet(task_id: libc::TASK_ID, task_name: *mut libc::c_char) -> libc::c_int;
242 }
243
244 const VX_TASK_NAME_LEN: usize = 31;
246
247 let mut name = truncate_cstr::<{ VX_TASK_NAME_LEN }>(name);
248 let res = unsafe { 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 pub fn join(self) {
322 let id = self.into_id();
323 let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) };
324 assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
325 }
326
327 pub fn id(&self) -> libc::pthread_t {
328 self.id
329 }
330
331 pub fn into_id(self) -> libc::pthread_t {
332 ManuallyDrop::new(self).id
333 }
334}
335
336impl Drop for Thread {
337 fn drop(&mut self) {
338 let ret = unsafe { libc::pthread_detach(self.id) };
339 debug_assert_eq!(ret, 0);
340 }
341}
342
343#[cfg(any(
344 target_os = "linux",
345 target_os = "nto",
346 target_os = "solaris",
347 target_os = "illumos",
348 target_os = "vxworks",
349 target_vendor = "apple",
350))]
351fn truncate_cstr<const MAX_WITH_NUL: usize>(cstr: &CStr) -> [libc::c_char; MAX_WITH_NUL] {
352 let mut result = [0; MAX_WITH_NUL];
353 for (src, dst) in cstr.to_bytes().iter().zip(&mut result[..MAX_WITH_NUL - 1]) {
354 *dst = *src as libc::c_char;
355 }
356 result
357}
358
359pub fn available_parallelism() -> io::Result<NonZero<usize>> {
360 cfg_if::cfg_if! {
361 if #[cfg(any(
362 target_os = "android",
363 target_os = "emscripten",
364 target_os = "fuchsia",
365 target_os = "hurd",
366 target_os = "linux",
367 target_os = "aix",
368 target_vendor = "apple",
369 target_os = "cygwin",
370 ))] {
371 #[allow(unused_assignments)]
372 #[allow(unused_mut)]
373 let mut quota = usize::MAX;
374
375 #[cfg(any(target_os = "android", target_os = "linux"))]
376 {
377 quota = cgroups::quota().max(1);
378 let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
379 unsafe {
380 if libc::sched_getaffinity(0, size_of::<libc::cpu_set_t>(), &mut set) == 0 {
381 let count = libc::CPU_COUNT(&set) as usize;
382 let count = count.min(quota);
383
384 if let Some(count) = NonZero::new(count) {
389 return Ok(count)
390 }
391 }
392 }
393 }
394 match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
395 -1 => Err(io::Error::last_os_error()),
396 0 => Err(io::Error::UNKNOWN_THREAD_COUNT),
397 cpus => {
398 let count = cpus as usize;
399 let count = count.min(quota);
401 Ok(unsafe { NonZero::new_unchecked(count) })
402 }
403 }
404 } else if #[cfg(any(
405 target_os = "freebsd",
406 target_os = "dragonfly",
407 target_os = "openbsd",
408 target_os = "netbsd",
409 ))] {
410 use crate::ptr;
411
412 #[cfg(target_os = "freebsd")]
413 {
414 let mut set: libc::cpuset_t = unsafe { mem::zeroed() };
415 unsafe {
416 if libc::cpuset_getaffinity(
417 libc::CPU_LEVEL_WHICH,
418 libc::CPU_WHICH_PID,
419 -1,
420 size_of::<libc::cpuset_t>(),
421 &mut set,
422 ) == 0 {
423 let count = libc::CPU_COUNT(&set) as usize;
424 if count > 0 {
425 return Ok(NonZero::new_unchecked(count));
426 }
427 }
428 }
429 }
430
431 #[cfg(target_os = "netbsd")]
432 {
433 unsafe {
434 let set = libc::_cpuset_create();
435 if !set.is_null() {
436 let mut count: usize = 0;
437 if libc::pthread_getaffinity_np(libc::pthread_self(), libc::_cpuset_size(set), set) == 0 {
438 for i in 0..libc::cpuid_t::MAX {
439 match libc::_cpuset_isset(i, set) {
440 -1 => break,
441 0 => continue,
442 _ => count = count + 1,
443 }
444 }
445 }
446 libc::_cpuset_destroy(set);
447 if let Some(count) = NonZero::new(count) {
448 return Ok(count);
449 }
450 }
451 }
452 }
453
454 let mut cpus: libc::c_uint = 0;
455 let mut cpus_size = size_of_val(&cpus);
456
457 unsafe {
458 cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
459 }
460
461 if cpus < 1 {
463 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
464 let res = unsafe {
465 libc::sysctl(
466 mib.as_mut_ptr(),
467 2,
468 (&raw mut cpus) as *mut _,
469 (&raw mut cpus_size) as *mut _,
470 ptr::null_mut(),
471 0,
472 )
473 };
474
475 if res == -1 {
477 return Err(io::Error::last_os_error());
478 } else if cpus == 0 {
479 return Err(io::Error::UNKNOWN_THREAD_COUNT);
480 }
481 }
482
483 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
484 } else if #[cfg(target_os = "nto")] {
485 unsafe {
486 use libc::_syspage_ptr;
487 if _syspage_ptr.is_null() {
488 Err(io::const_error!(io::ErrorKind::NotFound, "no syspage available"))
489 } else {
490 let cpus = (*_syspage_ptr).num_cpu;
491 NonZero::new(cpus as usize)
492 .ok_or(io::Error::UNKNOWN_THREAD_COUNT)
493 }
494 }
495 } else if #[cfg(any(target_os = "solaris", target_os = "illumos"))] {
496 let mut cpus = 0u32;
497 if unsafe { libc::pset_info(libc::PS_MYID, core::ptr::null_mut(), &mut cpus, core::ptr::null_mut()) } != 0 {
498 return Err(io::Error::UNKNOWN_THREAD_COUNT);
499 }
500 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
501 } else if #[cfg(target_os = "haiku")] {
502 unsafe {
505 let mut sinfo: libc::system_info = crate::mem::zeroed();
506 let res = libc::get_system_info(&mut sinfo);
507
508 if res != libc::B_OK {
509 return Err(io::Error::UNKNOWN_THREAD_COUNT);
510 }
511
512 Ok(NonZero::new_unchecked(sinfo.cpu_count as usize))
513 }
514 } else if #[cfg(target_os = "vxworks")] {
515 unsafe extern "C" {
518 fn vxCpuEnabledGet() -> libc::cpuset_t;
519 }
520
521 unsafe{
523 let set = vxCpuEnabledGet();
524 Ok(NonZero::new_unchecked(set.count_ones() as usize))
525 }
526 } else {
527 Err(io::const_error!(io::ErrorKind::Unsupported, "getting the number of hardware threads is not supported on the target platform"))
529 }
530 }
531}
532
533#[cfg(any(target_os = "android", target_os = "linux"))]
534mod cgroups {
535 use crate::borrow::Cow;
541 use crate::ffi::OsString;
542 use crate::fs::{File, exists};
543 use crate::io::{BufRead, Read};
544 use crate::os::unix::ffi::OsStringExt;
545 use crate::path::{Path, PathBuf};
546 use crate::str::from_utf8;
547
548 #[derive(PartialEq)]
549 enum Cgroup {
550 V1,
551 V2,
552 }
553
554 pub(super) fn quota() -> usize {
557 let mut quota = usize::MAX;
558 if cfg!(miri) {
559 return quota;
562 }
563
564 let _: Option<()> = try {
565 let mut buf = Vec::with_capacity(128);
566 File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
568 let (cgroup_path, version) =
569 buf.split(|&c| c == b'\n').fold(None, |previous, line| {
570 let mut fields = line.splitn(3, |&c| c == b':');
571 let version = match fields.nth(1) {
573 Some(b"") => Cgroup::V2,
574 Some(controllers)
575 if from_utf8(controllers)
576 .is_ok_and(|c| c.split(',').any(|c| c == "cpu")) =>
577 {
578 Cgroup::V1
579 }
580 _ => return previous,
581 };
582
583 if previous.is_some() && version == Cgroup::V2 {
585 return previous;
586 }
587
588 let path = fields.last()?;
589 Some((path[1..].to_owned(), version))
591 })?;
592 let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));
593
594 quota = match version {
595 Cgroup::V1 => quota_v1(cgroup_path),
596 Cgroup::V2 => quota_v2(cgroup_path),
597 };
598 };
599
600 quota
601 }
602
603 fn quota_v2(group_path: PathBuf) -> usize {
604 let mut quota = usize::MAX;
605
606 let mut path = PathBuf::with_capacity(128);
607 let mut read_buf = String::with_capacity(20);
608
609 let cgroup_mount = "/sys/fs/cgroup";
611
612 path.push(cgroup_mount);
613 path.push(&group_path);
614
615 path.push("cgroup.controllers");
616
617 if matches!(exists(&path), Err(_) | Ok(false)) {
619 return usize::MAX;
620 };
621
622 path.pop();
623
624 let _: Option<()> = try {
625 while path.starts_with(cgroup_mount) {
626 path.push("cpu.max");
627
628 read_buf.clear();
629
630 if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
631 let raw_quota = read_buf.lines().next()?;
632 let mut raw_quota = raw_quota.split(' ');
633 let limit = raw_quota.next()?;
634 let period = raw_quota.next()?;
635 match (limit.parse::<usize>(), period.parse::<usize>()) {
636 (Ok(limit), Ok(period)) if period > 0 => {
637 quota = quota.min(limit / period);
638 }
639 _ => {}
640 }
641 }
642
643 path.pop(); path.pop(); }
646 };
647
648 quota
649 }
650
651 fn quota_v1(group_path: PathBuf) -> usize {
652 let mut quota = usize::MAX;
653 let mut path = PathBuf::with_capacity(128);
654 let mut read_buf = String::with_capacity(20);
655
656 let mounts: &[fn(&Path) -> Option<(_, &Path)>] = &[
659 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu"), p)),
660 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu,cpuacct"), p)),
661 find_mountpoint,
665 ];
666
667 for mount in mounts {
668 let Some((mount, group_path)) = mount(&group_path) else { continue };
669
670 path.clear();
671 path.push(mount.as_ref());
672 path.push(&group_path);
673
674 if matches!(exists(&path), Err(_) | Ok(false)) {
676 continue;
677 }
678
679 while path.starts_with(mount.as_ref()) {
680 let mut parse_file = |name| {
681 path.push(name);
682 read_buf.clear();
683
684 let f = File::open(&path);
685 path.pop(); f.ok()?.read_to_string(&mut read_buf).ok()?;
687 let parsed = read_buf.trim().parse::<usize>().ok()?;
688
689 Some(parsed)
690 };
691
692 let limit = parse_file("cpu.cfs_quota_us");
693 let period = parse_file("cpu.cfs_period_us");
694
695 match (limit, period) {
696 (Some(limit), Some(period)) if period > 0 => quota = quota.min(limit / period),
697 _ => {}
698 }
699
700 path.pop();
701 }
702
703 break;
706 }
707
708 quota
709 }
710
711 fn find_mountpoint(group_path: &Path) -> Option<(Cow<'static, str>, &Path)> {
716 let mut reader = File::open_buffered("/proc/self/mountinfo").ok()?;
717 let mut line = String::with_capacity(256);
718 loop {
719 line.clear();
720 if reader.read_line(&mut line).ok()? == 0 {
721 break;
722 }
723
724 let line = line.trim();
725 let mut items = line.split(' ');
726
727 let sub_path = items.nth(3)?;
728 let mount_point = items.next()?;
729 let mount_opts = items.next_back()?;
730 let filesystem_type = items.nth_back(1)?;
731
732 if filesystem_type != "cgroup" || !mount_opts.split(',').any(|opt| opt == "cpu") {
733 continue;
735 }
736
737 let sub_path = Path::new(sub_path).strip_prefix("/").ok()?;
738
739 if !group_path.starts_with(sub_path) {
740 continue;
743 }
744
745 let trimmed_group_path = group_path.strip_prefix(sub_path).ok()?;
746
747 return Some((Cow::Owned(mount_point.to_owned()), trimmed_group_path));
748 }
749
750 None
751 }
752}
753
754#[cfg(all(target_os = "linux", target_env = "gnu"))]
760unsafe fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
761 dlsym!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
765
766 match __pthread_get_minstack.get() {
767 None => libc::PTHREAD_STACK_MIN,
768 Some(f) => unsafe { f(attr) },
769 }
770}
771
772#[cfg(all(
774 not(all(target_os = "linux", target_env = "gnu")),
775 not(any(target_os = "netbsd", target_os = "nuttx"))
776))]
777unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
778 libc::PTHREAD_STACK_MIN
779}
780
781#[cfg(any(target_os = "netbsd", target_os = "nuttx"))]
782unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
783 static STACK: crate::sync::OnceLock<usize> = crate::sync::OnceLock::new();
784
785 *STACK.get_or_init(|| {
786 let mut stack = unsafe { libc::sysconf(libc::_SC_THREAD_STACK_MIN) };
787 if stack < 0 {
788 stack = 2048; }
790
791 stack as usize
792 })
793}