Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc in kernel

When I try to use malloc in a kernel module I get an error message from the compiler. My code:

res=(ListNode*)malloc(sizeof(ListNode));

The compilers error message is:

/root/ex3/ex3mod.c:491: error: implicit declaration of function ‘malloc’

What should I do?

like image 821
yoavstr Avatar asked May 22 '10 14:05

yoavstr


People also ask

Why can't we use malloc in kernel code?

This means that ANY function you're calling in the kernel needs to be defined in the kernel. Linux does not define a malloc, hence you can't use it. There is a memory allocator and a family of memory allocation functions.

What does malloc do in Linux?

The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

What is kernel memory allocation?

The kernel should allocate memory dynamically to other kernel subsystems and to user processes. The KMA (kernel memory allocation) API usually consists of two functions: void* malloc(size_t nbytes); void free(void* ptr); There are various issues associated with allocation of memory.

Where is malloc defined in Linux?

In computing, malloc is a subroutine for performing dynamic memory allocation. malloc is part of the standard library and is declared in the stdlib. h header.


1 Answers

Note about the difference between the two allocation methods - kmalloc and kmem_cache, or vmalloc:

kmalloc: Best used for fast allocations that are smaller than a page (PAGE_SIZE, 0x1000 on most architectures). It doesn't involve mapping memory, so you get the memory straight from the kernel's 1:1 physical memory mapping. You get physically contingent memory. Note that if you you want to allocate more than one page (i.e. order > 0), you risk bumping into external fragmentation issues - i.e. the call might fail even if there is enough free. Higher order - higher chance for allocation failure, and up-time plays a factor here too.

If you want to achieve maximal allocation efficiency then using your own kmem_cache for each type of struct is the way to go (the other benefits for this strategy are being able to monitor the state of your allocations from /proc and catching memory leaks more easily).

vmalloc: Allocations of more than one page. You get mapped-memory in kernel space. Behind the scenes it is similar to what userspace gets - the kernel allocates a bunch of pages and maps them in a virtual address space. This allocation is slower than kmalloc's, and memory accesses might incur a bit more overhead.

like image 151
Dan Aloni Avatar answered Oct 15 '22 11:10

Dan Aloni