一:背景
二:例程
#include<linux/module.h>
#include<linux/kernel.h>
#include<linux/init.h>
#include<linux/fs.h>
#include<linux/slab.h>
#include<linux/interrupt.h>
MODULE_AUTHOR("Tan xujia");
MODULE_LICENSE("Dual BSD/GPL");
struct mem {
int count;
int size;
};
struct kmem_cache *p;
static int
__init mem_init(void)
{
printk("init\n");
p = kmem_cache_create("memtest", sizeof(struct mem), 0,
SLAB_HWCACHE_ALIGN, NULL);
if(!p){
return -1;
}else {
struct mem *p1 = (struct mem*)kmem_cache_alloc(p, GFP_KERNEL);
p1->count = 10;
p1->size = 12;
printk("p1->count = %d, p1->size = %d\n",
p1->count, p1->size);
kmem_cache_free(p, p1);
}
return 0;
}
static void
__exit mem_exit(void)
{
printk("exit\n");
kmem_cache_destroy(p);
p = NULL;
return;
}
module_init(mem_init);
module_exit(mem_exit);
obj-$(CONFIG_BNXT) += a.o
bnxt_en-y := a.o
all:
make -C /usr/src/kernels/$(shell uname -r) M=$(shell pwd) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean
使用dmesg可以看到相关的打印信息。
在/proc/slabinfo里可以看到相关的信息
三:API汇总。
struct kmem_cache *
kmem_cache_create(const char *name, size_t size, size_t offset,
unsigned long flags, void (*ctor)(void *))
void kmem_cache_destroy(struct kmem_cache *s)
void *kmem_cache_alloc(struct kmem_cache *cachep, int flags)
void kmem_cache_free(struct kmem_cache *cachep, void *objp)