轉載一篇關于程序記憶體計算和cgroup記憶體計算差異的文章
<a href="http://hustcat.github.io/memory-usage-in-process-and-cgroup/">http://hustcat.github.io/memory-usage-in-process-and-cgroup/</a>
在linux核心,對于程序的記憶體使用與cgroup的記憶體使用統計有一些相同和不同的地方。
程序的記憶體統計
一般來說,業務程序使用的記憶體主要有以下幾種情況:
(1)使用者空間的匿名映射頁(anonymous pages in user mode address spaces),比如調用malloc配置設定的記憶體,以及使用map_anonymous的mmap;當系統記憶體不夠時,核心可以将這部分記憶體交換出去;
(2)使用者空間的檔案映射頁(mapped pages in user mode address spaces),包含map file和map tmpfs;前者比如指定檔案的mmap,後者比如ipc共享記憶體;當系統記憶體不夠時,核心可以回收這些頁,但回收之前可能需要與檔案同步資料;
(3)檔案緩存(page in page cache of disk file);發生在程式通過普通的read/write讀寫檔案時,當系統記憶體不夠時,核心可以回收這些頁,但回收之前可能需要與檔案同步資料;
(4)buffer pages,屬于page cache;比如讀取塊裝置檔案。
其中(1)和(2)是算作程序的rss,(3)和(4)屬于page cache。
與程序記憶體統計相關的幾個檔案:
rss的計算:
對應top的rss列,do_task_stat源碼
即rss=file_rss + anon_rss
statm的介紹
statm統計資訊相關源碼見函數proc_pid_statm
top的shr=file_rss。
實際上,程序使用的共享記憶體,也是算到file_rss的,因為共享記憶體基于tmpfs。
anon_rss與file_rss的計算源碼
相關代碼
資料結構
rss and cache
可以看到,cache包含共享記憶體和file cache
mapped_file
mapped_file - # of bytes of mapped file (includes tmpfs/shmem)
從這裡可以看到,共享記憶體會增加到inactive_anon。
inactive_file
inactive_file - # of bytes of file-backed memory on inactive lru list.檔案使用的page cache(不包含共享記憶體)
示例程式
執行程式前後,cgroup memory.stat的值:
執行前:*
執行後:*
可以看到cgroup中,共享記憶體計算在cache、mapped_file、inactive_anon中。
(1)程序rss與cgroup rss的差別
程序的rss為程序使用的所有實體記憶體(file_rss+anon_rss),即anonymous pages+mapped apges(包含共享記憶體)。
cgroup rss為(anonymous and swap cache memory),不包含共享記憶體。
兩者都不包含file cache。
(2)cgroup cache包含file cache和共享記憶體。
<a href="http://man7.org/linux/man-pages/man5/proc.5.html">http://man7.org/linux/man-pages/man5/proc.5.html</a>
<a href="https://www.kernel.org/doc/documentation/cgroups/memory.txt">https://www.kernel.org/doc/documentation/cgroups/memory.txt</a>