Skip to main content

atmos/kernel/
mem_quota.rs

1//! # アプリごとのメモリの帳簿と上限の判定(TODO R5、2026-11-17)
2//!
3//! 目的: 1 つのアプリ(ブラウザのウィンドウ等)がヒープを使いすぎたら、**そのアプリだけ**を止め、
4//! OS とほかのアプリは動き続けるようにする(A7: 2〜3 本目の動画でヒープが尽きる、の受け皿)。
5//!
6//! ## 何を数えるか(軽い近似)
7//! - アプリのスレッド(`app_runner`)は起動時に「組」(1〜[`GROUPS`]-1 の番号)を 1 つ受け取る。
8//!   そのスレッドが起こしたスレッド(XHR・フォント・画像・動画・ローダー)は、起こした側の組を受け継ぐ
9//!   (`scheduler` が `Process::mem_group` に持ち、切り替えのたびに [`Ledger::set_core_group`] でコアへ写す)。
10//!   組 0 は OS(`gui_shell`・`usb_poll`・`net_service` など)で、数えない。
11//! - 確保のたびに、**そのとき動いているスレッドの組**へ大きさを足し、解放のたびに引く([`Ledger::on_alloc`]・
12//!   [`Ledger::on_dealloc`])。アロケータの錠の中で呼ぶので、アトミックの読み出しと書き込みだけ(RMW も錠も無し)。
13//! - **狂い**: 確保と解放が別の組のスレッドで起きると狂う(例: OS 側の `net_service` が受け取った受信の
14//!   バッファをアプリが解放すると、アプリの組は実際より少なく出る)。同じアプリの中(アプリのスレッドと
15//!   その背景のスレッド)で受け渡す分は同じ組なので狂わない。読むときは 0 未満を 0 とみなす。
16//!   少なく出る向きの狂いは「止めるのが遅れる」だけで、誤って止めることはない。
17//!
18//! ## いつ止めるか([`Ledger::verdict`])
19//! 1. **全体が尽きかけた**(ヒープの空きが [`LOW_FREE`] 未満。数えるのはアロケータの実際の空きなので狂わない)とき、
20//!    生きている組のうち一番多く持っている組([`MIN_VICTIM`] 以上)を止める。
21//! 2. **1 つの組が上限 [`app_limit`] を超えた**とき、その組を止める(ほかのアプリがヒープを空けていても)。
22//!
23//! 判定はアプリのスレッド自身が、錠を持っていない安全な地点(`window_mgr::kill_checkpoint`)で行い、
24//! 当たったらその場で自分を終わらせる(確保の途中では落とさない)。同時に 2 つの組を止めないよう、
25//! 止めている最中の組を [`Ledger::killing`] に置き、片付けの [`Ledger::close_group`] で外す。
26//!
27//! ## 止めたアプリの背景のスレッド(TODO R2 (c)、2026-11-17 続報)
28//! 組を閉じる([`Ledger::close_group`])ことが、その組の背景のスレッドへの「止まれ」の合図になる
29//! ([`Ledger::is_closed`]。`window_mgr::current_group_stopped` が今のコアの組で見る)。
30//! 組ごとに生きているスレッドの数を数え([`Ledger::thread_enter`]・[`Ledger::thread_leave`])、
31//! 閉じた組のスレッドが残っている間はその番号を新しいアプリに配らない。
32//!
33//! この module は純粋(`crate::` を参照しない)で、ホスト試験 `tests/src/test_mem_quota.rs`・
34//! `tests/src/test_group_stop.rs` から `#[path]` で使う。
35
36use core::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU8, AtomicUsize, Ordering};
37
38/// 組の数(0 は OS)。同時に動くアプリのスレッドは `window_mgr::MAX_RUNNERS`(16)まで。
39pub const GROUPS: usize = 32;
40/// コアの数。
41pub const CORES: usize = 4;
42/// OS・主要プロセス用の取り置き(`allocator::OS_HEAP_RESERVE` と同じ値。試験でも同じことを確かめる)。
43pub const RESERVE: usize = 32 * 1024 * 1024;
44/// ヒープの空きがこれを下回ったら「尽きかけ」(取り置き 32MB の手前に 32MB の余裕を置く)。
45/// 取り置きを割る確保はアプリ側で失敗し、確保の失敗の panic になる。その前に安全な地点で止めたい。
46pub const LOW_FREE: usize = 2 * RESERVE;
47/// 尽きかけのときに止める候補にする最小の量(これより少ない組は止めない。メモ帳などを巻き込まない)。
48pub const MIN_VICTIM: i64 = 16 * 1024 * 1024;
49
50/// 1 つのアプリ(組)の上限。アプリが使える分(全体 − 取り置き)の 7/8(768MB のヒープで 644MB)。
51///
52/// YouTube の視聴ページは 1 本目で 260〜410MB、3 本目の再生の後に 602MB まで行って尽きた(TODO A7)。
53/// それより上で、全体が尽きる(空き 64MB = 使用 704MB)より少し手前に置く。
54pub const fn app_limit(total: usize) -> usize {
55    total.saturating_sub(RESERVE) / 8 * 7
56}
57
58/// 判定の結果。
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub enum Verdict {
61    /// 止めない。
62    Keep,
63    /// この組だけで上限を超えた。
64    OverLimit,
65    /// 全体が尽きかけで、この組が一番多く持っている。
66    LargestUnderPressure,
67}
68
69/// アプリごとのメモリの帳簿。`allocator` に 1 個だけ置く(`allocator::MEM_LEDGER`)。
70pub struct Ledger {
71    /// コアごとの「今動いているスレッドの組」。
72    cur: [AtomicU8; CORES],
73    /// 組ごとの「確保 − 解放」のバイト数(狂いで負になりうる)。
74    bytes: [AtomicI64; GROUPS],
75    /// 組ごとの持ち主(アプリのスレッドのプロセス ID + 1。0 は空き)。
76    owner: [AtomicUsize; GROUPS],
77    /// ヒープの空きが [`LOW_FREE`] を下回っているか。
78    low: AtomicBool,
79    /// 止めている最中の組(0 は無し)。
80    killing: AtomicU8,
81    /// 次に配る組の番号の候補(同じ番号をすぐ使い回さないよう、順に回す)。
82    next: AtomicU8,
83    /// 組ごとの「生きているスレッドの数」(TODO R2 (c)、2026-11-17 続報)。スレッドを起こすと足し
84    /// ([`Ledger::thread_enter`])、`scheduler::exit` で引く([`Ledger::thread_leave`])。
85    /// 閉じた組でもスレッドが残っている間は、その番号を新しいアプリに配らない([`Ledger::open_group`])。
86    /// でないと、止めたアプリの背景のスレッドが新しいアプリの組に紛れ、止まる合図を見失う。
87    threads: [AtomicU32; GROUPS],
88}
89
90impl Default for Ledger {
91    fn default() -> Self {
92        Self::new()
93    }
94}
95
96impl Ledger {
97    pub const fn new() -> Self {
98        Self {
99            cur: [const { AtomicU8::new(0) }; CORES],
100            bytes: [const { AtomicI64::new(0) }; GROUPS],
101            owner: [const { AtomicUsize::new(0) }; GROUPS],
102            low: AtomicBool::new(false),
103            killing: AtomicU8::new(0),
104            next: AtomicU8::new(1),
105            threads: [const { AtomicU32::new(0) }; GROUPS],
106        }
107    }
108
109    /// 組 `g` が「閉じた」(そのアプリのスレッドが止まり、組が片付けられた)か。組 0(OS)は閉じない。
110    ///
111    /// 止めたアプリの背景のスレッドへの「止まれ」の合図はこれ(TODO R2 (c))。合図のために別の印は持たず、
112    /// 組の持ち主の欄が空いたことをそのまま使う(アトミックの読み出し 1 回)。
113    #[inline]
114    pub fn is_closed(&self, g: u8) -> bool {
115        if g == 0 {
116            return false;
117        }
118        match self.owner.get(g as usize) {
119            Some(o) => o.load(Ordering::Acquire) == 0,
120            None => false,
121        }
122    }
123
124    /// 組 `g` のスレッドが 1 本増えた(スレッドを起こした、または組を移した)。
125    pub fn thread_enter(&self, g: u8) {
126        if g == 0 {
127            return;
128        }
129        if let Some(t) = self.threads.get(g as usize) {
130            t.fetch_add(1, Ordering::AcqRel);
131        }
132    }
133
134    /// 組 `g` のスレッドが 1 本減った。残りの本数を返す(組 0 は常に 0)。
135    pub fn thread_leave(&self, g: u8) -> u32 {
136        if g == 0 {
137            return 0;
138        }
139        match self.threads.get(g as usize) {
140            Some(t) => {
141                // 0 より下へは行かない(数え漏れがあっても負にしない)。
142                let mut cur = t.load(Ordering::Acquire);
143                loop {
144                    let next = cur.saturating_sub(1);
145                    match t.compare_exchange_weak(cur, next, Ordering::AcqRel, Ordering::Acquire) {
146                        Ok(_) => return next,
147                        Err(v) => cur = v,
148                    }
149                }
150            }
151            None => 0,
152        }
153    }
154
155    /// スレッドを組 `from` から組 `to` へ移す(数だけ。`scheduler::set_current_mem_group`)。
156    pub fn move_thread(&self, from: u8, to: u8) {
157        if from == to {
158            return;
159        }
160        self.thread_leave(from);
161        self.thread_enter(to);
162    }
163
164    /// 組 `g` の生きているスレッドの数。
165    pub fn threads_of(&self, g: u8) -> u32 {
166        match self.threads.get(g as usize) {
167            Some(t) if g != 0 => t.load(Ordering::Acquire),
168            _ => 0,
169        }
170    }
171
172    /// コア `core` の今の組。
173    #[inline]
174    pub fn core_group(&self, core: usize) -> u8 {
175        match self.cur.get(core) {
176            Some(c) => c.load(Ordering::Relaxed),
177            None => 0,
178        }
179    }
180
181    /// コア `core` で動くスレッドが変わった(`scheduler::schedule`)。
182    #[inline]
183    pub fn set_core_group(&self, core: usize, group: u8) {
184        if let Some(c) = self.cur.get(core) {
185            c.store(group, Ordering::Relaxed);
186        }
187    }
188
189    /// 確保の後に呼ぶ(**アロケータの錠の中**。書き手は錠で 1 人なので読み出し+書き込みで足りる)。
190    /// `free_after` は確保の後のヒープの空き。
191    #[inline]
192    pub fn on_alloc(&self, core: usize, size: usize, free_after: usize) {
193        let g = self.core_group(core) as usize;
194        if g != 0 {
195            if let Some(b) = self.bytes.get(g) {
196                b.store(b.load(Ordering::Relaxed).wrapping_add(size as i64), Ordering::Relaxed);
197            }
198        }
199        self.update_low(free_after);
200    }
201
202    /// 解放の後に呼ぶ(**アロケータの錠の中**)。`free_after` は解放の後のヒープの空き。
203    #[inline]
204    pub fn on_dealloc(&self, core: usize, size: usize, free_after: usize) {
205        let g = self.core_group(core) as usize;
206        if g != 0 {
207            if let Some(b) = self.bytes.get(g) {
208                b.store(b.load(Ordering::Relaxed).wrapping_sub(size as i64), Ordering::Relaxed);
209            }
210        }
211        self.update_low(free_after);
212    }
213
214    /// 値が変わるときだけ書く(毎回書くと 4 コアの間でキャッシュの行が行き来する)。
215    #[inline]
216    fn update_low(&self, free_after: usize) {
217        let low = free_after < LOW_FREE;
218        if self.low.load(Ordering::Relaxed) != low {
219            self.low.store(low, Ordering::Relaxed);
220        }
221    }
222
223    /// ヒープの空きが尽きかけているか。
224    #[inline]
225    pub fn is_low(&self) -> bool {
226        self.low.load(Ordering::Relaxed)
227    }
228
229    /// 組 `g` が持っている量(0 未満は 0)。
230    pub fn bytes_of(&self, g: u8) -> i64 {
231        match self.bytes.get(g as usize) {
232            Some(b) => b.load(Ordering::Relaxed).max(0),
233            None => 0,
234        }
235    }
236
237    /// 組 `g` の持ち主のプロセス ID(空きなら `None`)。
238    pub fn owner_of(&self, g: u8) -> Option<usize> {
239        let v = self.owner.get(g as usize)?.load(Ordering::Acquire);
240        (v != 0).then(|| v - 1)
241    }
242
243    /// 止めている最中の組(0 は無し)。
244    pub fn killing(&self) -> u8 {
245        self.killing.load(Ordering::Acquire)
246    }
247
248    /// アプリのスレッド `pid` に新しい組を配る(量は 0 から)。空きが無ければ 0(数えない)。
249    pub fn open_group(&self, pid: usize) -> u8 {
250        let start = self.next.load(Ordering::Relaxed) as usize;
251        for i in 0..GROUPS - 1 {
252            // 1..GROUPS を start から順に回る。
253            let g = 1 + (start.wrapping_sub(1).wrapping_add(i)) % (GROUPS - 1);
254            // 閉じた組でも、止めたアプリの背景のスレッドがまだ残っていれば配らない(TODO R2 (c))。
255            if self.threads[g].load(Ordering::Acquire) != 0 {
256                continue;
257            }
258            let slot = &self.owner[g];
259            if slot.compare_exchange(0, pid + 1, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
260                self.bytes[g].store(0, Ordering::Relaxed);
261                let nx = 1 + g % (GROUPS - 1);
262                self.next.store(nx as u8, Ordering::Relaxed);
263                return g as u8;
264            }
265        }
266        0
267    }
268
269    /// プロセス `pid` の組を閉じる(アプリ本体を解放した後に呼ぶ)。閉じた組の番号を返す。
270    pub fn close_group_of(&self, pid: usize) -> Option<u8> {
271        for g in 1..GROUPS {
272            if self.owner[g].load(Ordering::Acquire) == pid + 1 {
273                self.close_group(g as u8);
274                return Some(g as u8);
275            }
276        }
277        None
278    }
279
280    /// 組 `g` を閉じる。止めている最中の組なら、その印も外す。
281    pub fn close_group(&self, g: u8) {
282        if let Some(o) = self.owner.get(g as usize) {
283            o.store(0, Ordering::Release);
284        }
285        let _ = self.killing.compare_exchange(g, 0, Ordering::AcqRel, Ordering::Relaxed);
286    }
287
288    /// 組 `g`(呼ぶのはその組のアプリのスレッド)を止めるべきか。`total` はヒープ全体の大きさ。
289    ///
290    /// ふだんの道(尽きかけでなく上限の内)は、アトミックの読み出し 2 回で `Keep` を返す。
291    pub fn verdict(&self, g: u8, total: usize) -> Verdict {
292        if g == 0 || g as usize >= GROUPS {
293            return Verdict::Keep;
294        }
295        let own = self.bytes_of(g);
296        let low = self.is_low();
297        let over = own > app_limit(total) as i64;
298        if !low && !over {
299            return Verdict::Keep;
300        }
301        if self.owner_of(g).is_none() {
302            return Verdict::Keep;
303        }
304        let k = self.killing();
305        if k != 0 && k != g {
306            // 別の組を止めている最中(その解放を待つ)。
307            return Verdict::Keep;
308        }
309        if over {
310            return Verdict::OverLimit;
311        }
312        if own < MIN_VICTIM {
313            return Verdict::Keep;
314        }
315        // 生きている組の中で一番多いか(同じ量なら番号の小さい方)。
316        for h in 1..GROUPS as u8 {
317            if h == g || self.owner_of(h).is_none() {
318                continue;
319            }
320            let other = self.bytes_of(h);
321            if other > own || (other == own && h < g) {
322                return Verdict::Keep;
323            }
324        }
325        Verdict::LargestUnderPressure
326    }
327
328    /// 組 `g` を止めると決めた印を立てる(ほかの組が同時に止めに入らないように)。
329    /// 既に別の組を止めている最中なら false。
330    pub fn begin_kill(&self, g: u8) -> bool {
331        match self.killing.compare_exchange(0, g, Ordering::AcqRel, Ordering::Relaxed) {
332            Ok(_) => true,
333            Err(cur) => cur == g,
334        }
335    }
336}