您的位置:首页 > 运维架构 > Linux

Linux平台上几个常见内核内存分配函数

2013-11-12 16:59 423 查看
转自:http://linux.chinaitlab.com/c/802382.html

 * kmalloc

  Prototype:

  #include <linux/slab.h>

  void *kmalloc(size_t size, int flags);

  Kmalloc分配一段未清0的连续物理内存页,并返回虚存地址。有点是快,并且可指定flag,如DMA内存,高地址区域内存等。缺点是不能分配大于128KB(处于跨平台考虑),几个重要的flag:

  GFP_ATOMIC

  Used to allocate memory from interrupt handlers and other code outside of a process context. Never sleeps.

  GFP_KERNEL

  Normal allocation of kernel memory. May sleep.

  GFP_USER

  Used to allocate memory for user-space pages; it may sleep.

  GFP_HIGHUSER

  Like GFP_USER, but allocates from high memory, if any. High memory is described in the next subsection.

  * slab allocator(lookaside cache)

  从Memcached的实现知道有这么一个内存管理策略,其显着特点是分配一组相同大小的内存块作为内存池,其实现对应于源代码中的<linux/slab.h>和mm/slab.c。

  Prototype:

  #include <linux/malloc.h>

  kmem_cache_t *kmem_cache_create(char *name, size_t size, size_t offset,

  unsigned long flags, constructor( ), destructor( ));

  int kmem_cache_destroy(kmem_cache_t *cache);

  /proc/slabinfo

  A virtual file containing statistics on slab cache usage.

  *__get_free_pages

  Prototype:

  _ _get_free_pages(unsigned int flags, unsigned int order);

  返回2^order个未清0连续物理页面,flags与kmalloc中flags一致,允许的最大order值为10或者11(根据体系结构不同)

  *alloc_pages

  Prototype:

  struct page *alloc_pages_node(int nid, unsigned int flags,

  unsigned int order);

  Kernel中页分配器实现,__get_free_pages即调用alloc_pages实现的

  The real core of the Linux page allocator is a function called alloc_pages_node:

  *vmalloc

  分配地址连续虚存,而不保证物理地址连续,大部分情况下适合“软件”,而不是驱动程序。相对而言,kmalloc和__get_free_pages虚存map到物理内存只需要增减一个偏移,而使用vmalloc分配需要修改页表,故vmalloc的开销较大,分配少数几个页面的效率太低。

  *per-cpu variables

  Each cpu hold an independant copy in their respective processor's caches, so there is no lock required and improve better performance, implemented as a linux 2.6 feature. Defined in <linux/percpu.h>.

  DEFINE_PER_CPU(type, name);

  get_cpu_var(sockets_in_use)++;

  put_cpu_var(sockets_in_use);

3.几种分配函数的比较

分配原理

最大内存

其他

__get_free_pages

/alloc_pages

直接对页框进行操作

4MB

适用于分配较大量的连续物理内存

kmem_cache_alloc

基于slab机制实现

128KB

适合需要频繁申请释放相同大小内存块时使用

kmalloc

基于kmem_cache_alloc实现

128KB

最常见的分配方式,需要小于页框大小的内存时可以使用

vmalloc

建立非连续物理内存到虚拟地址的映射

 
物理不连续,适合需要大内存,但是对地址连续性没有要求的场合

dma_alloc_coherent

基于__alloc_pages实现

4MB

适用于DMA操 作

ioremap

实现已知物理地址到虚拟地址的映射

 
适用于物理地址已知的场合,如设备驱动

alloc_bootmem

在启动kernel时,预留一段内存,内核看不见

 
小于物理内存大小,内存管理要求较高

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: