歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux服務器 >> Linux平台上幾個常見內核內存分配函數

Linux平台上幾個常見內核內存分配函數

日期:2017/3/2 16:34:48   编辑:Linux服務器

* 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);

Copyright © Linux教程網 All Rights Reserved