Linux内核的高速缓存管理有时称为‘slab分配器’。因此,相关函数和类型在<linux/slab.h>中声明。
数据类型kmem_cache。
创建缓存:
struct kmem_cache *kmem_cache_create(const char *name, size_t size, size_t align,
unsigned long flags,
void (*ctor)(void *));
name:A string which is used in /proc/slabinfo to identify this cache. 与整个高速缓存相关联,其功能是保管一些指向该名称的指针,而不是复制其内容,因此,驱动程序应该将指向静态(通常可取直接字符串)的指针传递给这个函数。名称不能包含空白。
size:The size of objects to be created in this cache.
align:The required alignment for the objects.
flags:SLAB flags。是一个掩码。
/*
* Flags to pass to kmem_cache_create().
* The ones marked DEBUG are only valid if CONFIG_DEBUG_SLAB is set.
*/
#define SLAB_CONSISTENCY_CHECKS 0x00000100UL /* DEBUG: Perform (expensive) checks on alloc/free */
#define SLAB_RED_ZONE 0x00000400UL /* DEBUG: Red zone objs in a cache */
#define SLAB_POISON 0x00000800UL /* DEBUG: Poison objects */
#define SLAB_HWCACHE_ALIGN 0x00002000UL /* Align objs on cache lines */
#define SLAB_CACHE_DMA 0x00004000UL /* Use GFP_DMA memory */
#define SLAB_STORE_USER 0x00010000UL /* DEBUG: Store the last owner for bug hunting */
#define SLAB_PANIC 0x00040000UL /* Panic if kmem_cache_create() fails */
ctor:A constructor for the objects.
分配内存对象:
一旦某个对象的高速缓存被创建,就可以调用kmem_cache_alloc从中分配内存对象。
void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags);
cachep:The cache to allocate from.就是刚创建的cache。
flags:和传递给kmalloc的相同。
释放内存对象:
void kmem_cache_free(struct kmem_cache *cachep, void *objp)
cachep:是创建的cache。
objp:是通过kmem_cache_alloc分配内存的对象。
释放缓存:
如果驱动程序代码中和高速缓存有关的部分已经处理完了(一个经典的情况是模块被卸载的时候),这时驱动程序应该释放它的高速缓存,函数如下:
void kmem_cache_destroy(struct kmem_cache *s);