Tuesday 8 April 2014

[Kernel Programming] Allocation of memory in Kernel

Allocation of memory in Kernel


kmalloc()kzalloc()kcalloc()vmalloc()
Allocates contiguous physical blocks of memory in byte-sized chunksAllocates contiguous physical blocks of memoryAllocates memory for an arraysame as kmalloc, except it allocates memory that is only virtually contiguous
Memory is not set to zeroMemory is set to zeroMemory is set to zerounderling physical memory can be discontiguous
void * kmalloc (size_t size, int flags)void * kzalloc (size_t size, int flags)void * kcalloc  (size_t n, size_t size, unsigned int __nocast flags);void * vmalloc (unsigned long size)
Depends on the flag used, it may sleepDepends on the flag used, it may sleepDepends on the flag used, it may sleepCan sleep, so don’t use it in interrupt context
Can allocate upto 4MBytesSame as kmallocNeed to check ?Can obtain very large regions of memory
Simple and fastSimple, preferable and fastSimple and fastSlow compare to kmalloc


Vmalloc(): Slower and not advisable if memory requirement is less. Because,
  1. Makes non-contiguous physical memory to continuous virtual memory
  2. Setting up the page table entries
  3. Pages obtained from vmalloc() must be mapped to their individual pages since physical memory is not contiguous
  4. Results in much greater TLB, performance is affected.

Note: malloc() function also works in same manner. i.e. allocated memory in continuous in virtual address space of the processor, but there is no guarantee that they are contiguous in the physical address space (physical RAM)

Flag: controls the behavior of memory allocation and divided into 3 groups
–Action modifiers: How to allocate memory. Ex: can sleep or not
–Zone modifiers: Where the request should be satisfied. (ex: DMA buffers)
–Types: types of allocation


FLAG TypeAction ModifierZone Modifier
GFP_KERNEL(__GFP_WAIT | __GFP_IO | __GFP_FS) -NA-
GFP_ATOMIC__GFP_HIGH -NA-
GFP_DMA__GFP_DMA


GFP_ATOMIC:  Allocation is High priority and does not sleep. This flag will  be used in Interrupt handlers, bottom halves where kernel should not sleep
GFP_KERNEL: Allocation will be Normal priority and can be used in process context, and safe to sleep

Action Modifiers and Zone Modifiers:

__GFP_HIGH: The kernel can access emergency pools.
__GFP_WAIT: The kernel can sleep
__GFP_IO: The kernel can start disk I/O
__GFP_FS: The kernel can start filesystem I/O
__GFP_DMA: Allocate only DMA-capable memory

References:
Third Edition of Linux Device Drivers, by Jonathan Corbet

No comments:

Post a Comment

You might also like

Related Posts Plugin for WordPress, Blogger...