一、概要

Linux “free”命令是 procps 组件的一部分。执行效果如下:

snippet.bash
[yz@ff yz]$ free -m
              total        used        free      shared  buff/cache   available
Mem:         257856       59086       67668        5136      131100      189914
Swap:         16383        3995       12388

其中相关指标不同版本procps计算方法不同。

二、used计算方法变迁

v3.3.10

https://gitlab.com/procps-ng/procps/-/blob/v3.3.10/proc/sysinfo.c

snippet.c
void meminfo(void){
  ……
  {"Cached",       &kb_page_cache},  // important
  {"MemFree",      &kb_main_free},    // important
  {"MemTotal",     &kb_main_total},   // important
  {"SReclaimable", &kb_slab_reclaimable}, // "slab reclaimable" (dentry and inode structures)
  {"Slab",         &kb_slab},         // kB version of vmstat nr_slab
  };
 
  ……
  kb_main_cached = kb_page_cache + kb_slab;
  kb_swap_used = kb_swap_total - kb_swap_free;
  kb_main_used = kb_main_total - kb_main_free - kb_main_cached - kb_main_buffers;

v3.3.12

计算内存used方法发生变更。

https://gitlab.com/procps-ng/procps/-/blob/v3.3.12/proc/sysinfo.c

snippet.c
void meminfo(void){
  ……
  {"Cached",       &kb_page_cache},  // important
  {"MemFree",      &kb_main_free},    // important
  {"MemTotal",     &kb_main_total},   // important
  {"SReclaimable", &kb_slab_reclaimable}, // "slab reclaimable" (dentry and inode structures)
  {"Slab",         &kb_slab},         // kB version of vmstat nr_slab
  };
 
  ……
  kb_main_cached = kb_page_cache + kb_slab_reclaimable; // 区别在这里
  kb_swap_used = kb_swap_total - kb_swap_free;
 
  mem_used = kb_main_total - kb_main_free - kb_main_cached - kb_main_buffers;
  if (mem_used < 0)
    mem_used = kb_main_total - kb_main_free;
  kb_main_used = (unsigned long)mem_used;

主要是用SReclaimable替代了Slab,修订说明 如下:

The previous commit added all of slab into the cache value. The thing was is cached in this context is something you can get back and reclaim if under memory pressure.
The problem was slab parameter includes both reclaimable and unreclaimable values which doesn't make sense in this context.This commit make cached only use the reclaimable component.