Issue
My understanding is that kmalloc()
allocates from anonymous memory. Does this actually reserve the physical memory immediately or is that going to happen only when a write page fault happens?
Solution
kmalloc()
does not usually allocate memory pages(1), it's more complicated than that. kmalloc()
is used to request memory for small objects (smaller than the page size), and manages those requests using already existing memory pages, similarly to what libc's malloc()
does to manage the heap in userspace programs.
There are different allocators that can be used in the Linux kernel: SLAB, SLOB and SLUB. Those use different approaches for the same goal: managing allocation and deallocation of kernel memory for small objects at runtime. A call to kmalloc()
may use any of the three depending on which one was configured into the kernel.
A call to kmalloc()
does not usually reserve memory at all, but rather just manages already reserved memory. Therefore memory returned by kmalloc()
does not require a subsequent page fault like a page requested through mmap()
normally would.
Copy on Write (CoW) is a different concept. Although it's still triggered through page faults, CoW is a mechanism used by the kernel to save space sharing existing mappings until they are modified. It is not what happens when a fault is triggered on a newly allocated memory page. A great example of CoW is what happens when the fork
syscall is invoked: the process memory of the child process is not immediately duplicated, instead existing pages are marked as CoW, and the duplication only happens at the first attempt to write.
I believe this should clear any doubt you have. The short answer is that kmalloc()
does not usually "reserve the physical memory immediately" because it merely allocates an object from already reserved memory.
(1) Unless the request is very large, in which case it falls back to actually allocating new memory through alloc_pages()
.
Answered By - Marco Bonelli Answer Checked By - Timothy Miller (WPSolving Admin)