Kernel Memory
Why Kernel Memory?
Isolation
如果 kernel 的資料和 user process 的資料混在同一塊記憶體裡,那麼一個惡意程式就可能直接讀取或竄改 kernel 的資料,造成嚴重的資安問題,因此每個 process 的 virtual address space 被分成了兩段
- User Mode Space
- Kernel Space
One Copy
所以 process 的 kernel space 都映射到同一塊 physical memory,因為所有 process 的 kernel 都一樣,所以只需要一份足矣
Why Discuss Kernel Memory Allocation?
Kernel’s request is predictable
kernel 的需求是可預測的。 User space 的程式可能動態分配任意大小的記憶體(像是 malloc),但 kernel 程式碼是編譯好、靜態的,它用到的資料結構種類有限(例如 task_struct、inode、page 等)。這意味著 kernel 可以事先「知道」自己會需要哪幾種大小的物件,如此我們就可以透過特別的分配方式大幅提升效率
Free-Memory Pool
既然我們已經知道了 kernel 會怎麼使用他的記憶體,那麼我們就可以在 kernel 真正使用這些 memory 前就先初始化好
沒有 Pool 的 kernel 記憶體:
┌────────────────────────────────┐
│ 一大塊空閒記憶體,要用再去切 │
└────────────────────────────────┘
有 Pool 的 kernel 記憶體:
┌──────────────────────────────────────┐
│ [task_struct][task_struct][task_struct] │ ← task_struct pool
│ [inode ][inode ][inode ] │ ← inode pool
│ [page ][page ][page ] │ ← page pool
└──────────────────────────────────────┘
Some Kernel’s Physical Memory is Physically Contiguous
Kernel 有些功能會需要連續的 physical memory
1. DMA (Direct Memory Access)
DMA 是負責在不需要 CPU 幫助的情況下在 disk 和 memory 間搬移資料的硬體,它沒有 MMU,只能操作 physical address,因此交給他的 buffer 必須是 physically contiguous
2. Early Boot
Kernel 啟動初期 paging 機制尚未建立,MMU 還沒開始工作,kernel image 必須載入到連續的 physical memory 才能正確執行
3. Efficiency
physically contiguous 的記憶體可以用 large pages(如 2MB hugepages)映射,減少 TLB entry 數量,提升 cache locality