1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
use crate::cmp;
use crate::ffi::CStr;
use crate::io;
use crate::mem;
use crate::num::NonZeroUsize;
use crate::ptr;
use crate::sys::{os, stack_overflow};
use crate::time::Duration;

#[cfg(all(target_os = "linux", target_env = "gnu"))]
use crate::sys::weak::dlsym;
#[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto"))]
use crate::sys::weak::weak;
#[cfg(not(any(target_os = "l4re", target_os = "vxworks", target_os = "espidf")))]
pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
#[cfg(target_os = "l4re")]
pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024;
#[cfg(target_os = "vxworks")]
pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 1024;
#[cfg(target_os = "espidf")]
pub const DEFAULT_MIN_STACK_SIZE: usize = 0; // 0 表示应使用 ESP-IDF menuconfig 系统中配置的栈大小

#[cfg(target_os = "fuchsia")]
mod zircon {
    type zx_handle_t = u32;
    type zx_status_t = i32;
    pub const ZX_PROP_NAME: u32 = 3;

    extern "C" {
        pub fn zx_object_set_property(
            handle: zx_handle_t,
            property: u32,
            value: *const libc::c_void,
            value_size: libc::size_t,
        ) -> zx_status_t;
        pub fn zx_thread_self() -> zx_handle_t;
    }
}

pub struct Thread {
    id: libc::pthread_t,
}

// 某些平台可能将 pthread_t 用作指针,在这种情况下,我们仍然希望线程为 Send/Sync
//
unsafe impl Send for Thread {}
unsafe impl Sync for Thread {}

impl Thread {
    // 不安全:有关安全要求,请参见 thread::Builder::spawn_unchecked
    pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
        let p = Box::into_raw(Box::new(p));
        let mut native: libc::pthread_t = mem::zeroed();
        let mut attr: libc::pthread_attr_t = mem::zeroed();
        assert_eq!(libc::pthread_attr_init(&mut attr), 0);

        #[cfg(target_os = "espidf")]
        if stack > 0 {
            // 仅在传递非零值时才设置栈
            // 0 用作指示应使用 ESP-IDF menuconfig 系统中配置的默认栈大小
            assert_eq!(
                libc::pthread_attr_setstacksize(&mut attr, cmp::max(stack, min_stack_size(&attr))),
                0
            );
        }

        #[cfg(not(target_os = "espidf"))]
        {
            let stack_size = cmp::max(stack, min_stack_size(&attr));

            match libc::pthread_attr_setstacksize(&mut attr, stack_size) {
                0 => {}
                n => {
                    assert_eq!(n, libc::EINVAL);
                    // EINVAL 表示 | stack_size | 太小或不是系统页面大小的倍数。
                    // 因为肯定是 >= PTHREAD_STACK_MIN,所以它一定是对齐问题。
                    // 向上舍入到最近的页面,然后重试。
                    //
                    let page_size = os::page_size();
                    let stack_size =
                        (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
                    assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0);
                }
            };
        }

        let ret = libc::pthread_create(&mut native, &attr, thread_start, p as *mut _);
        // Note: 如果线程创建失败并且该断言失败,则 p 将被泄漏。
        // 但是,替代设计可能会导致双重释放,这显然更糟。
        //
        assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);

        return if ret != 0 {
            // 线程无法启动,结果 p 没有被消费。
            // 因此,重建 box 使其被释放是安全的。
            drop(Box::from_raw(p));
            Err(io::Error::from_raw_os_error(ret))
        } else {
            Ok(Thread { id: native })
        };

        extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
            unsafe {
                // 接下来,设置我们的栈溢出处理程序,如果我们用完栈,可能会触发该处理程序。
                //
                let _handler = stack_overflow::Handler::new();
                // 最后,让我们运行一些代码。
                Box::from_raw(main as *mut Box<dyn FnOnce()>)();
            }
            ptr::null_mut()
        }
    }

    pub fn yield_now() {
        let ret = unsafe { libc::sched_yield() };
        debug_assert_eq!(ret, 0);
    }

    #[cfg(target_os = "android")]
    pub fn set_name(name: &CStr) {
        const PR_SET_NAME: libc::c_int = 15;
        unsafe {
            libc::prctl(
                PR_SET_NAME,
                name.as_ptr(),
                0 as libc::c_ulong,
                0 as libc::c_ulong,
                0 as libc::c_ulong,
            );
        }
    }

    #[cfg(target_os = "linux")]
    pub fn set_name(name: &CStr) {
        const TASK_COMM_LEN: usize = 16;

        unsafe {
            // 从 glibc 2.12、musl 1.1.16 和 uClibc 1.0.20 开始可用。
            let name = truncate_cstr::<{ TASK_COMM_LEN }>(name);
            let res = libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());
            // 我们没有在这里传播错误的好方法,但是在调试构建中,让我们检查一下这是否真的有效。
            debug_assert_eq!(res, 0);
        }
    }

    #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd"))]
    pub fn set_name(name: &CStr) {
        unsafe {
            libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
        }
    }

    #[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
    pub fn set_name(name: &CStr) {
        unsafe {
            let name = truncate_cstr::<{ libc::MAXTHREADNAMESIZE }>(name);
            let res = libc::pthread_setname_np(name.as_ptr());
            // 我们没有在这里传播错误的好方法,但是在调试构建中,让我们检查一下这是否真的有效。
            debug_assert_eq!(res, 0);
        }
    }

    #[cfg(target_os = "netbsd")]
    pub fn set_name(name: &CStr) {
        unsafe {
            let cname = CStr::from_bytes_with_nul_unchecked(b"%s\0".as_slice());
            let res = libc::pthread_setname_np(
                libc::pthread_self(),
                cname.as_ptr(),
                name.as_ptr() as *mut libc::c_void,
            );
            debug_assert_eq!(res, 0);
        }
    }

    #[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto"))]
    pub fn set_name(name: &CStr) {
        weak! {
            fn pthread_setname_np(
                libc::pthread_t, *const libc::c_char
            ) -> libc::c_int
        }

        if let Some(f) = pthread_setname_np.get() {
            let res = unsafe { f(libc::pthread_self(), name.as_ptr()) };
            debug_assert_eq!(res, 0);
        }
    }

    #[cfg(target_os = "fuchsia")]
    pub fn set_name(name: &CStr) {
        use self::zircon::*;
        unsafe {
            zx_object_set_property(
                zx_thread_self(),
                ZX_PROP_NAME,
                name.as_ptr() as *const libc::c_void,
                name.to_bytes().len(),
            );
        }
    }

    #[cfg(target_os = "haiku")]
    pub fn set_name(name: &CStr) {
        unsafe {
            let thread_self = libc::find_thread(ptr::null_mut());
            libc::rename_thread(thread_self, name.as_ptr());
        }
    }

    #[cfg(any(
        target_env = "newlib",
        target_os = "l4re",
        target_os = "emscripten",
        target_os = "redox",
        target_os = "vxworks"
    ))]
    pub fn set_name(_name: &CStr) {
        // Newlib、Emscripten 和 VxWorks 无法设置线程名称。
    }

    #[cfg(not(target_os = "espidf"))]
    pub fn sleep(dur: Duration) {
        let mut secs = dur.as_secs();
        let mut nsecs = dur.subsec_nanos() as _;

        // 如果我们被信号唤醒,则返回值为 -1,nanosleep 将使用剩余时间填充 `ts`。
        //
        unsafe {
            while secs > 0 || nsecs > 0 {
                let mut ts = libc::timespec {
                    tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
                    tv_nsec: nsecs,
                };
                secs -= ts.tv_sec as u64;
                let ts_ptr = &mut ts as *mut _;
                if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
                    assert_eq!(os::errno(), libc::EINTR);
                    secs += ts.tv_sec as u64;
                    nsecs = ts.tv_nsec;
                } else {
                    nsecs = 0;
                }
            }
        }
    }

    #[cfg(target_os = "espidf")]
    pub fn sleep(dur: Duration) {
        let mut micros = dur.as_micros();
        unsafe {
            while micros > 0 {
                let st = if micros > u32::MAX as u128 { u32::MAX } else { micros as u32 };
                libc::usleep(st);

                micros -= st as u128;
            }
        }
    }

    pub fn join(self) {
        unsafe {
            let ret = libc::pthread_join(self.id, ptr::null_mut());
            mem::forget(self);
            assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
        }
    }

    pub fn id(&self) -> libc::pthread_t {
        self.id
    }

    pub fn into_id(self) -> libc::pthread_t {
        let id = self.id;
        mem::forget(self);
        id
    }
}

impl Drop for Thread {
    fn drop(&mut self) {
        let ret = unsafe { libc::pthread_detach(self.id) };
        debug_assert_eq!(ret, 0);
    }
}

#[cfg(any(target_os = "linux", target_os = "macos", target_os = "ios", target_os = "watchos"))]
fn truncate_cstr<const MAX_WITH_NUL: usize>(cstr: &CStr) -> [libc::c_char; MAX_WITH_NUL] {
    let mut result = [0; MAX_WITH_NUL];
    for (src, dst) in cstr.to_bytes().iter().zip(&mut result[..MAX_WITH_NUL - 1]) {
        *dst = *src as libc::c_char;
    }
    result
}

pub fn available_parallelism() -> io::Result<NonZeroUsize> {
    cfg_if::cfg_if! {
        if #[cfg(any(
            target_os = "android",
            target_os = "emscripten",
            target_os = "fuchsia",
            target_os = "ios",
            target_os = "linux",
            target_os = "macos",
            target_os = "solaris",
            target_os = "illumos",
        ))] {
            #[cfg(any(target_os = "android", target_os = "linux"))]
            {
                let quota = cgroups::quota().max(1);
                let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
                unsafe {
                    if libc::sched_getaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mut set) == 0 {
                        let count = libc::CPU_COUNT(&set) as usize;
                        let count = count.min(quota);
                        // SAFETY: 关联掩码不能为空,并且配额被限制为至少 1
                        return Ok(NonZeroUsize::new_unchecked(count));
                    }
                }
            }
            match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
                -1 => Err(io::Error::last_os_error()),
                0 => Err(io::const_io_error!(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform")),
                cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) }),
            }
        } else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd"))] {
            use crate::ptr;

            #[cfg(target_os = "freebsd")]
            {
                let mut set: libc::cpuset_t = unsafe { mem::zeroed() };
                unsafe {
                    if libc::cpuset_getaffinity(
                        libc::CPU_LEVEL_WHICH,
                        libc::CPU_WHICH_PID,
                        -1,
                        mem::size_of::<libc::cpuset_t>(),
                        &mut set,
                    ) == 0 {
                        let count = libc::CPU_COUNT(&set) as usize;
                        if count > 0 {
                            return Ok(NonZeroUsize::new_unchecked(count));
                        }
                    }
                }
            }

            let mut cpus: libc::c_uint = 0;
            let mut cpus_size = crate::mem::size_of_val(&cpus);

            unsafe {
                cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
            }

            // 在出现错误或没有硬件线程的情况下的后备方法。
            if cpus < 1 {
                let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
                let res = unsafe {
                    libc::sysctl(
                        mib.as_mut_ptr(),
                        2,
                        &mut cpus as *mut _ as *mut _,
                        &mut cpus_size as *mut _ as *mut _,
                        ptr::null_mut(),
                        0,
                    )
                };

                // 处理错误 (如果有)。
                if res == -1 {
                    return Err(io::Error::last_os_error());
                } else if cpus == 0 {
                    return Err(io::const_io_error!(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform"));
                }
            }
            Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) })
        } else if #[cfg(target_os = "openbsd")] {
            use crate::ptr;

            let mut cpus: libc::c_uint = 0;
            let mut cpus_size = crate::mem::size_of_val(&cpus);
            let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];

            let res = unsafe {
                libc::sysctl(
                    mib.as_mut_ptr(),
                    2,
                    &mut cpus as *mut _ as *mut _,
                    &mut cpus_size as *mut _ as *mut _,
                    ptr::null_mut(),
                    0,
                )
            };

            // 处理错误 (如果有)。
            if res == -1 {
                return Err(io::Error::last_os_error());
            } else if cpus == 0 {
                return Err(io::const_io_error!(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform"));
            }

            Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) })
        } else if #[cfg(target_os = "nto")] {
            unsafe {
                use libc::_syspage_ptr;
                if _syspage_ptr.is_null() {
                    Err(io::const_io_error!(io::ErrorKind::NotFound, "No syspage available"))
                } else {
                    let cpus = (*_syspage_ptr).num_cpu;
                    NonZeroUsize::new(cpus as usize)
                        .ok_or(io::const_io_error!(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform"))
                }
            }
        } else if #[cfg(target_os = "haiku")] {
            // system_info cpu_count 字段在启动时使用 `smp_set_num_cpus` `get_system_info` 调用然后 `smp_get_num_cpus` 获取静态数据集
            //
            unsafe {
                let mut sinfo: libc::system_info = crate::mem::zeroed();
                let res = libc::get_system_info(&mut sinfo);

                if res != libc::B_OK {
                    return Err(io::const_io_error!(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform"));
                }

                Ok(NonZeroUsize::new_unchecked(sinfo.cpu_count as usize))
            }
        } else {
            // FIXME: 在 vxWorks、Redox、l4re 上实现
            Err(io::const_io_error!(io::ErrorKind::Unsupported, "Getting the number of hardware threads is not supported on the target platform"))
        }
    }
}

#[cfg(any(target_os = "android", target_os = "linux"))]
mod cgroups {
    //! 目前没有被覆盖
    //! * 非标准挂载点中的 cgroup v2
    //! * 包含控制字符或空格的路径,因为它们会在 procfs 输出中转义,我们不会取消转义
    //!
    use crate::borrow::Cow;
    use crate::ffi::OsString;
    use crate::fs::{try_exists, File};
    use crate::io::Read;
    use crate::io::{BufRead, BufReader};
    use crate::os::unix::ffi::OsStringExt;
    use crate::path::Path;
    use crate::path::PathBuf;
    use crate::str::from_utf8;

    #[derive(PartialEq)]
    enum Cgroup {
        V1,
        V2,
    }

    /// 如果配额无法确定或未设置,则以核心等价物返回 cgroup CPU 配额,向下舍入或 usize::MAX。
    ///
    pub(super) fn quota() -> usize {
        let mut quota = usize::MAX;
        if cfg!(miri) {
            // 由于隔离,在默认标志下尝试打开文件会失败。
            // 而且 Miri 无论如何都没有并行性。
            return quota;
        }

        let _: Option<()> = try {
            let mut buf = Vec::with_capacity(128);
            // 在 cgroup 层次结构中找到我们的位置
            File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
            let (cgroup_path, version) =
                buf.split(|&c| c == b'\n').fold(None, |previous, line| {
                    let mut fields = line.splitn(3, |&c| c == b':');
                    // 第二个字段是 v1 的控制器列表或 v2 为空
                    let version = match fields.nth(1) {
                        Some(b"") => Cgroup::V2,
                        Some(controllers)
                            if from_utf8(controllers)
                                .is_ok_and(|c| c.split(',').any(|c| c == "cpu")) =>
                        {
                            Cgroup::V1
                        }
                        _ => return previous,
                    };

                    // 已经找到的 v1 胜过 v2,因为它明确指定了它的控制器
                    if previous.is_some() && version == Cgroup::V2 {
                        return previous;
                    }

                    let path = fields.last()?;
                    // 跳过前导斜杠
                    Some((path[1..].to_owned(), version))
                })?;
            let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));

            quota = match version {
                Cgroup::V1 => quota_v1(cgroup_path),
                Cgroup::V2 => quota_v2(cgroup_path),
            };
        };

        quota
    }

    fn quota_v2(group_path: PathBuf) -> usize {
        let mut quota = usize::MAX;

        let mut path = PathBuf::with_capacity(128);
        let mut read_buf = String::with_capacity(20);

        // file-hierarchy(7) 手册页中定义的标准挂载位置
        let cgroup_mount = "/sys/fs/cgroup";

        path.push(cgroup_mount);
        path.push(&group_path);

        path.push("cgroup.controllers");

        // 如果我们没有看到 cgroup2,请跳过
        if matches!(try_exists(&path), Err(_) | Ok(false)) {
            return usize::MAX;
        };

        path.pop();

        let _: Option<()> = try {
            while path.starts_with(cgroup_mount) {
                path.push("cpu.max");

                read_buf.clear();

                if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
                    let raw_quota = read_buf.lines().next()?;
                    let mut raw_quota = raw_quota.split(' ');
                    let limit = raw_quota.next()?;
                    let period = raw_quota.next()?;
                    match (limit.parse::<usize>(), period.parse::<usize>()) {
                        (Ok(limit), Ok(period)) if period > 0 => {
                            quota = quota.min(limit / period);
                        }
                        _ => {}
                    }
                }

                path.pop(); // 弹出文件名
                path.pop(); // 弹出目录
            }
        };

        quota
    }

    fn quota_v1(group_path: PathBuf) -> usize {
        let mut quota = usize::MAX;
        let mut path = PathBuf::with_capacity(128);
        let mut read_buf = String::with_capacity(20);

        // 如果硬编码 cgroups(7) 手册页中提到的常用位置不起作用,请扫描 mountinfo 并为绑定挂载调整 `group_path`
        //
        let mounts: &[fn(&Path) -> Option<(_, &Path)>] = &[
            |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu"), p)),
            |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu,cpuacct"), p)),
            // 在具有大量挂载点的系统上,这可能是很昂贵的,但我们只有在 /proc/self/cgroups 明确指出该进程属于 cpu-controller cgroup v1 并且默认值不起作用时,才能达到这一点
            //
            //
            find_mountpoint,
        ];

        for mount in mounts {
            let Some((mount, group_path)) = mount(&group_path) else { continue };

            path.clear();
            path.push(mount.as_ref());
            path.push(&group_path);

            // 如果我们猜错了挂载,请跳过
            if matches!(try_exists(&path), Err(_) | Ok(false)) {
                continue;
            }

            while path.starts_with(mount.as_ref()) {
                let mut parse_file = |name| {
                    path.push(name);
                    read_buf.clear();

                    let f = File::open(&path);
                    path.pop(); // 在任何提前返回之前恢复缓冲区
                    f.ok()?.read_to_string(&mut read_buf).ok()?;
                    let parsed = read_buf.trim().parse::<usize>().ok()?;

                    Some(parsed)
                };

                let limit = parse_file("cpu.cfs_quota_us");
                let period = parse_file("cpu.cfs_period_us");

                match (limit, period) {
                    (Some(limit), Some(period)) if period > 0 => quota = quota.min(limit / period),
                    _ => {}
                }

                path.pop();
            }

            // 我们通过了上面的 try_exists,所以我们应该在到达这一行时遍历了正确的层次结构
            //
            break;
        }

        quota
    }

    /// 使用 cpu 控制器扫描 cgroup v1 挂载点的 mountinfo
    ///
    /// 如果 cgroupfs 是绑定挂载,则调整 `group_path` 以跳过已包含的前缀
    ///
    fn find_mountpoint(group_path: &Path) -> Option<(Cow<'static, str>, &Path)> {
        let mut reader = BufReader::new(File::open("/proc/self/mountinfo").ok()?);
        let mut line = String::with_capacity(256);
        loop {
            line.clear();
            if reader.read_line(&mut line).ok()? == 0 {
                break;
            }

            let line = line.trim();
            let mut items = line.split(' ');

            let sub_path = items.nth(3)?;
            let mount_point = items.next()?;
            let mount_opts = items.next_back()?;
            let filesystem_type = items.nth_back(1)?;

            if filesystem_type != "cgroup" || !mount_opts.split(',').any(|opt| opt == "cpu") {
                // 不是 cgroup / 不是 cpu 控制器
                continue;
            }

            let sub_path = Path::new(sub_path).strip_prefix("/").ok()?;

            if !group_path.starts_with(sub_path) {
                // 这是一个绑定挂载,绑定的子目录不包含该进程所属的 cgroup
                //
                continue;
            }

            let trimmed_group_path = group_path.strip_prefix(sub_path).ok()?;

            return Some((Cow::Owned(mount_point.to_owned()), trimmed_group_path));
        }

        None
    }
}

#[cfg(all(
    not(target_os = "linux"),
    not(target_os = "freebsd"),
    not(target_os = "macos"),
    not(target_os = "netbsd"),
    not(target_os = "openbsd"),
    not(target_os = "solaris")
))]
#[cfg_attr(test, allow(dead_code))]
pub mod guard {
    use crate::ops::Range;
    pub type Guard = Range<usize>;
    pub unsafe fn current() -> Option<Guard> {
        None
    }
    pub unsafe fn init() -> Option<Guard> {
        None
    }
}

#[cfg(any(
    target_os = "linux",
    target_os = "freebsd",
    target_os = "macos",
    target_os = "netbsd",
    target_os = "openbsd",
    target_os = "solaris"
))]
#[cfg_attr(test, allow(dead_code))]
pub mod guard {
    #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
    use libc::{mmap as mmap64, mprotect};
    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    use libc::{mmap64, mprotect};
    use libc::{MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE};

    use crate::io;
    use crate::ops::Range;
    use crate::sync::atomic::{AtomicUsize, Ordering};
    use crate::sys::os;

    // 这是在 init() 中初始化的,只能在之后读取
    static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);

    pub type Guard = Range<usize>;

    #[cfg(target_os = "solaris")]
    unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
        let mut current_stack: libc::stack_t = crate::mem::zeroed();
        assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
        Some(current_stack.ss_sp)
    }

    #[cfg(target_os = "macos")]
    unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
        let th = libc::pthread_self();
        let stackptr = libc::pthread_get_stackaddr_np(th);
        Some(stackptr.map_addr(|addr| addr - libc::pthread_get_stacksize_np(th)))
    }

    #[cfg(target_os = "openbsd")]
    unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
        let mut current_stack: libc::stack_t = crate::mem::zeroed();
        assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(), &mut current_stack), 0);

        let stack_ptr = current_stack.ss_sp;
        let stackaddr = if libc::pthread_main_np() == 1 {
            // 主线程
            stack_ptr.addr() - current_stack.ss_size + PAGE_SIZE.load(Ordering::Relaxed)
        } else {
            // 新线程
            stack_ptr.addr() - current_stack.ss_size
        };
        Some(stack_ptr.with_addr(stackaddr))
    }

    #[cfg(any(
        target_os = "android",
        target_os = "freebsd",
        target_os = "linux",
        target_os = "netbsd",
        target_os = "l4re"
    ))]
    unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
        let mut ret = None;
        let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
        #[cfg(target_os = "freebsd")]
        assert_eq!(libc::pthread_attr_init(&mut attr), 0);
        #[cfg(target_os = "freebsd")]
        let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
        #[cfg(not(target_os = "freebsd"))]
        let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
        if e == 0 {
            let mut stackaddr = crate::ptr::null_mut();
            let mut stacksize = 0;
            assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize), 0);
            ret = Some(stackaddr);
        }
        if e == 0 || cfg!(target_os = "freebsd") {
            assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
        }
        ret
    }

    // 前提条件: PAGE_SIZE 已初始化。
    unsafe fn get_stack_start_aligned() -> Option<*mut libc::c_void> {
        let page_size = PAGE_SIZE.load(Ordering::Relaxed);
        assert!(page_size != 0);
        let stackptr = get_stack_start()?;
        let stackaddr = stackptr.addr();

        // 确保 stackaddr 是页对齐的! 父进程可能已将 RLIMIT_STACK 重置为非页面对齐。
        // pthread_attr_getstack() 报告可用的栈区域 stackaddr <stackaddr + stacksize,因此,如果 stackaddr 不是页面对齐的,则计算修正值,使 stackaddr <new_page_aligned_stackaddr <stackaddr + stacksize
        //
        //
        //
        //
        let remainder = stackaddr % page_size;
        Some(if remainder == 0 {
            stackptr
        } else {
            stackptr.with_addr(stackaddr + page_size - remainder)
        })
    }

    pub unsafe fn init() -> Option<Guard> {
        let page_size = os::page_size();
        PAGE_SIZE.store(page_size, Ordering::Relaxed);

        if cfg!(all(target_os = "linux", not(target_env = "musl"))) {
            // Linux 不会立即分配整个栈,并且内核具有自己的栈保护机制,以便在与现有映射太接近时发生故障。
            // 如果我们使用自己的保护程序 map,则内核将开始在此之上强制执行一个较大的间隙,从而使很多可能的栈空间变得无用。
            // 请参见 #43052。
            //
            // 取而代之的是,我们只需要注意 rlimit 会在哪里开始出错,以便我们的处理程序可以报告 "栈溢出",并相信内核自己的栈保护会起作用。
            //
            //
            //
            //
            //
            let stackptr = get_stack_start_aligned()?;
            let stackaddr = stackptr.addr();
            Some(stackaddr - page_size..stackaddr)
        } else if cfg!(all(target_os = "linux", target_env = "musl")) {
            // 对于主线程,musl 的 pthread_attr_getstack 返回当前的栈大小,而不是其最终可以增长到的最大大小。
            // 它不能用于确定内核的栈保护的位置。
            //
            //
            None
        } else if cfg!(target_os = "freebsd") {
            // FreeBSD 的栈会自动增长,并且可以选择在底部包含一个保护页面。
            // 如果我们自己尝试重新映射栈底,FreeBSD 的保护页面就会向上移动。
            //
            // 所以我们将只使用内置的保护页面。
            let stackptr = get_stack_start_aligned()?;
            let guardaddr = stackptr.addr();
            // 从技术上讲,保护页面的数量是由 security.bsd.stack_guard_page sysctl 可调和控制的,但几乎没有理由将其从默认值更改。
            // 自 FreeBSD 11.1 和 10.4 以来,默认值一直为 1。
            //
            //
            const GUARD_PAGES: usize = 1;
            let guard = guardaddr..guardaddr + GUARD_PAGES * page_size;
            Some(guard)
        } else if cfg!(target_os = "openbsd") {
            // OpenBSD 栈已经包含一个保护页面,并且栈是不无效的。
            //
            // 我们只需要注意我们期望 rlimit 从哪里开始出错,因此我们的处理程序可以报告 "stack overflow",并相信内核自己的栈保护将起作用。
            //
            //
            //
            let stackptr = get_stack_start_aligned()?;
            let stackaddr = stackptr.addr();
            Some(stackaddr - page_size..stackaddr)
        } else {
            // 重新分配栈的最后一页。
            // 这样可以确保在栈溢出时引发 SIGBUS。
            // 强制执行严格 PAX MPROTECT 的系统不允许 mprotect() 具有比使用的初始 mmap() 少的限制性权限的映射,因此我们这里的 mmap() 具有 read/write 权限,然后只有 mprotect() 完全没有权限。
            // 请参见 issue #50313。
            //
            //
            //
            //
            let stackptr = get_stack_start_aligned()?;
            let result = mmap64(
                stackptr,
                page_size,
                PROT_READ | PROT_WRITE,
                MAP_PRIVATE | MAP_ANON | MAP_FIXED,
                -1,
                0,
            );
            if result != stackptr || result == MAP_FAILED {
                panic!("failed to allocate a guard page: {}", io::Error::last_os_error());
            }

            let result = mprotect(stackptr, page_size, PROT_NONE);
            if result != 0 {
                panic!("failed to protect the guard page: {}", io::Error::last_os_error());
            }

            let guardaddr = stackptr.addr();

            Some(guardaddr..guardaddr + page_size)
        }
    }

    #[cfg(any(target_os = "macos", target_os = "openbsd", target_os = "solaris"))]
    pub unsafe fn current() -> Option<Guard> {
        let stackptr = get_stack_start()?;
        let stackaddr = stackptr.addr();
        Some(stackaddr - PAGE_SIZE.load(Ordering::Relaxed)..stackaddr)
    }

    #[cfg(any(
        target_os = "android",
        target_os = "freebsd",
        target_os = "linux",
        target_os = "netbsd",
        target_os = "l4re"
    ))]
    pub unsafe fn current() -> Option<Guard> {
        let mut ret = None;
        let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
        #[cfg(target_os = "freebsd")]
        assert_eq!(libc::pthread_attr_init(&mut attr), 0);
        #[cfg(target_os = "freebsd")]
        let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
        #[cfg(not(target_os = "freebsd"))]
        let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
        if e == 0 {
            let mut guardsize = 0;
            assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
            if guardsize == 0 {
                if cfg!(all(target_os = "linux", target_env = "musl")) {
                    // 1.1.19 之前的 musl 版本始终将从 pthread_attr_get_np 获得的防护大小报告为零。
                    //
                    // 使用页面大小作为后备。
                    guardsize = PAGE_SIZE.load(Ordering::Relaxed);
                } else {
                    panic!("there is no guard page");
                }
            }
            let mut stackptr = crate::ptr::null_mut::<libc::c_void>();
            let mut size = 0;
            assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackptr, &mut size), 0);

            let stackaddr = stackptr.addr();
            ret = if cfg!(any(target_os = "freebsd", target_os = "netbsd")) {
                Some(stackaddr - guardsize..stackaddr)
            } else if cfg!(all(target_os = "linux", target_env = "musl")) {
                Some(stackaddr - guardsize..stackaddr)
            } else if cfg!(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")))
            {
                // 如 `man pthread_attr_getguardsize` 的 `BUGS` 部分所述,glibc 曾经将保护区包括在栈内。
                // 从 glibc 2.27 开始,并且在某些发行版本的反向移植中,此问题已得到纠正,因此现在将保护放置在栈的 (below) 的末尾。
                // 没有简单的方法让我们知道在运行时有哪些故障,因此我们只匹配栈基础上方或下方范围内的任何故障,以调用导致栈溢出的故障。
                //
                //
                //
                Some(stackaddr - guardsize..stackaddr + guardsize)
            } else {
                Some(stackaddr..stackaddr + guardsize)
            };
        }
        if e == 0 || cfg!(target_os = "freebsd") {
            assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
        }
        ret
    }
}

// glibc>= 2.15 具有一个 __pthread_get_minstack() 函数,该函数返回 PTHREAD_STACK_MIN 以及线程本地存储所需的字节。
// 我们需要这些信息,以避免在具有大量线程本地存储需求的应用程序中创建一个小的栈时发生崩溃。
//
// 有关原理和详细信息,请参见 #6233。
//
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
    // 我们使用 dlsym 来避免 ELF 版本对 GLIBC_PRIVATE 的依赖。
    // (#23628) 我们真的不应该使用这样的内部符号,但目前没有其他方法可以解释 TLS 大小。
    //
    dlsym!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);

    match __pthread_get_minstack.get() {
        None => libc::PTHREAD_STACK_MIN,
        Some(f) => unsafe { f(attr) },
    }
}

// 在非 glibc 平台上查找 __pthread_get_minstack() 毫无意义。
#[cfg(all(not(all(target_os = "linux", target_env = "gnu")), not(target_os = "netbsd")))]
fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
    libc::PTHREAD_STACK_MIN
}

#[cfg(target_os = "netbsd")]
fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
    2048 // 只是一个猜测
}