Heap memory allocation in Linux
I’m confused about whether the memory allocated by Linux when a process requests ‘x’ amount of heap is actually contiguous physically or not?
Here’s my understanding till now:
The unit of memory allocation in Linux is page size. By default, page size = 4KB. The page is physically contiguous in RAM.
As seen from the output of /proc/buddyinfo, the total memory is divided into several groups
group 0, group 1, … group 10
Each group ‘n’ contains multiple physically contiguous pages of memory, each of size 4KB * (2^n)
so group 0 contains pages of size 4KB,
group 1 contains pages of size 8KB,
group 2 contains pages of size 16KB etc.
now if suppose an application requests 12 KB of memory and suppose from group 2 onwards there is no free page available.
I want to know
-
whether memory allocation request will be successful in this case by using 1 page each from group 0 and group 1? or will it fail?
-
Are the pages in a particular group ‘n’ contiguous in physical memory or not? e.g. if group 2 has suppose 5 free pages, then are all these 5 pages physically contiguous(5 * 4 * 4=80KB of contiguous block in RAM)?
actually contiguous physically or not?
not. that was an easy one! The mapping between physical pages and process memory is pretty much arbitrary.
whether memory allocation request will be successful in this case by using 1 page each from group 0 and group 1? or will it fail?
generally, it would work (12 kB is really very little. If your system doesn’t have that many (3) contiguous pages, you have a serious problem). That’s the magic of an MMU: you can reorder the physical pages in any way you want. You still would try to keep these mappings as "straight" as possible to keep the necessary tables compact, and finding of free memory fast, but it does not fail if there’s not enough contiguous memory, but overall enough unused pages.
Are the pages in a particular group ‘n’ contiguous in physical memory or not? e.g. if group 2 has suppose 5 free pages, then are all these 5 pages physically contiguous(5 * 4 * 4=80KB of contiguous block in RAM)?
not. Especially not when you think about how your system might have another layer of nested page tables, e.g. through virtualization between physical memory and your operating system.