diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b564482..183065aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,15 @@ This file records each release. The format follows [Keep a Changelog](https://ke ### Fixed - nf_tables: the batch and the programs of the base chains share the elements of the sets. A batch copies a set only at its first change, and a commit makes the program data of a set again only when the set changed. Before, each batch begin copied each element of each table, and each commit copied each set that a base chain used into each program (#542). +- A thread of a cgroup over `memory.high` now takes back at the return to user mode only the pages that its cgroup charged over the limit since the last wait, as `reclaim_high` of Linux takes back `memcg_nr_pages_over_high`. Before, it took at least 64 pages also after a fault of one page. A write to swap keeps the CPU busy until the disk completes, so the workers of `stress-ng --vm` in TEST-55-OOMD of systemd kept both CPUs busy, and the workers that systemd-oomd killed took up to 38 seconds to exit. (#752) +- The reclaim of anonymous memory now looks at the address space in steps of 2 MiB and stops when it has enough pages, as `walk_page_range` of Linux. Before, each reclaim first collected each mapped page from its start to the end of the space. For the 10 workers of `stress-ng --vm 10 --vm-bytes 200M` in a cgroup over `memory.high`, this kept each CPU in the kernel, and PID1 did not answer `systemctl` for 25 seconds in TEST-55-OOMD of systemd. (#752) +- The reclaim of anonymous memory now goes on from the page after the last page that it took, as `swap_address` of Linux 2.4. Before, each reclaim looked at the address space again from address 0, so it looked at the same pages that cannot go each time. A cgroup over `memory.high` then used minutes of CPU in the reclaim, and because the kernel is not preemptive, PID1 did not get the CPU and `systemctl` timed out. (#752) +- The reclaim of a thread for `memory.high`, for `memory.max` and for a system that is short of memory now counts as a memory stall in the pressure (PSI) of its cgroup, as `psi_memstall_enter` of Linux around a reclaim. Before, only the wait after the reclaim counted, so the pressure stayed low while a cgroup did a lot of reclaim, and systemd-oomd did not kill it. TEST-55-OOMD of systemd needs this. (#752) +- A cgroup over `memory.high` now takes back pages and makes its threads wait once for each batch of 64 pages that it charged over the limit, as Linux charges in batches of `MEMCG_CHARGE_BATCH`. Before, a thread did a reclaim after each fault of one page, and the wait for a part of a batch was shorter than 10 ms, so no thread waited. The workers of `stress-ng --vm` in TEST-55-OOMD of systemd then kept the CPUs busy and the pressure "full" of the cgroup stayed near 0. (#752) +- The reclaim of anonymous memory now skips for up to 1 second an address space that had no page to give at the last look and has the same number of pages. Before, each reclaim of a cgroup looked at each page of each sleeping process of the cgroup again. In TEST-55-OOMD of systemd the reclaim looked at 9000 pages for each page that it took. (#752) +- The read of a page back from swap at a fault now counts as a memory stall in the pressure (PSI) of the cgroup of the thread, as `swap_read_folio` of Linux counts the read of a page of the working set. Before, a thread that waited for swap counted as a thread that ran, and the pressure "full" stayed low while all threads of a cgroup waited for swap. (#752) +- One read or write of the swap areas now runs at a time, and the other tasks that want to do swap I/O sleep until their turn, as a task of Linux sleeps in `submit_bio_wait`. Before, they spun on the lock of the disk driver. When the workers of `stress-ng --vm` in TEST-55-OOMD of systemd thrashed, both CPUs then spun for the disk, and `systemctl` and the killed workers did not get a CPU. (#752) +- A thread with a kill now does not take back pages for `memory.high` at its return to user mode, and a fault of a thread with a kill does not reclaim and does not call the OOM killer, as Linux delivers the fatal signal before `mem_cgroup_handle_over_high` and `out_of_memory` gives true for a task in `task_will_free_mem`. Before, the killed workers of `stress-ng` in TEST-55-OOMD of systemd wrote pages to swap before they ended. (#752) ## [0.5.39] - 2026-11-22 diff --git a/core/rk-cgroup/src/lib.rs b/core/rk-cgroup/src/lib.rs index c1d2020b..658428cd 100644 --- a/core/rk-cgroup/src/lib.rs +++ b/core/rk-cgroup/src/lib.rs @@ -1641,7 +1641,10 @@ impl Hierarchy { /// The time in nanoseconds that a thread of `id` must wait because its cgroup or a cgroup /// above it uses more than `memory.high`, as `mem_cgroup_handle_over_high` of Linux. The /// wait grows with the square of the part of the use over the limit and with the pages that - /// the cgroup charged while over it. Sets the count of these pages to 0. + /// the cgroup charged while over it. A cgroup gives a wait only when these pages are a full + /// batch of `HIGH_BATCH` pages, as Linux charges and handles the pages in batches of + /// `MEMCG_CHARGE_BATCH`. Then the count of the pages goes to 0. The count also goes to 0 + /// when the use is not over the limit. pub fn high_delay(&mut self, id: CgId) -> u64 { if !self.shared.any_over_high.load(Ordering::SeqCst) { return 0; @@ -1651,12 +1654,16 @@ impl Hierarchy { let on = self.on(a, MEMORY); let Some(n) = self.nodes.get(&a) else { continue }; let m = &n.c.mem; - let charged = m.over_high.swap(0, Ordering::SeqCst); let (current, high) = (m.current.load(Ordering::Relaxed), m.high.load(Ordering::Relaxed)); if !on || high == MAX || current <= high || high == 0 { + m.over_high.store(0, Ordering::SeqCst); + continue; + } + if m.over_high.load(Ordering::SeqCst) < HIGH_BATCH * PAGE_SIZE { continue; } + let charged = m.over_high.swap(0, Ordering::SeqCst); // The part over the limit in units of 2^-20, `calculate_overage` of Linux. let over = ((current - high) << 20) / high; overage = overage.max(over); @@ -1668,10 +1675,8 @@ impl Hierarchy { if self.nodes.values().any(|n| n.c.mem.over_high.load(Ordering::SeqCst) > 0) { self.shared.any_over_high.store(true, Ordering::SeqCst); } - // `calculate_high_delay` of Linux, in nanoseconds instead of jiffies. Linux handles the - // pages in batches of `HIGH_BATCH`, and the limit is for one batch. Here a thread can - // come back after each page, so the limit is for a batch and the wait is for the part of - // a batch. + // `calculate_high_delay` of Linux, in nanoseconds instead of jiffies. The limit is for + // one batch of `HIGH_BATCH` pages. let delay = (u128::from(overage) * u128::from(overage) * 1_000_000_000) >> 34; let delay = delay.min(u128::from(HIGH_DELAY_MAX)) * u128::from(pages); let delay = u64::try_from(delay / u128::from(HIGH_BATCH)).unwrap_or(HIGH_DELAY_MAX); @@ -2611,9 +2616,14 @@ pub fn count_reclaim(id: CgId, who: Reclaimer, anon: bool, scanned: u64, stolen: /// Takes back memory from `id` and each cgroup above it whose use is over `memory.high`, as /// `reclaim_high` of Linux. Each of these cgroups gives the bytes that the subtree charged over -/// the limit, and at least `RECLAIM_BATCH`. The return to user mode calls this before -/// [`high_delay`], so the wait is for the use that the reclaim leaves. -pub fn reclaim_high(id: CgId) { +/// the limit since the last wait, as Linux takes back the `memcg_nr_pages_over_high` pages of +/// the task. A cgroup gives nothing until these bytes are a batch of `HIGH_BATCH` pages, as Linux +/// charges in batches of `MEMCG_CHARGE_BATCH` pages. One reclaim of a batch costs much less than +/// a reclaim for each page. The return to user mode calls this +/// before [`high_delay`], so the wait is for the use that the reclaim leaves. The reclaim counts +/// as a memory stall of the cgroup `stall` of the thread in the pressure, as `psi_memstall_enter` +/// of Linux around the reclaim. +pub fn reclaim_high(id: CgId, stall: CgId) { if id == 0 || !shared().any_over_high.load(Ordering::Relaxed) { return; } @@ -2624,15 +2634,21 @@ pub fn reclaim_high(id: CgId) { let high = a.mem.high.load(Ordering::Relaxed); let current = a.mem.current.load(Ordering::Relaxed); let charged = a.mem.over_high.load(Ordering::Relaxed); - (a.on(MEMORY) && high != MAX && current > high) - .then(|| (a.id, charged.max(RECLAIM_BATCH))) + (a.on(MEMORY) && high != MAX && current > high && charged >= HIGH_BATCH * PAGE_SIZE) + .then_some((a.id, charged)) }) .collect(); (over, Changed::default()) }); - for (cg, bytes) in over.unwrap_or_default() { + let over = over.unwrap_or_default(); + if over.is_empty() { + return; + } + psi_change(stall, |c| c.memstall += 1); + for (cg, bytes) in over { reclaim_swap(cg, bytes); } + psi_change(stall, |c| c.memstall = c.memstall.saturating_sub(1)); } /// Charges a page of memory to `id`. A charge past a `memory.max` first takes back page cache @@ -2732,6 +2748,20 @@ pub fn high_delay(id: CgId) -> u64 { if id == 0 || !shared().any_over_high.load(Ordering::Relaxed) { return 0; } + // Most returns to user mode come before a full batch. They do not take the lock of the + // hierarchy. + let due = with_counters(id, |c, _| { + let due = c.path().any(|a| { + let charged = a.mem.over_high.load(Ordering::Relaxed); + let high = a.mem.high.load(Ordering::Relaxed); + charged >= HIGH_BATCH * PAGE_SIZE + || (charged > 0 && a.mem.current.load(Ordering::Relaxed) <= high) + }); + (due, Changed::default()) + }); + if due != Some(true) { + return 0; + } with(|h| h.high_delay(id)) } diff --git a/core/rk-cgroup/src/tests.rs b/core/rk-cgroup/src/tests.rs index bee1af5c..a38a196d 100644 --- a/core/rk-cgroup/src/tests.rs +++ b/core/rk-cgroup/src/tests.rs @@ -477,14 +477,54 @@ fn memory_high_makes_a_delay_that_grows_with_the_use() { // Twice the limit gives the longest wait. h.charge_memory(a, (1 << 20) - PAGE_SIZE).unwrap(); assert_eq!(h.high_delay(a), HIGH_DELAY_MAX); - // The wait is for the pages that the cgroup charged since the last wait. + // The wait is for the pages that the cgroup charged since the last wait, in batches of + // `HIGH_BATCH` pages. assert_eq!(h.high_delay(a), 0); h.charge_memory(a, PAGE_SIZE).unwrap(); - assert_eq!(h.high_delay(a), HIGH_DELAY_MAX / HIGH_BATCH); + assert_eq!(h.high_delay(a), 0); + h.charge_memory(a, (HIGH_BATCH - 1) * PAGE_SIZE).unwrap(); + assert_eq!(h.high_delay(a), HIGH_DELAY_MAX); + assert_eq!(h.high_delay(a), 0); let events = h.read(a, "memory.events", 0).unwrap(); assert!(events.starts_with("low 0\nhigh "), "{events}"); } +#[test] +fn memory_high_counts_the_pages_over_the_limit_only_while_the_use_is_over_it() { + let mut h = Hierarchy::new(0, 1); + h.write(ROOT, "cgroup.subtree_control", b"+memory", 0).unwrap(); + let a = h.mkdir(ROOT, b"a", 0).unwrap(); + h.write(a, "memory.high", b"1M", 0).unwrap(); + h.charge_memory(a, 1 << 20).unwrap(); + h.charge_memory(a, (HIGH_BATCH - 1) * PAGE_SIZE).unwrap(); + assert_eq!(h.high_delay(a), 0); + // The use goes under the limit, and the pages over it do not count after that. + h.uncharge_memory(a, HIGH_BATCH * PAGE_SIZE); + assert_eq!(h.high_delay(a), 0); + h.charge_memory(a, 2 * PAGE_SIZE).unwrap(); + h.write(a, "memory.high", b"512K", 0).unwrap(); + assert_eq!(h.high_delay(a), 0); + // A full batch at twice the limit gives the longest wait. + h.charge_memory(a, (HIGH_BATCH - 2) * PAGE_SIZE).unwrap(); + assert_eq!(h.high_delay(a), HIGH_DELAY_MAX); +} + +#[test] +fn memory_high_wait_of_a_batch_grows_with_the_square_of_the_use_over_the_limit() { + let mut h = Hierarchy::new(0, 1); + h.write(ROOT, "cgroup.subtree_control", b"+memory", 0).unwrap(); + let a = h.mkdir(ROOT, b"a", 0).unwrap(); + h.write(a, "memory.high", b"64M", 0).unwrap(); + h.charge_memory(a, 64 << 20).unwrap(); + // A batch at 1/256 over the limit gives 1/1024 s, less than the shortest wait. + h.charge_memory(a, HIGH_BATCH * PAGE_SIZE).unwrap(); + assert_eq!(h.high_delay(a), 0); + // At 1/64 over the limit a batch gives 1/64 s, as `calculate_high_delay` of Linux gives + // HZ / 64. The wait is for the 3 batches since the last wait. + h.charge_memory(a, 3 * HIGH_BATCH * PAGE_SIZE).unwrap(); + assert_eq!(h.high_delay(a), 3 * 1_000_000_000 / 64); +} + #[test] fn memory_oom_group_gives_the_highest_group() { let mut h = Hierarchy::new(0, 1); diff --git a/core/rk-mm/src/idle.rs b/core/rk-mm/src/idle.rs new file mode 100644 index 00000000..1a454d30 --- /dev/null +++ b/core/rk-mm/src/idle.rs @@ -0,0 +1,75 @@ +//! The mark of an address space that the reclaim of anonymous memory found with no page to take. +//! +//! The reclaim of a memory cgroup looks at each process of the cgroup in turn. A process that +//! only sleeps, or whose pages `fork` shares with its children, has no page that can go. Linux +//! takes pages from the LRU lists of the cgroup and does not look at such a process again and +//! again. Here the reclaim looks at the page tables, so it skips a space that had no page to give +//! at the last look and that has the same number of pages now. The mark is good for +//! [`IDLE_NS`] only, because a page can become a page of only one space without a fault of +//! this space, for example when a child exits. + +use core::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; + +/// The time in nanoseconds for which a mark stays good. +pub const IDLE_NS: u64 = 1_000_000_000; + +/// The mark. The pages are one more than the number of pages of the space at the look, and 0 +/// when the space has no mark. +#[derive(Default)] +pub struct Idle { + pages: AtomicUsize, + at: AtomicU64, +} + +impl Idle { + /// Marks the space, which has `pages` pages at the time `now` and no page to give. + pub fn mark(&self, pages: usize, now: u64) { + self.at.store(now, Ordering::Relaxed); + self.pages.store(pages.saturating_add(1), Ordering::Relaxed); + } + + /// Removes the mark. + pub fn clear(&self) { + self.pages.store(0, Ordering::Relaxed); + } + + /// Tells if the reclaim can skip the space, which has `pages` pages at the time `now`. + pub fn skip(&self, pages: usize, now: u64) -> bool { + self.pages.load(Ordering::Relaxed) == pages.saturating_add(1) + && now.saturating_sub(self.at.load(Ordering::Relaxed)) < IDLE_NS + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_space_with_no_mark_is_not_skipped() { + let idle = Idle::default(); + assert!(!idle.skip(0, 0)); + assert!(!idle.skip(5, 100)); + } + + #[test] + fn a_marked_space_is_skipped_while_its_pages_stay_the_same() { + let idle = Idle::default(); + idle.mark(10, 1000); + assert!(idle.skip(10, 1000)); + assert!(idle.skip(10, 1000 + IDLE_NS - 1)); + // A fault or an unmap changes the pages, and the reclaim looks again. + assert!(!idle.skip(11, 1000)); + assert!(!idle.skip(9, 1000)); + } + + #[test] + fn a_mark_ends_after_its_time_or_a_clear() { + let idle = Idle::default(); + idle.mark(0, 1000); + assert!(idle.skip(0, 1000)); + assert!(!idle.skip(0, 1000 + IDLE_NS)); + idle.mark(3, 5); + idle.clear(); + assert!(!idle.skip(3, 5)); + } +} diff --git a/core/rk-mm/src/lib.rs b/core/rk-mm/src/lib.rs index a1de9d75..3315a368 100644 --- a/core/rk-mm/src/lib.rs +++ b/core/rk-mm/src/lib.rs @@ -14,6 +14,7 @@ extern crate alloc; pub mod hugetlb; +pub mod idle; pub mod ksm; pub mod pttree; pub mod rangelog; @@ -27,7 +28,7 @@ mod space; #[cfg(all(target_os = "none", any(target_arch = "x86_64", target_arch = "aarch64")))] pub use space::{ Access, AddressSpace, FileRef, MMAP_MIN_ADDR, MMAP_TOP, MmFile, MmapRequest, Remap, STACK_SIZE, - STACK_TOP, WriteMap, set_populate_hook, + STACK_TOP, WriteMap, set_memstall_hook, set_populate_hook, }; pub use vma::{Backing, HugeAdvice, PAGE_SIZE, Prot, STACK_GUARD_GAP, Vma, VmaKind, VmaSet}; diff --git a/core/rk-mm/src/space.rs b/core/rk-mm/src/space.rs index c5577984..220389fa 100644 --- a/core/rk-mm/src/space.rs +++ b/core/rk-mm/src/space.rs @@ -391,7 +391,16 @@ impl Read { Self::Swap(slot) => { above_reserve()?; let frame = charged(rk_frame::mm::alloc_frame(), memcg)?; - slot.read(&frame).map_err(|()| Errno::EIO)?; + // A page that comes back from swap was in use before the reclaim took it, so the + // wait for it counts as a memory stall, as `swap_read_folio` of Linux counts the + // read of a page of the working set. + let mut read = Ok(()); + let mut run = || read = slot.read(&frame); + match MEMSTALL_HOOK.get() { + Some(stall) => stall(&mut run), + None => run(), + } + read.map_err(|()| Errno::EIO)?; frame.set_anon(); Ok(Prepared::Swap { slot, frame }) } @@ -481,6 +490,12 @@ pub struct AddressSpace { /// The top of the `mmap` area, as `mmap_base` of Linux. It is [`MMAP_TOP`] less a random /// offset that `execve` sets. mmap_top: AtomicUsize, + /// The address where the next reclaim of anonymous memory looks first, as `swap_address` of + /// the mm of Linux 2.4. Each reclaim goes on from the page after the last page that it took, + /// so the pages at the start that cannot go are not looked at each time. + reclaim_at: AtomicUsize, + /// The mark of a space in which the last reclaim found no page to take. + idle: crate::idle::Idle, } fn map_error(e: MapError) -> Errno { @@ -611,6 +626,8 @@ impl AddressSpace { huge_resv: SpinLock::new(BTreeMap::new()), hiwater: AtomicUsize::new(0), mmap_top: AtomicUsize::new(MMAP_TOP), + reclaim_at: AtomicUsize::new(0), + idle: crate::idle::Idle::default(), } } @@ -1904,12 +1921,32 @@ impl AddressSpace { /// Writes up to `want` private anonymous pages of the space to a swap area and frees their /// frames, for the reclaim of a memory cgroup or of the system, as `shrink_folio_list` of /// Linux. The pages are the pages of [`AddressSpace::page_out`]. Gives the pages that the - /// reclaim looked at and the pages that went, for `pgscan_anon` and `pgsteal_anon`. + /// reclaim looked at and the pages that went, for `pgscan_anon` and `pgsteal_anon`. The + /// reclaim starts after the page where the last one stopped, and goes round to the start of + /// the space, as an LRU list of Linux puts a page that it looked at to the end. A space in + /// which the whole look found no page is skipped for a time while its pages stay the same, + /// so a cgroup with many sleeping processes does not look at their pages for each reclaim. pub fn reclaim_anon(&self, want: usize) -> (usize, usize) { if want == 0 { return (0, 0); } - self.page_out_range(0, usize::MAX, want) + let now = rk_frame::time::nanos(); + if self.idle.skip(self.vm.page_count(), now) { + return (0, 0); + } + let at = self.reclaim_at.load(Ordering::Relaxed); + let (mut scanned, mut n, mut next) = self.page_out_range(at, usize::MAX, want); + if next.is_none() && at > 0 { + let (s, m, after) = self.page_out_range(0, at, want - n); + (scanned, n, next) = (scanned + s, n + m, after); + } + self.reclaim_at.store(next.unwrap_or(0), Ordering::Relaxed); + if n == 0 && next.is_none() { + self.idle.mark(self.vm.page_count(), now); + } else { + self.idle.clear(); + } + (scanned, n) } /// Reads back each page of the space that has a swap entry for which `of` gives `true`, and @@ -1938,31 +1975,51 @@ impl AddressSpace { } /// Writes up to `want` pages of `start..end` to swap. See [`AddressSpace::page_out`]. Gives - /// the pages that it looked at and the pages that went. - fn page_out_range(&self, start: usize, end: usize, want: usize) -> (usize, usize) { - let st = self.state.lock(); - let mut pages = Vec::new(); - for vma in st.vmas.iter().filter(|v| v.start < end && start < v.end) { - if !vma.shared && !vma.hugetlb && !vma.locked { - let (from, to) = (start.max(vma.start), end.min(vma.end)); - pages.extend(self.vm.mapped_pages(VirtAddr::new(from), VirtAddr::new(to))); - } + /// the pages that it looked at, the pages that went, and the page where it stopped before + /// the end of the range. + fn page_out_range( + &self, + start: usize, + end: usize, + want: usize, + ) -> (usize, usize, Option) { + if want == 0 { + return (0, 0, Some(start)); } - // The writes wait for the disk, so they run with no lock of the areas, as the write back - // of `munmap`. - drop(st); - let (mut scanned, mut n) = (0, 0); - for page in pages { - if n >= want { + let (mut scanned, mut n, mut at) = (0, 0, start); + while at < end { + // The pages go in batches of `RECLAIM_BATCH` bytes, so a reclaim that wants a few + // pages does not first collect each mapped page of a large space, as `walk_page_range` + // of Linux stops when the reclaim has enough. + let st = self.state.lock(); + let Some(vma) = st + .vmas + .iter() + .find(|v| at < v.end && v.start < end && !v.shared && !v.hugetlb && !v.locked) + else { break; + }; + let from = at.max(vma.start); + let to = end.min(vma.end).min(from.saturating_add(RECLAIM_BATCH)); + let pages = self.vm.mapped_pages(VirtAddr::new(from), VirtAddr::new(to)); + // The writes wait for the disk, so they run with no lock of the areas, as the write + // back of `munmap`. + drop(st); + at = to; + for page in pages { + scanned += 1; + // A page that cannot go takes no swap entry. + let Some(frame) = self.vm.swap_out_start(page) else { continue }; + let Some(slot) = SwapSlot::alloc(self.memcg()) else { + return (scanned, n, Some(page.get())); + }; + n += usize::from(self.swap_out(page, &frame, slot)); + if n >= want { + return (scanned, n, Some(page.get() + PAGE_SIZE)); + } } - scanned += 1; - // A page that cannot go takes no swap entry. - let Some(frame) = self.vm.swap_out_start(page) else { continue }; - let Some(slot) = SwapSlot::alloc(self.memcg()) else { break }; - n += usize::from(self.swap_out(page, &frame, slot)); } - (scanned, n) + (scanned, n, None) } /// Writes the page `frame` at `page`, which `swap_out_start` gave, to the swap entry `slot`, @@ -2455,6 +2512,10 @@ fn only_enomem(r: Result<(), Errno>) -> Result<(), Errno> { } } +/// The bytes of the address space that the reclaim of anonymous memory looks at in one step, the +/// size of one page table. See [`AddressSpace::page_out_range`]. +const RECLAIM_BATCH: usize = 2 << 20; + /// The pages of a populate between two calls of the hook of [`set_populate_hook`], as /// `MEMCG_CHARGE_BATCH` of Linux. const POPULATE_BATCH: usize = 64; @@ -2471,6 +2532,16 @@ pub fn set_populate_hook(hook: fn() -> bool) { POPULATE_HOOK.call_once(|| hook); } +/// The hook of [`set_memstall_hook`]. +static MEMSTALL_HOOK: Once = Once::new(); + +/// Sets the function that runs the read of a page back from swap for a fault. The function +/// counts the read as a memory stall of the thread in the pressure, as `psi_memstall_enter` and +/// `psi_memstall_leave` of Linux around the read. +pub fn set_memstall_hook(hook: fn(&mut dyn FnMut())) { + MEMSTALL_HOOK.call_once(|| hook); +} + /// Tells if `vma` allows `access`. fn allowed(vma: &Vma, access: Access) -> bool { match access { diff --git a/core/rk-proc/src/cgroup.rs b/core/rk-proc/src/cgroup.rs index cb5fd6c0..b08cd02e 100644 --- a/core/rk-proc/src/cgroup.rs +++ b/core/rk-proc/src/cgroup.rs @@ -251,10 +251,16 @@ pub fn wait_throttled(thread: &Thread) -> bool { /// Takes memory back from the cgroups over `memory.high`, and then keeps `thread` waiting when /// its cgroup charged pages over `memory.high`, as `mem_cgroup_handle_over_high` of Linux. The -/// wait counts as a memory stall in the pressure. A kill or a change of the limit ends the wait. +/// reclaim and the wait count as a memory stall in the pressure. A kill or a change of the limit ends the wait. fn wait_over_high(thread: &Thread, cg: CgId) { + // A thread with a kill goes to its exit, and its memory goes back with its address space. + // Linux delivers the fatal signal before `resume_user_mode_work`, so such a task does not + // reclaim or wait in `mem_cgroup_handle_over_high`. + if thread.is_killed() { + return; + } let memcg = thread.process().memcg(); - rk_cgroup::reclaim_high(memcg); + rk_cgroup::reclaim_high(memcg, cg); let delay = rk_cgroup::high_delay(memcg); if delay == 0 { return; @@ -277,6 +283,16 @@ pub fn populate_wait() -> bool { !thread.is_killed() } +/// Runs `f` as a memory stall of the current thread in the pressure of its cgroup, as +/// `psi_memstall_enter` and `psi_memstall_leave` of Linux. A fault reads a page back from swap +/// with this. Kernel work outside a thread counts nothing. +pub fn memstall(f: &mut dyn FnMut()) { + match crate::current_thread() { + Some(thread) => stalled(&thread, f), + None => f(), + } +} + /// Charges an I/O of the current thread to its cgroup, for `io.stat`. Kernel work goes to the /// root. The delay of `io.max` waits until the thread goes back to user mode, so the thread does /// not wait with the locks of a file system. The block layer calls this after each batch, with @@ -391,19 +407,25 @@ fn reap(victim: &Arc) { /// It does not kill init or a process with `oom_score_adj` -1000. The thread then waits for /// the end of the victim, so that the fault can try again. Gives `false` if no process can go. pub fn system_oom(thread: &Thread) -> bool { + // A thread with a kill frees its memory at its exit, so it does not reclaim or kill, as + // `out_of_memory` of Linux gives true at once for a task in `task_will_free_mem`. + if thread.is_killed() { + return true; + } // A fault that a memory cgroup refused, with free memory in the system, is not for this // killer. if rk_frame::mm::frame_stats().free > system_reserve() { return false; } - // The clean page cache goes first, as the reclaim of Linux before `out_of_memory`. - rk_vfs::blockdev::reclaim_all(); - if rk_frame::mm::frame_stats().free > system_reserve() { - return true; - } - // Then anonymous memory goes to swap, and the fault tries again while the reclaim frees - // pages. - if reclaim_anon(rk_cgroup::ROOT, RECLAIM_BATCH) > 0 { + // The clean page cache goes first, as the reclaim of Linux before `out_of_memory`. Then + // anonymous memory goes to swap, and the fault tries again while the reclaim frees pages. The + // reclaim counts as a memory stall, as `__perform_reclaim` of Linux. + let freed = stalled(thread, || { + rk_vfs::blockdev::reclaim_all(); + rk_frame::mm::frame_stats().free > system_reserve() + || reclaim_anon(rk_cgroup::ROOT, RECLAIM_BATCH) > 0 + }); + if freed { return true; } // A victim that is still on its way out frees its memory soon: wait for it, as Linux does @@ -458,6 +480,12 @@ pub fn memcg_oom(thread: &Thread) -> bool { if memcg == 0 { return false; } + // A thread with a kill ends at its return to user mode, and its memory goes back then. It + // does not reclaim or kill, as `mem_cgroup_out_of_memory` of Linux skips the kill for a task + // in `task_will_free_mem`. + if thread.is_killed() { + return true; + } // A test charge finds the cgroup whose limit blocks the page. let blocking = match rk_cgroup::charge_page(memcg) { Ok(()) => { @@ -470,7 +498,7 @@ pub fn memcg_oom(thread: &Thread) -> bool { }; // Anonymous memory goes to swap before a kill, as `try_charge_memcg` of Linux does a // reclaim before `mem_cgroup_oom`. The fault holds no lock of the space now. - if reclaim_anon(blocking, RECLAIM_BATCH) > 0 { + if stalled(thread, || reclaim_anon(blocking, RECLAIM_BATCH) > 0) { return true; } let cg = thread.cgroup(); @@ -492,6 +520,16 @@ pub fn memcg_oom(thread: &Thread) -> bool { victim.is_some() } +/// Runs the reclaim `f` of a fault of `thread`. The reclaim counts as a memory stall of the cgroup +/// of the thread, as `psi_memstall_enter` of Linux around a direct reclaim. +fn stalled(thread: &Thread, f: impl FnOnce() -> R) -> R { + let cg = thread.cgroup(); + rk_cgroup::psi_change(cg, |c| c.memstall += 1); + let r = f(); + rk_cgroup::psi_change(cg, |c| c.memstall = c.memstall.saturating_sub(1)); + r +} + /// The bytes of the anonymous reclaim for a fault that a memory cgroup or the system refused, as /// `SWAP_CLUSTER_MAX` pages of Linux. const RECLAIM_BATCH: u64 = 32 * crate::PAGE_SIZE as u64; diff --git a/core/rk-syscall/src/run.rs b/core/rk-syscall/src/run.rs index e4903261..463d0c6d 100644 --- a/core/rk-syscall/src/run.rs +++ b/core/rk-syscall/src/run.rs @@ -380,6 +380,8 @@ pub fn init() { rk_cgroup::set_reclaim(rk_vfs::blockdev::reclaim_memcg); // A long populate waits for `memory.high` after each batch of pages. rk_mm::set_populate_hook(rk_proc::cgroup::populate_wait); + // The read of a page back from swap counts as a memory stall in the pressure. + rk_mm::set_memstall_hook(rk_proc::cgroup::memstall); rk_vfs::blockdev::set_memcg_ops(rk_vfs::blockdev::MemcgOps { current: || rk_proc::current_thread().map_or(0, |t| t.process().memcg()), charge: rk_cgroup::charge_file, diff --git a/fs/rk-vfs/src/swap.rs b/fs/rk-vfs/src/swap.rs index 8a6cb519..3d615488 100644 --- a/fs/rk-vfs/src/swap.rs +++ b/fs/rk-vfs/src/swap.rs @@ -17,7 +17,7 @@ use crate::inode::{FiemapExtent, Inode, InodeRef, Result}; use crate::wait::WaitQueue; use alloc::sync::Arc; use alloc::vec::Vec; -use core::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use rk_abi::Errno; use rk_block::Queue; use rk_block::cache::PAGE_SIZE; @@ -581,7 +581,7 @@ fn locate(e: u64) -> Result<(Arc, u64)> { /// Gives `EINVAL` for an entry of no active area, and the error of the disk. pub fn write_page(e: u64, data: &[u8]) -> Result<()> { let (queue, sector) = locate(e)?; - queue.write(sector, &data[..PAGE_SIZE]) + IO.run(|| queue.write(sector, &data[..PAGE_SIZE])) } /// Reads the page of the swap entry `e` into `buf`, with direct I/O from the disk. @@ -591,9 +591,43 @@ pub fn write_page(e: u64, data: &[u8]) -> Result<()> { /// Gives `EINVAL` for an entry of no active area, and the error of the disk. pub fn read_page(e: u64, buf: &mut [u8]) -> Result<()> { let (queue, sector) = locate(e)?; - queue.read(sector, &mut buf[..PAGE_SIZE]) + IO.run(|| queue.read(sector, &mut buf[..PAGE_SIZE])) } +/// The turn of the reads and writes of the swap areas. The driver of the disk does one request +/// at a time, and its lock spins, so a task that waits for the lock holds its CPU. When many +/// tasks thrash, each CPU then spins for the disk, and no other task runs. With the turn, one +/// task waits for the disk and the others sleep, as a task of Linux sleeps in `submit_bio_wait` +/// and in `folio_wait_locked` while the disk does the I/O of another task. The CPU then runs the +/// other tasks of the system. +struct IoTurn { + busy: AtomicBool, + queue: WaitQueue, +} + +impl IoTurn { + const fn new() -> Self { + Self { busy: AtomicBool::new(false), queue: WaitQueue::new() } + } + + /// Runs `f` when no other task has the turn, and gives the turn to the next task after it. + fn run(&self, f: impl FnOnce() -> R) -> R { + self.queue.wait_until(|| { + self.busy + .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) + .is_ok() + .then_some(()) + }); + let r = f(); + self.busy.store(false, Ordering::Release); + self.queue.wake_one(); + r + } +} + +/// The turn of all the swap I/O. +static IO: IoTurn = IoTurn::new(); + #[cfg(test)] mod tests { use super::*; @@ -630,6 +664,34 @@ mod tests { assert_eq!(s.alloc(), None); } + /// Several threads do swap I/O at the same time. One at a time has the turn, and each gets it. + #[test] + fn one_swap_io_at_a_time_has_the_turn() { + extern crate std; + let turn = IoTurn::new(); + let (inside, most, done) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); + std::thread::scope(|s| { + for _ in 0..4 { + s.spawn(|| { + for _ in 0..200 { + let n = turn.run(|| { + let n = inside.fetch_add(1, Ordering::SeqCst) + 1; + most.fetch_max(n, Ordering::SeqCst); + core::hint::spin_loop(); + inside.fetch_sub(1, Ordering::SeqCst); + n + }); + assert_eq!(n, 1); + done.fetch_add(1, Ordering::SeqCst); + } + }); + } + }); + assert_eq!(most.load(Ordering::SeqCst), 1); + assert_eq!(done.load(Ordering::SeqCst), 800); + assert!(!turn.busy.load(Ordering::SeqCst)); + } + #[test] fn an_entry_has_the_type_and_the_page() { assert_eq!(split(entry(3, 12345)), (3, 12345)); diff --git a/fs/rk-vfs/src/wait.rs b/fs/rk-vfs/src/wait.rs index b74ed063..76edc2e1 100644 --- a/fs/rk-vfs/src/wait.rs +++ b/fs/rk-vfs/src/wait.rs @@ -87,6 +87,12 @@ impl WaitQueue { #[cfg(all(target_os = "none", any(target_arch = "x86_64", target_arch = "aarch64")))] self.inner.wake_all(); } + + /// Wakes the first task that waits. + pub fn wake_one(&self) { + #[cfg(all(target_os = "none", any(target_arch = "x86_64", target_arch = "aarch64")))] + self.inner.wake_one(); + } } impl Default for WaitQueue {