浅析Kernel中的cache机制

来源:互联网 发布:js url encode 编码 编辑:程序博客网 时间:2024/06/01 19:17

浅析Kernel中的cache机制

内核中的各个子系统都有cache的身影,这篇文章尝试分析一下常用的子系统中所使用的cache机制及实现.


首先,来看一下slab cache: Android 2.X系列的kernel里默认使用的slab allocation.

slab cache的思想最初由Jeff Bonwick早Sun OS中诞生(可敬的SUN, 可悲的SUN, 总是看到一些技术最初来自于它,就跟我经常看到一些技术来自与IBM一样).它的关键理念是提供了一些经常被使用的object, 这些object只需要被初始化一次,可以被系统多次使用.这样就节省了各种初始化的时间及分配它们的时间.尤其对系统中经常需要用到的一些小的object,比如mutex. Linux内核中按大小提供了一系列的slab cache来给不同的场景使用,它们被使用一个list管理起来. 关键的kmem_cache的结构可以在源码处slab_def.h中找到.


如上图所示,每种kmem_cache都包含有一系列的slabs,它们会被按填充的内容及着色方法来被管理.具体提供给驱动开发者使用的接口在slab.c中有各个函数的注释都可以看到!这里就不详细的讨论了.在参考资料 1中也有描述.只不过最新的kernel的接口的参数与这篇文章稍有不同.


可以通过cat /proc/slabinfo看到当前系统中所有slab的信息.同时,sys/class/slab/*下有更详细的信息.对应的相关调试信息可以通过init/Kconfig中有关slab的配置选项来打开.


详细的参看关于<重读<Understanding The Linux Virtual Memory Manager>笔记中第八章的描述

再来看一下,slub cache: Ubuntu 10.10默认的kernel里使用的就是slub allocation.
choice
    prompt "Choose SLAB allocator"
    default SLUB
    help
       This option allows to select a slab allocator.

config SLAB
    bool "SLAB"
    help
      The regular slab allocator that is established and known to work
      well in all environments. It organizes cache hot objects in
      per cpu and per node queues.

config SLUB
    bool "SLUB (Unqueued Allocator)"
    help
       SLUB is a slab allocator that minimizes cache line usage
       instead of managing queues of cached objects (SLAB approach).
       Per cpu caching is realized using slabs of objects instead
       of queues of objects. SLUB can use memory efficiently
       and has enhanced diagnostics. SLUB is the default choice for
       a slab allocator.

config SLOB
    depends on EMBEDDED
    bool "SLOB (Simple Allocator)"
    help
       SLOB replaces the stock allocator with a drastically simpler
       allocator. SLOB is generally more space efficient but
       does not perform as well on large systems


最后来看一下slob cache:

它是为内存很小的嵌入式设备准备的,当CONFIG_SLAB选项被disable后, 内核会去使用SLOB作为替代.

开启了它之后, slab emulation layer 最终会调用SLOB提供的接口.目前的Android的内核都没有使用该SLOB.估计一些更加嵌入的设备会考虑使用它吧.

由于使用场景有限,这里就不仔细研究它了.


updated: 对了,还需要注意的是, 内核对于page的管理, 除了有slab之外, 其它的page都是通过LRU来管理, 这里需要分清楚.


再说些题外话, Linux Memory Manager是一项很有挑战的工程, 相关的资料可以在邮件列表和Linux-MM的网站上找到. 里面有帮助理解linux的内存管理的有用的文档. 之后我也会写下自己对linux内存管理的理解.


参考资料:

1. http://www.ibm.com/developerworks/linux/library/l-linux-slab-allocator/

2. http://www.makelinux.net/ldd3/chp-8-sect-2

3. http://lwn.net/Articles/157944/ slob介绍

4. http://www.kernel.org/doc/gorman/html/understand/understand011.html slab的经典书籍