What are the different functions: `malloc ()` and `kmalloc ()`?

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

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

or something else?

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

+6
source share
1 answer

I answer the second question, assuming you are using Linux. Regarding the first, please take a look at my comment.

kmalloc uses get_free_page to get memory. The method of collecting pages depends on the second parameter ( GFP_ATOMIC GFP_KERNEL ... , in which GFP means GET FREE PAGE). The advantage of kmalloc in GFP is that it can accommodate multiple distributions on one page.

Some options for kmalloc:

 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. 

In addition, get_free_page and kmalloc very similar. _get_free_pages is different from get_free_page because it gives a pointer to the first byte of a memory area, which is potentially several (physically adjacent) pages long. Another function, which again is very similar to get_free_page , is get_zeroed_page(unsigned int flags) , which receives one page, for example get_free_page , but get_free_page memory

+3
source

Source: https://habr.com/ru/post/958420/


All Articles