kmalloc and vmalloc in the linux kernel

insert image description here

kmallocand vmallocare 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:

  1. Both are memory allocation methods in kernel space.
  2. Both can be used to dynamically allocate memory, and the memory size can be specified at runtime.
  3. The allocated memory can only be used by the kernel and cannot be directly accessed by user space.

difference:

  1. Continuity: kmalloc The allocated memory is physically contiguous, while vmallocthe allocated memory is only virtually contiguous. This means that kmallocthe allocated memory can be used for hardware devices that require physically contiguous memory, while the vmallocallocated memory is only suitable for scenarios that do not require physically contiguous memory.

  2. Allocation Size: Due to the kmallocneed 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, vmalloclarger memory blocks can be allocated because it uses virtual address space, as long as there is enough physical memory available.

  3. Allocation speed: Due to kmallocthe contiguous physical memory, the allocation speed is usually faster. However, vmallocwhen 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.

  4. Memory management: kmalloc The allocated memory comes from the kernel's buddy system (Buddy System), which manages the physical memory page frame. The allocated vmallocmemory comes from the virtual address space, which uses page tables to map virtual addresses to physical memory.

  5. Memory release: kmalloc After the allocated memory is released, it can be reassigned to other requests immediately, and the vmallocallocated 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, kmallocit is more suitable for scenarios that require physically contiguous memory and high allocation speed requirements, and vmallocis 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~
insert image description here

Guess you like

Origin blog.csdn.net/qq_33471732/article/details/131669824