Allocation of memory in Kernel
kmalloc() | kzalloc() | kcalloc() | vmalloc() |
---|---|---|---|
Allocates contiguous physical blocks of memory in byte-sized chunks | Allocates contiguous physical blocks of memory | Allocates memory for an array | same as kmalloc, except it allocates memory that is only virtually contiguous |
Memory is not set to zero | Memory is set to zero | Memory is set to zero | underling 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 sleep | Depends on the flag used, it may sleep | Depends on the flag used, it may sleep | Can sleep, so don’t use it in interrupt context |
Can allocate upto 4MBytes | Same as kmalloc | Need to check ? | Can obtain very large regions of memory |
Simple and fast | Simple, preferable and fast | Simple and fast | Slow compare to kmalloc |
Vmalloc():
Slower and not advisable if memory requirement is less. Because,
- Makes non-contiguous physical memory to continuous virtual memory
- Setting up the page table entries
- Pages obtained from vmalloc() must be mapped to their individual pages since physical memory is not contiguous
- 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 Type | Action Modifier | Zone 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