系统相关
首页 > 系统相关> > 《内核kernel:slab内存分配模块编写》

《内核kernel:slab内存分配模块编写》

作者:互联网

一、模块编写

#include <linux/module.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/init.h>

static char *kbuf;
static int size = 21*PAGE_SIZE;
static struct kmem_cache *my_cache;
module_param(size, int, 0644);

static int __init my_init(void)
{
	/* create a memory cache */
	if (size > KMALLOC_MAX_SIZE) {
		pr_err
		    (" size=%d is too large; you can't have more than %lu!\n",
		     size, KMALLOC_MAX_SIZE);
		return -1;
	}

	my_cache = kmem_cache_create("mycache", size, 0,
				     SLAB_HWCACHE_ALIGN, NULL);
	if (!my_cache) {
		pr_err("kmem_cache_create failed\n");
		return -ENOMEM;
	}
	pr_info("create mycache correctly\n");

	/* allocate a memory cache object */
	kbuf = kmem_cache_alloc(my_cache, GFP_ATOMIC);
	if (!kbuf) {
		pr_err(" failed to create a cache object\n");
		(void)kmem_cache_destroy(my_cache);
		return -1;
	}
	pr_info(" successfully created a object, kbuf_addr=0x%p\n", kbuf);

	return 0;
}

static void __exit my_exit(void)
{
	/* destroy a memory cache object */
	kmem_cache_free(my_cache, kbuf);
	pr_info("destroyed a cache object\n");

	/* destroy the memory cache */
	kmem_cache_destroy(my_cache);
	pr_info("destroyed mycache\n");
}

module_init(my_init);
module_exit(my_exit);

MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Ben ShuShu");

二、Makefile

BASEINCLUDE ?= /home/yexiang/work/running_kernel/runninglinuxkernel_4.0
#BASEINCLUDE ?= /lib/modules/`uname -r`/build

slab_lab-objs := slab.o

obj-m   := slab_lab.o
all :
        $(MAKE) -C $(BASEINCLUDE) M=$(PWD) modules;

clean:
        $(MAKE) -C $(BASEINCLUDE) SUBDIRS=$(PWD) clean;
        rm -f *.ko;

编译:make

运行:

/ # insmod /mnt/slab_lab.ko 
[14079.597334] create mycache correctly
[14079.600284]  successfully created a object, kbuf_addr=0xc2da0000

 

标签:pr,kernel,my,kmem,cache,内核,kbuf,slab,size
来源: https://blog.csdn.net/yexiangCSDN/article/details/96132324