Linux 核心 OOM Killer 與 Android LMKd 協同機制深度拆解:從 oom_badness 評分算法到端側 LLM 記憶體防禦實戰 / Deconstructing Linux Kernel OOM Killer and Android LMKd Orchestration: From oom_badness Scoring Algorithm to Edge LLM Memory Defense in Practice
daily-tech:2026-11-30
Linux 核心 OOM Killer 與 Android LMKd 協同機制深度拆解:從 oom_badness 評分算法到端側 LLM 記憶體防禦實戰 / Deconstructing Linux Kernel OOM Killer and Android LMKd Orchestration: From oom_badness Scoring Algorithm to Edge LLM Memory Defense in Practice
現象:在現代旗艦 Android 智慧型手機、智慧車載系統與邊緣運算(Edge AI)硬體上,部署 2B 至 7B 參數規模的端側大語言模型(On-Device LLM,如 Gemma 2、Llama 3 或 Qwen 2.5)已經成為可能。然而,許多軟體團隊在實機壓測時常遭遇令人費解的崩潰現象:當模型剛載入時運作正常,但在長對話或使用者輸入複雜多輪提示時,模型吐字進行到第 2,000 個 Token 左右,整個應用程式突然毫無預警閃退;嚴重時,甚至整個系統 UI 出現長達數秒的凍結(System Freezing),隨後桌面啟動器(Launcher)重新加載,終端日誌中僅留下怵目驚心的 Out of memory: Kill process or sacrifice child 訊息。為什麼明明設備具備 8GB 甚至 12GB 實體 LPDDR 記憶體,系統卻依然會慘遭「爆記憶體」?當實體記憶體耗盡時,Linux 核心底層的 OOM Killer 究竟是依據什麼規則決定要殺死哪一個行程?而 Android 的低記憶體守護行程(LMKd)又是如何與 Linux 核心協同作戰,避免系統在端側 AI 狂暴的記憶體消耗下直接崩潰?
Symptom: On modern Android flagship smartphones, automotive cockpits, and edge computing platforms, deploying 2B to 7B parameter on-device Large Language Models (LLMs)—such as Gemma 2, Llama 3, or Qwen 2.5—has become feasible. However, engineering teams frequently encounter perplexing runtime crashes during stress tests: the model loads successfully, but during extended multi-turn conversations where generation reaches roughly the 2,000-token threshold, the application abruptly vanishes without an unhandled exception stack trace. In worse cases, the entire system UI freezes for several seconds before the launcher process restarts, leaving only the chilling kernel message Out of memory: Kill process or sacrifice child in the dmesg logs. Why does a device equipped with 8GB or even 12GB of physical LPDDR memory still suffer from catastrophic out-of-memory events? Under severe memory starvation, what precise mathematical heuristics govern the Linux kernel's OOM Killer when selecting a victim process, and how does Android's userspace Low Memory Killer daemon (LMKd) orchestrate with the kernel to prevent system collapses under aggressive on-device AI workloads?
機制:從 oom_badness 核心原始碼剖析到 Android LMKd 與 PSI 協同管線 / Mechanism: From Kernel oom_badness Source Code to Android LMKd and PSI Pipeline
要透徹理解這套崩潰防禦體系,我們必須直接翻開 Linux 6.18 核心原始碼 mm/oom_kill.c,直擊 oom_badness() 的底層計分邏輯。當系統實體記憶體低於低水位線(Low Watermark)且記憶體回收執行緒(kswapd)與直接回收(Direct Reclaim)均宣告失敗時,核心別無選擇,只能觸發 OOM Killer。核心對每個候選行程評估的懲罰分數演算法如下:
To master this crash defense hierarchy, we examine the Linux 6.18 kernel source in mm/oom_kill.c, analyzing the foundational heuristic within oom_badness(). When physical memory plunges below the kernel low watermark and both asynchronous reclamation (kswapd) and synchronous direct reclamation fail, the kernel invokes the OOM Killer. The badness score calculated for each candidate task strictly follows this kernel logic:
// 核心原始碼引用:Linux 6.18.55 (mm/oom_kill.c: lines 202-237)
long oom_badness(struct task_struct *p, unsigned long totalpages)
{
long points;
long adj;
if (oom_unkillable_task(p))
return LONG_MIN;
p = find_lock_task_mm(p);
if (!p)
return LONG_MIN;
adj = (long)p->signal->oom_score_adj;
if (adj == OOM_SCORE_ADJ_MIN ||
mm_flags_test(MMF_OOM_SKIP, p->mm) ||
in_vfork(p)) {
task_unlock(p);
return LONG_MIN;
}
// 基礎基準分:該行程實體常駐記憶體 (RSS) + 交換分頁 (Swap) + 分頁表開銷
points = get_mm_rss(p->mm) + get_mm_counter(p->mm, MM_SWAPENTS) +
mm_pgtables_bytes(p->mm) / PAGE_SIZE;
task_unlock(p);
// 正規化 oom_score_adj 權重調整(範圍 -1000 到 +1000)
adj *= totalpages / 1000;
points += adj;
return points;
}從核心代碼中可以清楚看見:
1. 記憶體基準分(Baseline Points):核心計算該行程實際佔用的實體記憶體常駐集大小(Resident Set Size, RSS)、已換出的 Swap 區塊大小,以及該行程自身分頁表(Page Tables)所耗用的記憶體頁面數總和。這意味著**常駐記憶體越肥大的行程,被殺死的機率成正比飆升**。
2. 權重加權調節(oom_score_adj):核心將使用者空間設定的 oom_score_adj(範圍由 -1000 至 +1000)乘以 totalpages / 1000,轉換為實體頁面數量直接加到 points 上。若設為 OOM_SCORE_ADJ_MIN(-1000),該行程直接享有免死金牌(回傳 LONG_MIN),核心絕不擊殺。
3. Android LMKd 的早預警介入(PSI 機制):若放任系統跌入 Linux 核心層級的 OOM Killer,後果是毀滅性的——整個核心陷入重度鎖競爭(Lock Contention),且核心只看記憶體大小,無法理解「這個行程是前景正在對話的 AI,還是背景沒用的快取」。因此,Android 在使用者空間打造了 LMKd(Low Memory Killer Daemon)。現代 LMKd 透過 Linux 核心的 PSI(Pressure Stall Information,/proc/pressure/memory) 監控系統記憶體停頓時間。當 some 或 full 記憶體停頓指標越過閾值時,LMKd 立即啟動「階梯式擊殺」:先砍 oom_score_adj = 900~999 的快取 App(Cached),若壓力未減緩,再砍 700~800 的前一個 App(Previous),以極小代價迅速換取記憶體喘息空間,**力保前景端側 AI 行程(adj 通常為 0)不受波及**。
Dissecting the source code reveals three critical realities:
1. Baseline Memory Points: The kernel sums the task's Resident Set Size (RSS), swapped pages (Swap), and internal page table footprint. Consequently, **the larger a process swells in physical RAM, the higher its probability of being targeted**.
2. Adjustment Normalization (oom_score_adj): The userspace score adjustment oom_score_adj (spanning -1000 to +1000) is scaled by totalpages / 1000 and added directly to points. If configured to OOM_SCORE_ADJ_MIN (-1000), the process is deemed unkillable (returning LONG_MIN).
3. Proactive Android LMKd via PSI: Surrendering to the kernel-level OOM Killer is catastrophic—severe lock contention freezes the OS, and the kernel lacks context to distinguish a foreground interactive AI assistant from a dormant background service. Hence, Android operates the userspace LMKd, monitoring Linux PSI (Pressure Stall Information via /proc/pressure/memory). When memory stall thresholds are breached, LMKd executes stepped pre-emptive culling: first terminating cached apps (oom_score_adj = 900~999), progressing to previous apps (700~800), reclaiming pages proactively to **insulate the foreground AI process (adj = 0) from kernel slaughter**.
影響:端側 LLM 的動態 KV 快取爆炸與系統崩潰邊界 / Impact: Dynamic KV Cache Explosion and System Collapse Boundaries in Edge LLMs
端側大語言模型之所以極易誘發 OOM,其根因在於其獨特的記憶體架構:
1. 模型靜態權重(Static Weights):以 4-bit 量化(INT4)的 7B 參數模型為例,靜態權重約佔用 3.8GB 至 4.2GB 記憶體。這部分記憶體通常以 mmap 映射,在記憶體緊張時可由核心直接回收分頁(Drop Clean Pages),代價僅是稍後存取時產生 Minor Page Fault。
2. 動態 KV 快取(Dynamic KV Cache 致命黑洞):LLM 在自回歸解碼(Autoregressive Generation)過程中,每生成一個 Token,就必須在記憶體中為所有 Transformer 層保存 Key 與 Value 張量。對於 2K 上下文長度,以 FP16 保存的 KV 快取即高達 1.5GB 甚至更高,且這些屬於**無法丟棄的匿名記憶體(Anonymous Memory)**。隨著對話長度增加,記憶體佔用呈現線性飆升。若缺乏動態分頁管理,匿名頁激增將迅速擠佔所有可用空間,導致 LMKd 殺無可殺,最終 Linux OOM Killer 鎖定佔用記憶體最大的端側 AI 進程直接斬首!
3. 快取收縮與記憶體頻寬枯竭:當記憶體水位逼近極限時,Linux 核心會強制縮減 Page Cache(檔案系統快取),這會使 Android 系統的各項 I/O 操作直接變成磁碟同步阻塞,產生嚴重的「掉幀與凍結」,讓使用者誤以為是 AI 模型算力不足,實則是記憶體子系統已陷入崩潰邊緣。
Why on-device LLMs are singularly prone to OOM triggers stems from their distinct memory footprint:
1. Static Model Weights: An INT4-quantized 7B parameter model requires approximately 3.8GB to 4.2GB of baseline storage. Typically loaded via mmap, clean pages can be evicted under pressure at the expense of minor page faults.
2. Dynamic KV Cache (The Black Hole): During autoregressive token generation, the attention mechanism caches Key and Value projections for all attention layers. For a 2,048-token context in FP16, the KV cache demands 1.5GB+ of **strictly unevictable anonymous memory**. Without segmented allocation, continuous conversation linear expansion exhaustively burns DRAM, depleting LMKd candidate pools until the kernel OOM Killer executes the AI application as the highest-scoring candidate.
3. Buffer Eviction and I/O Thrashing: Extreme memory pressure collapses page caches, converting regular filesystem reads across Android into blocking disk transactions. This manifests as system-wide micro-stuttering, mistaken for compute constraints when memory exhaustion is the true culprit.
可操作小步驟:端側 AI 記憶體監控與防護實戰 / Actionable Steps: Edge AI Memory Profiling and Defense in Practice
可操作小步驟:在端側 AI 系統開發與 Linux/Android 驅動整合時,建議採取以下三道實作防線:
Actionable Steps: When deploying edge AI workloads on Linux and Android, implement the following three engineering defenses:
# 步驟 1:實機觀察 Linux 核心 PSI 記憶體停頓壓力狀態
# 讀取當前記憶體壓力指標 (some=任務受阻, full=全系統受阻)
adb shell cat /proc/pressure/memory
# 預期輸出:
# some avg10=2.15 avg60=1.42 avg300=0.85 total=1254820
# full avg10=0.50 avg60=0.20 avg300=0.05 total=452100
# 步驟 2:檢查端側 AI 服務的 oom_score 與 oom_score_adj
PID=$(adb shell pidof com.example.edge.ai)
echo "PID: $PID"
adb shell cat /proc/$PID/oom_score
adb shell cat /proc/$PID/oom_score_adj
# 步驟 3:在 Android 服務中提升 AI 推論行程優先級,避免被誤殺
# 透過 Foreground Service 或宣告 Process Priority 防止 adj 跌入後台快取區
# 或在開發除錯環境下給予保護:
adb shell "echo -500 > /proc/$PID/oom_score_adj"
# 步驟 4:端側 LLM 採用 PagedAttention 與 KV 快取動態量化 (INT8/INT4)
// C++ / LiteRT 架構範例:限制最大 KV Cache 上限並啟用滑動窗口 (Sliding Window)
ModelConfig config;
config.max_context_length = 2048;
config.enable_paged_kv_cache = true;
config.kv_cache_quantization = QuantType::INT8; // 節省 50% 匿名記憶體!
config.memory_pressure_callback = [](MemoryPressureLevel level) {
if (level == MemoryPressureLevel::CRITICAL) {
// 核心或 LMKd 發出壓力警報時,主動釋放歷史對話 KV 張量
EvictOldestKVTensors();
}
};oom_badness() 斬首門檻的隱形推手。善用 Linux PSI 監聽機制與 Android LMKd 協同,並採用 PagedAttention 與動態上下文窗口截斷,才是保障端側 AI 穩定運作的核心解法。Kernel Note: In edge LLM architecture, never dimension memory solely around static weights. Dynamic KV cache growth coupled with page table overhead triggers
oom_badness() execution. Combining Linux PSI hooks with Android LMKd and PagedAttention sliding windows ensures continuous operational resilience.Recommended Gear: Exploring Linux kernel systems and edge embedded AI demands reliable high-speed debugging hardware. This thermal-engineered NVMe enclosure ensures sustained high-throughput trace capture and model testing.
查看高效能 NVMe 固態硬碟盒與開發者除錯週邊
(本文包含分潤合作連結,點擊購買可支持本研究所持續產出高品質技術深度拆解)
導流與延伸閱讀 / Related Articles
【上一篇回顧】:Linux DMA-BUF 跨晶片零拷貝架構深度拆解:從 GPU/NPU 緩衝共享到 Android 端側 AI 推論管線優化
【下一篇預告】:從 eBPF 看 Linux 核心網路封包路徑:XDP 零拷貝過濾與安全防禦實戰
參考資料與官方文獻 / References
- Linux Kernel Source Code (v6.18.55):
mm/oom_kill.c(lines 202-243),oom_badness()implementation, check date: 2026-11-30. - Android Open Source Project (AOSP): Low Memory Killer Daemon (LMKd) Architecture & PSI Integration, check date: 2026-11-30.
- Linux Kernel Documentation: Pressure Stall Information (PSI), check date: 2026-11-30.
- Android Developer Guide: Manage your app's memory, check date: 2026-11-30.
留言
張貼留言