Let me explain what a virtual address is. The Linux kernel provides a separate, contiguous virtual address space for each process. The interior of the virtual address space is divided into kernel space and user space. Processors with different word lengths (that is, the maximum length of data that can be processed by a single CPU instruction) have different ranges of address Spaces.

The kernel space of all processes is associated with the same physical memory. A process can access kernel space memory only after it switches to kernel state. The segmentation we are talking about is for user space only.

There are two ways to manage the relationship between virtual addresses and physical addresses. 1, Segment management: find physical addresses by Segment selectors and offsets within segments.

User space is divided into five different memory segments from low address to high address.

Code segments (read-only segments), including code and constants, etc.

Data segments, including global variables, etc.

The heap, including dynamically allocated memory, starts at a low address and grows upwards.

File mapping segments, including dynamic libraries, shared memory, and so on, grow downward from high addresses. (This picture is not drawn)

Stack, including local variables, function call context, etc. The stack size is fixed, usually 8 MB.

Fragmentation is easy to occur, and memory swap efficiency is low (not easy to swap out to disk). In order to solve these two problems, memory paging occurs.

2. Paging: A virtual address consists of a page number and an in-page offset.

The MMU specifies a minimum unit of memory mapping, which is a page, usually 4 KB in size. In order to solve the problem of too many page table entries, there are two ways: multi-level page table and large page.

Not all virtual memory for a process is allocated physical memory, only the virtual memory that is actually used is allocated physical memory. This is called the locality principle of programs. According to this principle, to improve access speed, MMU (Memory Manage Unit) has a hardware: Translation Lookaside Buffer (TLB). Used to cache common page tables for processes.

Memory segmentation and paging are not opposites; they are used in combination, often referred to as segment-page memory management.

The address used by the program is called the logical address;

Addresses mapped by segmental memory management are called virtual addresses (linear addresses).

Map linear addresses to physical addresses through paged memory management.