跳到主要內容

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?

Linux 核心 OOM Killer 與 Android LMKd 雙層記憶體防禦架構端側 LLM 推論與記憶體壓力源Edge LLM / LiteRT / On-Device AI模型權重 + 動態 KV 快取分配上下文暴增 (Context Expansion)實體記憶體逼近 Low Watermark觸發 PSI (/proc/pressure/memory)產生 Some / Full 記憶體停頓事件傳統模式未優化:引發全機嚴重卡死Android 使用者空間防禦:LMKdsystem/memory/lmkd (Daemon)PSI 驅動分級清理階梯 (Kill Levels)監控 epoll /proc/pressure/memory按 oom_score_adj 優先級逐步回收CACHED (900+) → PREVIOUS (700)提前釋放匿名頁與快取,遏止雪崩保護前景 AI 服務 (adj: 0~100) 存活Linux 核心最後防線:OOM Killermm/oom_kill.c (Kernel Core)oom_badness() 終極評分算法RSS + Swap + PageTables + Adj若 LMKd 未能及時回血:觸發 OOM計算 points = (rss + swap + pt) + adj挑選最高分任務發送 SIGKILL 終止避免 Kernel Panic,維持系統存活端側 AI / LLM 記憶體階梯防禦與 OOM 調度架構對比❌ 缺乏防護:LLM 吐字時 KV 快取爆炸 → 核心直接觸發 OOM Killer → 誤殺前景 AI 行程或核心重要守護行程 [嚴重當機或閃退]✔ 雙層協同:動態 KV PagedAttention + LMKd PSI 早預警回收後台快取 + oom_score_adj 綁定保護 [推論流暢無卡頓,記憶體零崩潰]
圖 1|Linux 核心 OOM Killer 與 Android LMKd 協同防禦架構:從 PSI 早預警、oom_badness 權重計算到端側 LLM 記憶體防護模型 / Figure 1 | Linux kernel OOM Killer and Android LMKd cooperative defense architecture: from PSI early alerts to oom_badness scoring and edge LLM protection.

機制:從 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();
    }
};
核心機制備忘:在設計端側大模型應用時,永遠不能只計算靜態權重大小。動態 KV 快取加上分頁表開銷,是將系統推向 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.
好物推薦:深入研究 Linux 核心系統程式設計與端側嵌入式 AI,需要一把兼具靈活散熱與高速傳輸的除錯工具。推薦這款專為開發者設計的高效能散熱外接固態硬碟盒與 USB-C 監控排線,穩定支援高負載推論與系統日誌長時錄製。
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

  1. Linux Kernel Source Code (v6.18.55): mm/oom_kill.c (lines 202-243), oom_badness() implementation, check date: 2026-11-30.
  2. Android Open Source Project (AOSP): Low Memory Killer Daemon (LMKd) Architecture & PSI Integration, check date: 2026-11-30.
  3. Linux Kernel Documentation: Pressure Stall Information (PSI), check date: 2026-11-30.
  4. Android Developer Guide: Manage your app's memory, check date: 2026-11-30.

留言

這個網誌中的熱門文章

kimiflare:將 Moonshot Kimi-K2.6 直接部署於 Cloudflare 的終端 AI 編碼助手 | kimiflare: A Terminal Coding Agent Powered by Moonshot Kimi-K2.6 on Cloudflare

無需中繼,在你的 Cloudflare 帳戶中直接運行強大的 Kimi 終端編碼智能體。 | No middleman, run the powerful Kimi terminal coding agent directly on your own Cloudflare account. 🔎 工具速覽 / AT A GLANCE Category AI Coding Agent / Developer Tool Pricing Free (Open-weight model / Cloudflare Workers AI pricing) BestFor Developers seeking a private, high-context terminal AI assistant with direct infrastructure control. GitHub Stars ⭐ 36 🚀 引言 / Introduction kimiflare 是一款為開發者量身打造的終端編碼智能體,它將 Moonshot 的 1 兆參數開源模型 Kimi-K2.6 與 Cloudflare Workers AI 完美結合。不同於傳統 AI 工具,kimiflare 讓流量直接在你的 Cloudflare 帳戶中流動,徹底擺脫第三方代理或 AI 閘道的束縛,實現最高等級的控制力與隱私。 | kimiflare is a terminal coding agent tailored for developers, seamlessly combining Moonshot's 1T-parameter open-source model Kimi-K2.6 with Cloudflare Workers AI. Unlike traditional AI tools, kimiflare routes traffic directly through your Cloudflare account, eliminating the n...

text-to-cad: 讓 AI 驅動的參數化 CAD 建模成為現實 / text-to-cad: Bringing AI-Driven Parametric CAD Modeling to Reality

一個讓 AI 代理能生成、預覽並迭代 3D CAD 模型的開源框架 / An open-source harness for AI agents to generate, preview, and iterate 3D CAD models. 🔎 工具速覽 / AT A GLANCE Category AI-Powered CAD Tooling / AI 驅動 CAD 工具 Pricing Free (Open Source) / 免費(開源) BestFor Robotics engineers and product designers using AI coding agents / 使用 AI 程式碼代理的機器人工程師與產品設計師 GitHub Stars ⭐ 93 🚀 引言 / Introduction text-to-cad 是一個強大的開源框架,旨在填補大型語言模型(LLM)與專業 3D 建模之間的鴻溝。它允許開發者利用 Claude Code 或 Codex 等 AI 代理,透過程式碼生成精確的參數化幾何模型,並提供即時預覽與迭代能力。 text-to-cad is a powerful open-source harness designed to bridge the gap between Large Language Models (LLMs) and professional 3D modeling. It enables developers to leverage AI agents like Claude Code or Codex to generate precise parametric geometry via code, providing real-time preview and iteration capabilities. 🛠️ 核心功能 / Key Features 與 Codex 或 Claude Code 等代理...

Orca Skills: 開源賦能,加速雲安全工作流

加速雲安全工作流 - Orca Skills 整合多種工具與插件,打造高效安全環境 | Accelerate Cloud Security Workflows with Orca Skills, a Suite of Tools and Plugins 🔎 工具速覽 / AT A GLANCE Category 开源安全工具 Pricing 开源免费 BestFor 雲安全团队、DevSecOps工程师 GitHub Stars ⭐ 33 🚀 引言 / Introduction 在雲端環境中,確保安全不僅是一種技術挑戰,更是對工作效率的一場考驗。Orca Skills 是一款專為加速 Orca 云平台安全工作流而設計的开源插件工具包。透過整合多種工具和插件,幫助我們在複雜的安全環境下保持高效率。 🛠️ 核心功能 / Key Features Orca Skills 提供了一系列功能強大的安全工作流工具,包括警報處理、影響分析、配置源頭追溯等。這些工具不僅能夠幫助我們快速定位問題,還能確保在解決問題時避免造成不必要的後續問題。 💡 技術亮點 / Tech Highlights Orca Skills 真正的亮點在于其開放性與兼容性。它不僅支持Anthropic Claude Code、Cursor 和 Codex,還能夠與 MCP(Orca Security)集成,為安全團隊提供全面的支持。 📦 快速上手 / Quick Start 要快速開始使用 Orca Skills,首先需要安裝所需環境和工具。接下來,配置 MCP 以實現與 Orca Cloud Platform 的集成。最後,測試各個技能插件以確保其正常運行。 中英文對照: 要快速開始使用 Orca Skills 首先需要安裝所需環境和工具 接著配置 MCP 以實現與 Orca 云平台的集成 最...