Nov 20, 2010

Kernel Shared Memory (KSM)

Kernel Shared Memory[1] 有時也被稱為 Kernel Samepage Merging 是在 linux 2.6.32[2] 被加入 main tree 裡,簡單的話,它的目地如 XEN的 Memory CoW[3] 與 VmWare 的 Transparent Page Sharing[4] 一樣,把相同內容的 page merge 在一起就是做 de-duplication 的動作讓記憶體空間更有效的被利用,當然相對地,需要花更多的 CPU 效能來做這些事,不過相對上來說,因該還是值得的。

動手玩看看前,先確定 linux kernel > 2.6.32 and Enable KSM
$ cat /boot/config-`uname -r` | grep KSM
CONFIG_KSM=y

KSM 只能使用在利用 madvise syscall 將記憶體區塊設為 MADV_MERGEABLE,另外如要取消改為 MADV_UNMERGEABLE。所以需要確認 KVM 的版本 > v0.12.0-rc0。

linux 有 Enable KSM 的話,/sys/kernel/mm/ksm/ 會有以下檔案
pages_shared how many shared pages are being used
pages_sharing how many more sites are sharing them i.e. how much saved
pages_unshared how many pages unique but repeatedly checked for merging
pages_volatile how many pages changing too fast to be placed in a tree
full_scans how many times all mergeable areas have been scanned
run Whether the KSM process is running.
sleep_millisecs how many milliseconds ksmd should sleep before performing another page scan.

開始使用
1. 開啟 KSM 功能
echo 1 > /sys/kernel/mm/ksm/run

2. 開二個相似的 VM image
/opt/bin/qemu -hda xp.raw -m 1024 &
/opt/bin/qemu -hda xp2.raw -m 1024 &

下面的二張圖是有開KSM跟沒關的差別,可明顯的看出,開了KSM的記憶體使用量少了一半左右


[1] http://lwn.net/Articles/306704/
[2] http://kernelnewbies.org/Linux_2_6_32
[3] http://www.xen.org/files/xensummit_fall07/18_GregorMilos.pdf
[4] http://kb.vmware.com/kb/1021095

No comments: