EmbLogic's Blog

Difference between Kmalloc() and Vmalloc()

In order to allocate memory from kernel various types of API(application programming interfaces) are used.Two such API’s are Kmalloc() and Vmalloc().

SYNTAX:

void * kmalloc(size_t size , int flags);

void * vmalloc(unsigned long size);

Kmalloc() is use to allocate memory requested from the kernel.The memory allocated is returned by the API and it is physically as well virtually contiguous.Generally we need this physically contiguous memory when we have to implement some driver which will be used to interface some hardware or device.In kmalloc we can define the size,how much memory is needed and also we can give flags as GFP_ATOMIC and GFP_KERNEL.GFP_ATOMIC means get free pages from kernel in atomic fashion means the allocation will never sleep in between and the priority is also highest.This is generally used in interrupt handlers,and in those situation where sleep is not permitted as in the case with spinlocks.Another flag is GFP_KERNEL means get free pages from kernel,here sleep is allowed and it is normal allocation.The major disadvantage of kmalloc is that in certain cases when not enough physical memory is present,the API will return error usually NULL is returned and wastage of memory is there.There are other flags also GFP_WAIT,GFP_MASK depending on various features and requirements.The defintion of kmalloc is usually found in <slab.h> header file.

Vmalloc() is used to allocate memory from the kernel.The memory allocated is virtually contiguous but not physically contiguous.This API works in the similar manner as the user level malloc() works.It means vmalloc ensures memory is allocated from vitual address space.In vmalloc there is no option to define flag.We can give the amount of size we required in the argument.The user will not be able to distinguish the difference in memory allocated by vmalloc and kmalloc since it will be virtually contiguous but in real manner at the backend that memory will be in chunks /blocks.Every page table of the block will be having details of the another page table linked to it.If not enough memory is available then NULL will be returned.we can find vmalloc in header file<vmalloc.h>.The major advantage of vmalloc is that if enough physical contiguous memory is not available then it will allocate memory virtually in chunks and will link that memory so it appears to be virtually contiguous.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>