linux 内存回收机制

linux 4.
一、内存回收的对象
文件映射缓存,文件读写和代码段等占用一些内存,缓存文件以提高文件访问的效率,当内存紧张的时候会被丢弃或者协会磁盘后丢弃,以回收物理内存
匿名映射因为不与文件关联想要回收其所占空间不能想那样直接丢弃,利用外存空间将部分内存swap出去达到回收内存的目的
drop_cachesWriting to this will cause the kernel to drop clean caches, as well asreclaimable slab objects like dentries and inodes.Once dropped, theirmemory becomes free.To free pagecache:echo 1 > /proc/sys/vm/drop_cachesTo free reclaimable slab objects (includes dentries and inodes):echo 2 > /proc/sys/vm/drop_caches To free slab objects and pagecache:echo 3 > /proc/sys/vm/drop_caches swappinessThis control is used to define how aggressive the kernel will swapmemory pages.Higher values will increase aggressiveness, lower valuesdecrease the amount of swap.A value of 0 instructs the kernel not toinitiate swap until the amount of free and file-backed pages is lessthan the high water mark in a zone.The default value is 60.
二、内存回收的时机
1.zone 周期回收

linux 内存回收机制

文章插图
vm中的每个zone会有一个kswap负责周期的内存回收,kswap源码在mm/.c
kswap回收的主要函数 和node
是针对一些模块自己注册的 自定义cache回收
比如ubifs 中会就是回收本文件系统的TNC(tree node cache),用来缓存flash上的索引树,提高访问速度
/* UBIFS TNC shrinker description */static struct shrinker ubifs_shrinker_info = {.scan_objects = ubifs_shrink_scan,.count_objects = ubifs_shrink_count,.seeks = DEFAULT_SEEKS,};
则是去 可回收的LRU list
2.分配不到mem时候主动回收
直接回收发生在sk 中
三、LRU机制
LRU(最近使用)与二次机会原则(被使用两次的页面会转换位)是内存页面回收的方法
为了实现上述功能,以zone为单位建立了五种不同类型的页面的链表,如下图所示,内核需要回收页面的时候会优先选择链表中的末端为0的页面回收
【linux 内存回收机制】page的 与的状态的变换如下