kmalloc
and vmalloc
are two memory allocation methods in the Linux kernel, they are both used to allocate memory for the kernel, but they have some important differences in how they use and manage memory. Below we discuss in detail the similarities and differences between these two memory allocation methods.
Same point:
- Both are memory allocation methods in kernel space.
- Both can be used to dynamically allocate memory, and the memory size can be specified at runtime.
- The allocated memory can only be used by the kernel and cannot be directly accessed by user space.
difference:
-
Continuity:
kmalloc
The allocated memory is physically contiguous, whilevmalloc
the allocated memory is only virtually contiguous. This means thatkmalloc
the allocated memory can be used for hardware devices that require physically contiguous memory, while thevmalloc
allocated memory is only suitable for scenarios that do not require physically contiguous memory. -
Allocation Size: Due to the
kmalloc
need to allocate physically contiguous memory, it may fail when allocating large chunks of memory (because no large enough contiguous physical memory region can be found). In contrast,vmalloc
larger memory blocks can be allocated because it uses virtual address space, as long as there is enough physical memory available. -
Allocation speed: Due to
kmalloc
the contiguous physical memory, the allocation speed is usually faster. However,vmalloc
when allocating memory, it is necessary to search for an available area in the virtual address space and establish a page table mapping, so the allocation speed is relatively slow. -
Memory management:
kmalloc
The allocated memory comes from the kernel's buddy system (Buddy System), which manages the physical memory page frame. The allocatedvmalloc
memory comes from the virtual address space, which uses page tables to map virtual addresses to physical memory. -
Memory release:
kmalloc
After the allocated memory is released, it can be reassigned to other requests immediately, and thevmalloc
allocated memory will not be reclaimed immediately after the physical memory is released, but will remain in the virtual address space until the next allocation.
To sum up, kmalloc
it is more suitable for scenarios that require physically contiguous memory and high allocation speed requirements, and vmalloc
is more suitable for scenarios that require large memory blocks and do not require high physical contiguity. Choosing an appropriate memory allocation method according to actual needs is an important consideration in kernel programming.
[The last bug] There are updates and releases on multiple platforms. You can connect three times with one click, follow + star, and don't miss exciting content~