Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is different functions: `malloc()` and `kmalloc()`?

What is different functions: malloc() and kmalloc()? They differ only in that:

  • the malloc() can be called in user-space and kernel-space, and it allocates a physically fragmented memory area
  • but kmalloc() can be called only in kernel-space, and it allocates physically contiguous memory chunk

or something else?

kmalloc() use pointer in virtual or physical addressing and what kmalloc() is different from __ get_free_pages()?

like image 928
Alex Avatar asked Nov 19 '13 18:11

Alex


2 Answers

  • malloc uses Buddy algorithm for allocation of chunks.
  • The kmalloc kernel service, which allocates physically contiguous memory regions in the kernel address space, is in built on top of the slab and object cache interface which uses slab allocator algorithm.

More details here

like image 84
Amit Singh Avatar answered Oct 01 '22 20:10

Amit Singh


I answer to the second question, assuming that you are using Linux OS. Regarding to the first one please have a look to my comment.

kmallocuses get_free_page to get the memory. The way in which the pages are collected depends on the second parameter ( GFP_ATOMIC GFP_KERNEL ... in which GFP means GET FREE PAGE). The advantage of kmalloc on the GFP is that it can fit multiple allocations into a single page.

some of the options for kmalloc are:

GFP_USER - Allocate memory on behalf of user. May sleep.
GFP_KERNEL - Allocate normal kernel ram. May sleep.
GFP_ATOMIC - Allocation will not sleep. May use emergency pools. For example, use this inside interrupt handlers.
GFP_HIGHUSER - Allocate pages from high memory.
GFP_NOIO - Do not do any I/O at all while trying to get memory.
GFP_NOFS - Do not make any fs calls while trying to get memory.
GFP_NOWAIT - Allocation will not sleep.
GFP_THISNODE - Allocate node-local memory only.
GFP_DMA - Allocation suitable for DMA. Should only be used for kmalloc caches. Otherwise, use a slab created with SLAB_DMA.

Apart from this get_free_page and kmalloc are very similar. _get_free_pages differs from get_free_page because it gives the pointer to the first byte of a memory area that is potentially several (physically contiguous) pages long. Another function that is again very similar to get_free_page is get_zeroed_page(unsigned int flags) which gets a single page like get_free_page but zeroes the memory

like image 39
Jekyll Avatar answered Oct 01 '22 20:10

Jekyll