后备高速缓存-kmem_cache

本文深入探讨Linux内核中的slab分配器,包括kmem_cache数据类型的使用,如何创建、分配、释放内存对象及缓存。解析SLAB标志的作用,如一致性检查、红区对象、对象中毒等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值