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(
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 }>(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 pub fn join(self) {
310 let id = self.into_id();
311 let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) };
312 assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
313 }
314
315 pub fn id(&self) -> libc::pthread_t {
316 self.id
317 }
318
319 pub fn into_id(self) -> libc::pthread_t {
320 ManuallyDrop::new(self).id
321 }
322}
323
324impl Drop for Thread {
325 fn drop(&mut self) {
326 let ret = unsafe { libc::pthread_detach(self.id) };
327 debug_assert_eq!(ret, 0);
328 }
329}
330
331#[cfg(any(
332 target_os = "linux",
333 target_os = "nto",
334 target_os = "solaris",
335 target_os = "illumos",
336 target_os = "vxworks",
337 target_os = "cygwin",
338 target_vendor = "apple",
339))]
340fn truncate_cstr<const MAX_WITH_NUL: usize>(cstr: &CStr) -> [libc::c_char; MAX_WITH_NUL] {
341 let mut result = [0; MAX_WITH_NUL];
342 for (src, dst) in cstr.to_bytes().iter().zip(&mut result[..MAX_WITH_NUL - 1]) {
343 *dst = *src as libc::c_char;
344 }
345 result
346}
347
348pub fn available_parallelism() -> io::Result<NonZero<usize>> {
349 cfg_if::cfg_if! {
350 if #[cfg(any(
351 target_os = "android",
352 target_os = "emscripten",
353 target_os = "fuchsia",
354 target_os = "hurd",
355 target_os = "linux",
356 target_os = "aix",
357 target_vendor = "apple",
358 target_os = "cygwin",
359 ))] {
360 #[allow(unused_assignments)]
361 #[allow(unused_mut)]
362 let mut quota = usize::MAX;
363
364 #[cfg(any(target_os = "android", target_os = "linux"))]
365 {
366 quota = cgroups::quota().max(1);
367 let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
368 unsafe {
369 if libc::sched_getaffinity(0, size_of::<libc::cpu_set_t>(), &mut set) == 0 {
370 let count = libc::CPU_COUNT(&set) as usize;
371 let count = count.min(quota);
372
373 if let Some(count) = NonZero::new(count) {
378 return Ok(count)
379 }
380 }
381 }
382 }
383 match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
384 -1 => Err(io::Error::last_os_error()),
385 0 => Err(io::Error::UNKNOWN_THREAD_COUNT),
386 cpus => {
387 let count = cpus as usize;
388 let count = count.min(quota);
390 Ok(unsafe { NonZero::new_unchecked(count) })
391 }
392 }
393 } else if #[cfg(any(
394 target_os = "freebsd",
395 target_os = "dragonfly",
396 target_os = "openbsd",
397 target_os = "netbsd",
398 ))] {
399 use crate::ptr;
400
401 #[cfg(target_os = "freebsd")]
402 {
403 let mut set: libc::cpuset_t = unsafe { mem::zeroed() };
404 unsafe {
405 if libc::cpuset_getaffinity(
406 libc::CPU_LEVEL_WHICH,
407 libc::CPU_WHICH_PID,
408 -1,
409 size_of::<libc::cpuset_t>(),
410 &mut set,
411 ) == 0 {
412 let count = libc::CPU_COUNT(&set) as usize;
413 if count > 0 {
414 return Ok(NonZero::new_unchecked(count));
415 }
416 }
417 }
418 }
419
420 #[cfg(target_os = "netbsd")]
421 {
422 unsafe {
423 let set = libc::_cpuset_create();
424 if !set.is_null() {
425 let mut count: usize = 0;
426 if libc::pthread_getaffinity_np(libc::pthread_self(), libc::_cpuset_size(set), set) == 0 {
427 for i in 0..libc::cpuid_t::MAX {
428 match libc::_cpuset_isset(i, set) {
429 -1 => break,
430 0 => continue,
431 _ => count = count + 1,
432 }
433 }
434 }
435 libc::_cpuset_destroy(set);
436 if let Some(count) = NonZero::new(count) {
437 return Ok(count);
438 }
439 }
440 }
441 }
442
443 let mut cpus: libc::c_uint = 0;
444 let mut cpus_size = size_of_val(&cpus);
445
446 unsafe {
447 cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
448 }
449
450 if cpus < 1 {
452 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
453 let res = unsafe {
454 libc::sysctl(
455 mib.as_mut_ptr(),
456 2,
457 (&raw mut cpus) as *mut _,
458 (&raw mut cpus_size) as *mut _,
459 ptr::null_mut(),
460 0,
461 )
462 };
463
464 if res == -1 {
466 return Err(io::Error::last_os_error());
467 } else if cpus == 0 {
468 return Err(io::Error::UNKNOWN_THREAD_COUNT);
469 }
470 }
471
472 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
473 } else if #[cfg(target_os = "nto")] {
474 unsafe {
475 use libc::_syspage_ptr;
476 if _syspage_ptr.is_null() {
477 Err(io::const_error!(io::ErrorKind::NotFound, "no syspage available"))
478 } else {
479 let cpus = (*_syspage_ptr).num_cpu;
480 NonZero::new(cpus as usize)
481 .ok_or(io::Error::UNKNOWN_THREAD_COUNT)
482 }
483 }
484 } else if #[cfg(any(target_os = "solaris", target_os = "illumos"))] {
485 let mut cpus = 0u32;
486 if unsafe { libc::pset_info(libc::PS_MYID, core::ptr::null_mut(), &mut cpus, core::ptr::null_mut()) } != 0 {
487 return Err(io::Error::UNKNOWN_THREAD_COUNT);
488 }
489 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
490 } else if #[cfg(target_os = "haiku")] {
491 unsafe {
494 let mut sinfo: libc::system_info = crate::mem::zeroed();
495 let res = libc::get_system_info(&mut sinfo);
496
497 if res != libc::B_OK {
498 return Err(io::Error::UNKNOWN_THREAD_COUNT);
499 }
500
501 Ok(NonZero::new_unchecked(sinfo.cpu_count as usize))
502 }
503 } else if #[cfg(target_os = "vxworks")] {
504 unsafe extern "C" {
507 fn vxCpuEnabledGet() -> libc::cpuset_t;
508 }
509
510 unsafe{
512 let set = vxCpuEnabledGet();
513 Ok(NonZero::new_unchecked(set.count_ones() as usize))
514 }
515 } else {
516 Err(io::const_error!(io::ErrorKind::Unsupported, "getting the number of hardware threads is not supported on the target platform"))
518 }
519 }
520}
521
522#[cfg(any(target_os = "android", target_os = "linux"))]
523mod cgroups {
524 use crate::borrow::Cow;
530 use crate::ffi::OsString;
531 use crate::fs::{File, exists};
532 use crate::io::{BufRead, Read};
533 use crate::os::unix::ffi::OsStringExt;
534 use crate::path::{Path, PathBuf};
535 use crate::str::from_utf8;
536
537 #[derive(PartialEq)]
538 enum Cgroup {
539 V1,
540 V2,
541 }
542
543 pub(super) fn quota() -> usize {
546 let mut quota = usize::MAX;
547 if cfg!(miri) {
548 return quota;
551 }
552
553 let _: Option<()> = try {
554 let mut buf = Vec::with_capacity(128);
555 File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
557 let (cgroup_path, version) =
558 buf.split(|&c| c == b'\n').fold(None, |previous, line| {
559 let mut fields = line.splitn(3, |&c| c == b':');
560 let version = match fields.nth(1) {
562 Some(b"") => Cgroup::V2,
563 Some(controllers)
564 if from_utf8(controllers)
565 .is_ok_and(|c| c.split(',').any(|c| c == "cpu")) =>
566 {
567 Cgroup::V1
568 }
569 _ => return previous,
570 };
571
572 if previous.is_some() && version == Cgroup::V2 {
574 return previous;
575 }
576
577 let path = fields.last()?;
578 Some((path[1..].to_owned(), version))
580 })?;
581 let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));
582
583 quota = match version {
584 Cgroup::V1 => quota_v1(cgroup_path),
585 Cgroup::V2 => quota_v2(cgroup_path),
586 };
587 };
588
589 quota
590 }
591
592 fn quota_v2(group_path: PathBuf) -> usize {
593 let mut quota = usize::MAX;
594
595 let mut path = PathBuf::with_capacity(128);
596 let mut read_buf = String::with_capacity(20);
597
598 let cgroup_mount = "/sys/fs/cgroup";
600
601 path.push(cgroup_mount);
602 path.push(&group_path);
603
604 path.push("cgroup.controllers");
605
606 if matches!(exists(&path), Err(_) | Ok(false)) {
608 return usize::MAX;
609 };
610
611 path.pop();
612
613 let _: Option<()> = try {
614 while path.starts_with(cgroup_mount) {
615 path.push("cpu.max");
616
617 read_buf.clear();
618
619 if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
620 let raw_quota = read_buf.lines().next()?;
621 let mut raw_quota = raw_quota.split(' ');
622 let limit = raw_quota.next()?;
623 let period = raw_quota.next()?;
624 match (limit.parse::<usize>(), period.parse::<usize>()) {
625 (Ok(limit), Ok(period)) if period > 0 => {
626 quota = quota.min(limit / period);
627 }
628 _ => {}
629 }
630 }
631
632 path.pop(); path.pop(); }
635 };
636
637 quota
638 }
639
640 fn quota_v1(group_path: PathBuf) -> usize {
641 let mut quota = usize::MAX;
642 let mut path = PathBuf::with_capacity(128);
643 let mut read_buf = String::with_capacity(20);
644
645 let mounts: &[fn(&Path) -> Option<(_, &Path)>] = &[
648 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu"), p)),
649 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu,cpuacct"), p)),
650 find_mountpoint,
654 ];
655
656 for mount in mounts {
657 let Some((mount, group_path)) = mount(&group_path) else { continue };
658
659 path.clear();
660 path.push(mount.as_ref());
661 path.push(&group_path);
662
663 if matches!(exists(&path), Err(_) | Ok(false)) {
665 continue;
666 }
667
668 while path.starts_with(mount.as_ref()) {
669 let mut parse_file = |name| {
670 path.push(name);
671 read_buf.clear();
672
673 let f = File::open(&path);
674 path.pop(); f.ok()?.read_to_string(&mut read_buf).ok()?;
676 let parsed = read_buf.trim().parse::<usize>().ok()?;
677
678 Some(parsed)
679 };
680
681 let limit = parse_file("cpu.cfs_quota_us");
682 let period = parse_file("cpu.cfs_period_us");
683
684 match (limit, period) {
685 (Some(limit), Some(period)) if period > 0 => quota = quota.min(limit / period),
686 _ => {}
687 }
688
689 path.pop();
690 }
691
692 break;
695 }
696
697 quota
698 }
699
700 fn find_mountpoint(group_path: &Path) -> Option<(Cow<'static, str>, &Path)> {
705 let mut reader = File::open_buffered("/proc/self/mountinfo").ok()?;
706 let mut line = String::with_capacity(256);
707 loop {
708 line.clear();
709 if reader.read_line(&mut line).ok()? == 0 {
710 break;
711 }
712
713 let line = line.trim();
714 let mut items = line.split(' ');
715
716 let sub_path = items.nth(3)?;
717 let mount_point = items.next()?;
718 let mount_opts = items.next_back()?;
719 let filesystem_type = items.nth_back(1)?;
720
721 if filesystem_type != "cgroup" || !mount_opts.split(',').any(|opt| opt == "cpu") {
722 continue;
724 }
725
726 let sub_path = Path::new(sub_path).strip_prefix("/").ok()?;
727
728 if !group_path.starts_with(sub_path) {
729 continue;
732 }
733
734 let trimmed_group_path = group_path.strip_prefix(sub_path).ok()?;
735
736 return Some((Cow::Owned(mount_point.to_owned()), trimmed_group_path));
737 }
738
739 None
740 }
741}
742
743#[cfg(all(target_os = "linux", target_env = "gnu"))]
749unsafe fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
750 dlsym!(
754 fn __pthread_get_minstack(attr: *const libc::pthread_attr_t) -> libc::size_t;
755 );
756
757 match __pthread_get_minstack.get() {
758 None => libc::PTHREAD_STACK_MIN,
759 Some(f) => unsafe { f(attr) },
760 }
761}
762
763#[cfg(all(
765 not(all(target_os = "linux", target_env = "gnu")),
766 not(any(target_os = "netbsd", target_os = "nuttx"))
767))]
768unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
769 libc::PTHREAD_STACK_MIN
770}
771
772#[cfg(any(target_os = "netbsd", target_os = "nuttx"))]
773unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
774 static STACK: crate::sync::OnceLock<usize> = crate::sync::OnceLock::new();
775
776 *STACK.get_or_init(|| {
777 let mut stack = unsafe { libc::sysconf(libc::_SC_THREAD_STACK_MIN) };
778 if stack < 0 {
779 stack = 2048; }
781
782 stack as usize
783 })
784}