Linux内核内存管理,是否一直使用连续的内存页面?

问题描述:

Linux内核是否连续分配内存,例如从malloc开始?如果没有足够的可用部分,但可以整体使用的较小部分,Linux会使用吗?

Is linux kernel allocating memory consecutively, e.g from malloc ? If there's no big part available, but smaller part in pieces that works as a total, will Linux use that ?

我假设在问题中,连续"是指物理内存.

在执行过程时(例如,当您使用gdbaddr2line时)看到的所有地址都是虚拟地址.到物理内存的映射仍然存在.

All the addresses you see when a process executes, for example when you use gdb or addr2line, are virtual addresses. The mapping to physical memory stays under the hood.

malloc通常是不是系统调用.它是特定于平台的系统调用(例如mmapbrk)的包装.由流程调用时,它导致调用流程的内存得以扩展.

malloc is usually not a system call. It is a wrapper around a platform-specific system call (such as mmap or brk). When invoked by a process, it results in the memory of the invoking process to be extended.

例如,假设页面大小为4KB,malloc(40960)可以请求10页内存. 内存管理单元(MMU)不会立即在物理内存中分配10个页面.而是将新条目(在这种情况下为10)添加到调用过程的地址空间中,即,将新条目添加到该过程的页表中.该虚拟内存将是连续的.

For example, malloc(40960) could request 10 pages of memory, assuming 4KB page size. The Memory Management Unit (MMU) doesn't immediately allocate 10 pages in the physical memory. Instead, new entries (10 in this case) are added to the address space of the invoking process, that is, new entries are added in the page table of this process. This virtual memory will be contiguous.

现在假定在执行的后期,该进程尝试使用此新分配的内存.这时,由于该进程接触了未分配的内存,因此调用了页面错误.然后,MMU将在RAM中分配实际的物理页面(4096个连续字节),更新页面表并恢复该过程的执行.

Now assume that later during the execution, the process tries to use this newly allocated memory, At that moment, a page fault is invoked because the process touched unallocated memory. The MMU will then allocate an actual physical page (4096 continuous bytes) in RAM, update the page table and resume execution of the process.

因此,我们唯一可以确定的是,尽管整个40960字节(10页)在虚拟内存中看起来是连续的,但40960字节中的4096字节(一页)在物理内存(RAM)中是连续的.这10个页面中的任何一个或全部都可以映射到分散在RAM中的页面.

So the only thing we can be sure of is that 4096 bytes (one page) out of 40960 bytes are contiguous in physical memory (RAM), although the entire 40960 bytes (10 pages) appears as contiguous in the virtual memory. Any or all of the 10 pages may be mapped to pages that are scattered in RAM.

虚拟内存将其隐藏,并为进程提供一个干净,连续的空间. MMU使用页表通过将虚拟内存映射到物理内存来提供后端支持.

Virtual memory hides this and presents a clean, contiguous space to a process. The MMU uses the page table to provide a backend support by mapping virtual to physical memory.