分类: LINUX
2011-07-04 23:23:41
/*
vmalloc,kmalloc,get_free_page,kmem_cache_create
vmalloc与kmalloc区别在于起始地址不同,kmalloc分配的内存处于3GB~high_memory之间,这段内核
空间与物理内存的映射一一对应,而vmalloc分配的内存在VMALLOCSTAERT~4GB之间,这段非连续内存
区映射到物理内存也可能是非连续的,vmalloc分配的物理地址无需连续,而kmalloc确保页在物理上
是连续的
*/
unsigned char * vmchar;
unsigned char * kmchar;
unsigned char * m_free_pages;
struct kmem_cache_t * kmem_cache;
unsigned char * slabchar;
static int __init mem_test_init(void)
{
printk("Hello, world/n");
//vmalloc test
//分配虚拟内存,也就是位于高端128M内存
printk("[vmalloc] Enter Jiffy %ld/n",jiffies);
vmchar = (unsigned char *)vmalloc(16*1024*1024);
if (!vmchar)
{
printk("Error on vmalloc/n");
return -1;
}
memset(vmchar,0,16*1024*1024);
printk("vmalloc address : %x/n",vmchar);
//kmalloc test
//kmalloc分配的低端内存,直接映射到物理内存
printk("[kmalloc] Enter Jiffy %ld/n",jiffies);
//kmalloc最大只能开辟128k
kmchar = (unsigned char *)kmalloc(PAGE_SIZE*32,GFP_KERNEL);
if (!kmchar)
{
printk("Error on kmalloc/n");
return -1;
}
memset(kmchar,0,PAGE_SIZE*32);
printk("kmalloc address : %x/n",kmchar);
printk("[kmalloc] Exit Jiffy %ld/n",jiffies);
//get_free_page test
//也是使用kmalloc分配的内存区域
printk("[get_free_pages] Enter Jiffy %ld/n",jiffies);
m_free_pages = (unsigned char *)__get_free_pages(GFP_KERNEL,2);
if (!m_free_pages)
{
printk("Error on m_free_pages/n");
return -1;
}
memset(m_free_pages,''a'',PAGE_SIZE*2);
/*
while(m_free_pages)
{
printk("[get_free_pages] address == %x/n",m_free_pages>>PAGE_SHIFT);
}
*/
printk("get_free_pages address : %x/n",m_free_pages);
printk("[get_free_pages] Exit Jiffy %ld/n",jiffies);
//slab alloc test
//使用后备高速缓存,对于反复地分配很多同一大小的内存块使用Slab分配方式
printk("[Slab] Enter Jiffy %ld/n",jiffies);
kmem_cache = kmem_cache_create("slab_cache",4,0,SLAB_HWCACHE_ALIGN,NULL);
if (!kmem_cache)
{
printk("Error on Slab/n");
return -1;
}
slabchar = kmem_cache_alloc(kmem_cache,GFP_KERNEL);
if (!slabchar)
{
printk("Error on alloc slab cache/n");
return -1;
}
memset(slabchar,0,4);
printk("Slab address : %x/n",slabchar);
kmem_cache_free(kmem_cache,slabchar);
kmem_cache_destroy(kmem_cache);
printk("[Slab] Exit Jiffy %ld/n",jiffies);
return 0;
}
static void __exit mem_test_exit(void)
{
vfree(vmchar);
kfree(kmchar);
free_pages(m_free_pages,2);
}
module_init(mem_test_init);
module_exit(mem_test_exit);