| @@ -5,7 +5,10 @@ |
| 5 | 5 | //! The API mirrors the subset of corosensei the runtime used. |
| 6 | 6 | //! |
| 7 | 7 | //! - **Stacks** are the runtime's own: an anonymous mapping with a guard |
| 8 | | −//! page at its low end, committed lazily by the kernel. |
| 8 | +//! page at its low end, committed lazily by the kernel. Their tops are |
| 9 | +//! aligned on [`REGION`], so that a stack's memory, page tables |
| 10 | +//! included, can be given back while its fiber is suspended |
| 11 | +//! ([`Coroutine::hibernate`], ADR 0028). |
| 9 | 12 | //! - **The switch** is the runtime's own on x86_64 Linux: it saves the |
| 10 | 13 | //! callee-saved registers (and the floating-point control words) on the |
| 11 | 14 | //! current stack, stores the stack pointer, and loads the other one. A |
| @@ -21,10 +24,14 @@ |
| 21 | 24 | //! - code on a fiber must not hold thread-local state across a suspension, |
| 22 | 25 | //! since it may resume on another thread (see `sched::Fiber`). |
| 23 | 26 | |
| 24 | | −/// A fiber stack: `size` usable bytes above one guard page. |
| 27 | +/// A fiber stack: at least `size` usable bytes above one guard page. |
| 25 | 28 | pub(crate) struct Stack { |
| 29 | + /// The mapping, guard page first. |
| 26 | 30 | base: *mut u8, |
| 27 | 31 | len: usize, |
| 32 | + /// Where the stack starts (it grows down): aligned on [`REGION`]. The |
| 33 | + /// mapping's last bytes, above it, are never used. |
| 34 | + top: usize, |
| 28 | 35 | } |
| 29 | 36 | |
| 30 | 37 | // SAFETY: a stack is plain memory, owned by one fiber at a time. |
| @@ -32,9 +39,21 @@ unsafe impl Send for Stack {} |
| 32 | 39 | |
| 33 | 40 | const PAGE: usize = 4096; |
| 34 | 41 | |
| 42 | +/// What one page table maps with 4 KiB pages (x86_64, and aarch64's |
| 43 | +/// default). A stack's top is aligned on it, so the regions at its top |
| 44 | +/// belong to it alone: when [`Stack::release`] gives them back, the |
| 45 | +/// kernel frees their page tables too (Linux's `CONFIG_PT_RECLAIM` |
| 46 | +/// reclaims a page table only when the whole range it maps is released). |
| 47 | +/// Without that, an idle actor kept a 4 KiB page table for its one |
| 48 | +/// touched stack page (ADR 0028). With larger pages the alignment is only |
| 49 | +/// less useful. |
| 50 | +pub(crate) const REGION: usize = 2 << 20; |
| 51 | + |
| 35 | 52 | impl Stack { |
| 36 | 53 | pub(crate) fn new(size: usize) -> std::io::Result<Stack> { |
| 37 | | − let len = size.div_ceil(PAGE) * PAGE + PAGE; |
| 54 | + // The guard page, the stack, and room to align its top: virtual |
| 55 | + // memory only, never touched. |
| 56 | + let len = PAGE + size.div_ceil(PAGE) * PAGE + REGION; |
| 38 | 57 | // SAFETY: a fresh private anonymous mapping; nothing aliases it. |
| 39 | 58 | unsafe { |
| 40 | 59 | let base = libc::mmap( |
| @@ -54,16 +73,38 @@ impl Stack { |
| 54 | 73 | libc::munmap(base, len); |
| 55 | 74 | return Err(e); |
| 56 | 75 | } |
| 76 | + // At least `PAGE + size` above `base`, since the mapping is |
| 77 | + // `REGION` longer than that. |
| 78 | + let top = (base as usize + len) & !(REGION - 1); |
| 57 | 79 | Ok(Stack { |
| 58 | 80 | base: base.cast(), |
| 59 | 81 | len, |
| 82 | + top, |
| 60 | 83 | }) |
| 61 | 84 | } |
| 62 | 85 | } |
| 63 | 86 | |
| 64 | 87 | /// The highest address (exclusive): stacks grow down from here. |
| 65 | | − fn top(&self) -> usize { |
| 66 | | − self.base as usize + self.len |
| 88 | + pub(crate) fn top(&self) -> usize { |
| 89 | + self.top |
| 90 | + } |
| 91 | + |
| 92 | + /// Give the stack's memory back to the kernel: its pages read as zeros |
| 93 | + /// afterwards, and the page tables of the whole regions at its top are |
| 94 | + /// freed. Nothing on it may be live: a finished fiber's stack, or a |
| 95 | + /// suspended one already saved ([`Coroutine::hibernate`]). |
| 96 | + pub(crate) fn release(&self) { |
| 97 | + let low = self.base as usize + PAGE; |
| 98 | + // SAFETY: `low..top` is inside the mapping, above the guard page; |
| 99 | + // the caller guarantees nothing on it is live. |
| 100 | + let r = unsafe { |
| 101 | + libc::madvise( |
| 102 | + low as *mut libc::c_void, |
| 103 | + self.top - low, |
| 104 | + libc::MADV_DONTNEED, |
| 105 | + ) |
| 106 | + }; |
| 107 | + debug_assert_eq!(r, 0, "louise: madvise: {}", std::io::Error::last_os_error()); |
| 67 | 108 | } |
| 68 | 109 | |
| 69 | 110 | /// The lowest usable address (just above the guard page). |
| @@ -410,6 +451,17 @@ mod imp { |
| 410 | 451 | }) |
| 411 | 452 | } |
| 412 | 453 | |
| 454 | + /// Save this suspended fiber's stack, then give its memory back |
| 455 | + /// ([`Stack::release`]): [`Coroutine::restore`] with the snapshot |
| 456 | + /// before resuming it. An idle actor's stack holds 688 bytes |
| 457 | + /// (`tests/bench/idle.lse`), against a 4 KiB page and a 4 KiB page |
| 458 | + /// table resident. |
| 459 | + pub(crate) fn hibernate(&mut self) -> Option<Snapshot> { |
| 460 | + let snap = self.snapshot()?; |
| 461 | + self.stack.as_ref().expect("stack").release(); |
| 462 | + Some(snap) |
| 463 | + } |
| 464 | + |
| 413 | 465 | /// Make this fiber the suspended one `snap` was taken of. What its |
| 414 | 466 | /// stack held is overwritten: the fiber must be finished, or its |
| 415 | 467 | /// suspension saved or released. |
| @@ -717,6 +769,11 @@ mod imp { |
| 717 | 769 | pub(crate) fn restore(&mut self, _: &Snapshot) { |
| 718 | 770 | unreachable!("louise: no snapshots on this target") |
| 719 | 771 | } |
| 772 | + |
| 773 | + /// Not available on this target either (no snapshots). |
| 774 | + pub(crate) fn hibernate(&mut self) -> Option<Snapshot> { |
| 775 | + None |
| 776 | + } |
| 720 | 777 | } |
| 721 | 778 | } |
| 722 | 779 | |
| @@ -810,6 +867,42 @@ mod tests { |
| 810 | 867 | } |
| 811 | 868 | |
| 812 | 869 | #[test] |
| 870 | + fn stack_tops_are_aligned_and_leave_the_size_asked_for() { |
| 871 | + for size in [64 << 10, 256 << 10, 64 << 20] { |
| 872 | + let s = Stack::new(size).unwrap(); |
| 873 | + assert_eq!(s.top() % REGION, 0); |
| 874 | + assert!(s.top() - (s.base as usize + PAGE) >= size); |
| 875 | + assert!(s.top() <= s.base as usize + s.len); |
| 876 | + } |
| 877 | + } |
| 878 | + |
| 879 | + #[cfg(all(target_arch = "x86_64", target_os = "linux"))] |
| 880 | + #[test] |
| 881 | + fn a_hibernated_fiber_resumes_where_it_was() { |
| 882 | + let mut co = Coroutine::with_stack( |
| 883 | + Stack::new(64 << 20).unwrap(), |
| 884 | + |y: &Yielder<u64, u64>, base| { |
| 885 | + let local = [base, base + 1, base + 2, base + 3]; // on the stack |
| 886 | + let x = y.suspend(local[1]); |
| 887 | + let x = x + y.suspend(std::hint::black_box(&local)[2]); |
| 888 | + std::hint::black_box(local).iter().sum::<u64>() + x |
| 889 | + }, |
| 890 | + ); |
| 891 | + assert!(matches!(co.resume(10), CoroutineResult::Yield(11))); |
| 892 | + let snap = co.hibernate().expect("x86_64"); |
| 893 | + // The stack reads as zeros now: only the snapshot holds the frames |
| 894 | + // (its lowest word, the saved MXCSR, is never 0). |
| 895 | + assert_ne!(snap.words[0], 0); |
| 896 | + // SAFETY: `sp` is inside the mapping, above its guard page. |
| 897 | + assert_eq!(unsafe { (snap.sp as *const usize).read_volatile() }, 0); |
| 898 | + co.restore(&snap); |
| 899 | + assert!(matches!(co.resume(1), CoroutineResult::Yield(12))); |
| 900 | + let snap = co.hibernate().expect("x86_64"); |
| 901 | + co.restore(&snap); |
| 902 | + assert!(matches!(co.resume(2), CoroutineResult::Return(49))); |
| 903 | + } |
| 904 | + |
| 905 | + #[test] |
| 813 | 906 | fn deep_recursion_runs_on_the_fiber_stack() { |
| 814 | 907 | fn depth(n: u32) -> u32 { |
| 815 | 908 | let pad = [n; 32]; |