加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

__get_free_pages | 分配内存(直接分页) | free_pages 释放内存

(2013-03-05 10:53:02)
标签:

linux

work

育儿

分类: 计算机与 Internet
函数原型:
#include
__get_free_pages (unsigned int gfp_mask, unsigned int order);

2.4 内核需要包含的头文件是

__get_free_pages() 函数的第一个变量 gfp_mask 可以直接使用 kmalloc() 函数中使用的参数。但是,第二个变量不是指定大小,而表示 2^order 次方个页,如是 0 就分配一个页,是 3 就分配 8 个页。

如果想为分配一块内存空间,但嫌计算所需多少页比较麻烦,那可以使用 get_order() 函数来获取 order 值。如:
char *buff;
int order;
order = get_order (8192);
buff = __get_free_pages (GFP_KERNEL, order);
if (buff != NULL) {
...
free_pages (buff, order);
}

使 用该函数时,一定要注意 order 最大值,该最大值定义为 MAX_ORDER ,通常为 11 ,也可能是 10 ,这根据平台的不同而不同。如果 order 的值国大,则分配失败的几率就较高,通常使用小于 5 的值,即只分配 32 x PAGE_SIZE 大小的内存。

其实 kmalloc() 的底层实现也是基于 __get_free_pages() 。

由 __get_free_pages 申请的内存由 free_pages() 函数来释放,其原型为:
#include
free_pages(unsigned long addr, unsigned int order);


//----------------------------------------------------------------------

Driver was mapping some kernel memory (required to be physically contiguous) to userspace via noPage or page fault mechanism. Memory buffers were allocated through __get_free_pages or kmalloc. These APIs were invoked with GFP_KERNEL flag and size in some MBs. When called __get_free_pages without __GFP_COMP, returns cluster pages. A cluster page has head page refcounted and tail pages not. These pages are mapped page by page via noPage or page fault handler implemented by the driver. Before returning a page, handler calls get_page to refcount the page. Till point every thing looks normal, but problem arises, when number of pages in the particular zone, from where memory was allocated, triggers threshold and calls shrink_zones. shrink_zones API puts active pages (refcounted) back to freelist (after coalescing with buddies) if the pages are evictable (determined using page_unevictable API) or if decrementing the page->count once makes them free. Thus for tail pages, decrementing refcount in release_pages API would result in swaping these pages. This can lead to either bad page BUG when you free or can lead to corruption of memory by driver, who still owns handles to these pages.

To avoid this, __get_free_pages must be called with __GFP_COMP or must be split into individual pages and noPage handler call SetPageResevred and get_page both. Calling SetPageResevred and get_page both  guarantees that driver code would work for different kernel versions.


0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有