Deep understanding of virtual memory in computer systems

Source: Internet
Author: User
Tags anonymous byte sizes data structures exception handling requires

The key abstraction that a process provides to an application:

a separate logical control flow that provides an illusion as if our program exclusively uses the processor . a private address space that provides an illusion as if our program exclusively uses the memory system.

Virtual Memory

Virtual memory is a perfect interaction between hardware exceptions, hardware address translation, main memory, disk files, and kernel software, which provides a large, consistent, and private address space for each process. With a very clear mechanism, virtual memory provides three important capabilities:

(1) It uses main memory as a cache of address space stored on disk, storing only the active area in main memory, and transmitting data back and forth between disk and main memory as needed, in this way, it is efficient in using main memory.

(2) It simplifies memory management by providing a consistent address space for each process .

(3) it protects the address space of each process from being destroyed by other processes .


physical and virtual addressing

Physical Addressing

The main memory of a computer system is organized into an array of cells consisting of m contiguous byte sizes. Each byte has a unique physical address (physical ADDRESS,PA). The address of the first byte is 0, the next byte has an address of 1, the next is 2, and so on. Given this simple structure, the most natural way for a CPU to access memory is to use physical addresses, which we call physical addressing.

Virtual Addressing

When using virtual addressing, the CPU accesses the main memory by generating a virtual Address,va address, which is converted to the appropriate physical address before being sent to the memory. The task of translating a virtual address into a physical address is called address translation (translation). Like exception handling, address translation requires close collaboration between the CPU hardware and the operating system. The dedicated hardware called the memory Management Unit,mmu on the CPU chip uses the query table stored in main memory to dynamically translate the virtual address, and the contents of the table are managed by the operating system.


address Space

The address space (adress space) is an ordered collection of non-integer addresses: {0,1,2,...}

If the integer in the address space is contiguous, then we say it is a linear address space (linear). In a system with virtual memory, the CPU generates a virtual address from an n = 2 ^ n address space called the virtual address space: {0,1,2,3,..., N-1}

The size of an address space is described by the number of times required to represent the maximum address. For example, a virtual address space that contains an n=2^n address is called an n-bit address space. Now the system typically supports 32-bit or 64-bit virtual address space.

A system also has a physical address space (physical addresss space) that corresponds to the M-byte of the physical memory in the system: {0,1,2,... M-1}

M does not require a power of 2, but in order to simplify the discussion, we assume that M = 2 ^ M.

The concept of address space is important because it clearly distinguishes between data Objects (bytes) and their properties (addresses). Once this distinction is realized, we can generalize it, allowing each data object to have multiple independent addresses, each of which is chosen from a different address space (discontinuous meaning). )。 This is the basic idea of virtual memory . Each byte in main memory has a virtual address selected from the virtual address space and a physical address selected from the Physical address space. (This paragraph does not understand how to read ~ ~)


virtual memory as a tool for caching

Conceptually, a virtual memory (VM) is organized into an array of cells that are stored in n contiguous byte sizes on a disk. Each byte has a unique virtual address, and this unique virtual address is used as an index to the array. The contents of the array on the disk are cached in main memory. As with other caches in the memory hierarchy, the data on the disk (lower layer) is segmented into blocks that act as transmission units between the disk and main memory (higher). The VM system handles this problem by dividing the virtual memory into blocks of fixed size called virtual pages (vitual PAGE,VP). The size of each virtual page is P = 2 ^ n bytes. Similarly, physical memory is split into physical pages (physical page,pp), and the size is also p-bytes (physical pages are also called page frames).

At any one time, the collection of virtual pages is divided into three disjoint subsets:

Unassigned : A page that the VM system has not yet assigned (or created). Unallocated blocks do not have any data associated with them, so they do not occupy any disk space. (No calls to malloc or mmap) Cached : The allocated pages in the physical store are currently being deferred. (already called malloc and Mmap, which is being referenced in the program) Not cached : the allocated pages in the physical memory are not being slowed. (already called malloc and mmap, not yet referenced in the program)


Page Table

As with any cache, a virtual storage system must have some way of determining whether a virtual page is stored somewhere in the DRAM. If so, the system must also determine which physical page the virtual page resides on. If not, the system must determine where the virtual page resides on the disk, select a sacrifice page in the physical memory, and copy the virtual page from disk to DRAM, replacing the sacrifice page.

These features are provided by a combination of hardware and software, including the operating system software, the address translation hardware in the MMU (Memory management unit), and a data structure in the physical memory called the page table, which maps the virtual page to the physical page. A page table is an array of page table entries (page tables entry,pte).





Linux virtual memory system

Linux maintains a separate virtual address space for each process .



Kernel virtual memory contains code and data structures in the kernel. Some areas of the kernel virtual storage are mapped to physical pages shared by all processes. For example, each process shares the kernel's code and global data Structures .


1. Linux Virtual memory area (also the concept of a region under Windows)

Linux organizes virtual storage into a collection of areas (also called segments). An area is a continuous slice (chunk) of existing (allocated) virtual memory that is associated in some way. For example, code snippets, data segments, heaps, shared library segments, and areas where the user stack is different. each virtual page that exists is saved in a zone, and a virtual page that is not part of a zone does not exist and cannot be referenced by the process. The concept of a zone is important because it allows for a gap in the virtual address space. The kernel does not have to log those virtual pages that do not exist, and such pages do not occupy memory. Any additional resources on the disk or the kernel itself .

The kernel maintains a separate task structure for each process in the system (task_struct in the source code). The elements in the task structure contain or point to all the information that the kernel needs to run the process (for example, a PID, a pointer to the user stack, the name of the executable target file, and the program counter).



An entry in task_struct points to Mm_struct, which describes the current state in the virtual storage. Where PGD points to the base address of the first-level page table (the page global catalog), and mmap points to a list of vm_area_struct (regional structures), where each vm_area_structs describes a region (area) of the current virtual address space. When the kernel runs this process, it stores the PGD in the CR3 control register.

A specific area structure contains the following fields:

Vm_start: Point to the beginning of the area. Vm_end: Point at the end of the area. Vm_prot: Describes the read and Write permission permissions for all pages contained within this area. Vm_flags: Describes whether pages in this area are shared with other processes, or whether the process is private (and some other information is also described). Vm_next: Points to the next area structure in the list.


memory Mapping (similar mechanism under Windows, called Memory mapping) Linux (and some other forms of Unix) associates a virtual memory area with an object on a disk to initialize the contents of this virtual memory area, a process known as memory mapping。 A virtual memory area can be mapped to one of two types of objects: (1)Common Files on Unix files: An area can be mapped to a contiguous portion of a regular disk file, such as an executable target file. The file Area (section) is divided into page-sized slices, each containing the initialization of a virtual page. Because the page height is on demand, these virtual pages do not actually carry physical memory until the first time the CPU refers to the page (that is, it launches a virtual address that falls within the scope of the address space page). If the zone file area is larger, then use zero to populate the rest of the area.
(2)Anonymous Files: An area can also be mapped to an anonymous file, the anonymous file is created by the kernel and contains all binary zeros. When the CPU first refers to a virtual page in such a region, the kernel finds a suitable sacrifice page in the physical memory, and if the page is modified, the page is swapped out, and the page table is overwritten with a binary zero overlay, which marks the page as residing in memory. Note there is no actual data transfer between the disk and the storage. For this reason, pages in areas that map to anonymous files are sometimes referred to as requests for binary zeros (Demand-zero page). In either case, once a virtual page is initialized, it is swapped between a dedicated swap file maintained by the kernel (swap files). Swap files are also called Swap spaces (swap space) or swap areas (swap area). An important point to be aware of,at any moment, the swap space limits the total number of virtual pages that the currently running process can allocate
look at the shared object againAn object can be mapped to a region of virtual storage, either as a shared object or as a private object. If a process maps a shared object to a region of its virtual address space, then any write to this zone by the process is also visible to other processes that also map the shared object to their virtual storage. Also, this change is reflected in the original object on disk. (One way of IPC) on the other hand, changes made to a zone mapped to a private object are not visible to other processes, and any writes that the process makes to the zone are not reflected in the objects on disk. A virtual storage area mapped to a shared object is called a shared zone. Similarly, there are private areas.

The key point of a shared object is that even if the object is mapped to multiple shared areas, the physical memory only needs to hold a copy of the shared object.

a Shared object (note that physical pages are not necessarily contiguous.) )



private objects are mapped to virtual memory using a clever technique called write-time copy (Copy-on-write). For each process that maps private objects, the page table entries for the corresponding private zone are marked as read-only, and the zone structure is marked as private write-time copies.



look at the fork function again

When the fork function is called by the current process, the kernel creates a variety of data structures for the new process and assigns it a unique PID. To create a virtual memory for this new process, it creates the mm_struct, the region structure, and the original copy of the page table for the current process. It marks every page in two processes as read-only and marks each of the two processes as private write-time copies.

When fork is returned in a new process, the new process now has the same virtual memory as the virtual memory that existed when the fork was called. When either of these processes later writes, the write-time copy mechanism creates a new page, thus preserving the abstract concept of private address space for each process.


look at the Execve function again .

Assume that a program running in the current process performs the following calls:

Execve ("A.out", null,null);

The EXECVE function loads and runs the program contained in the executable target file a.out in the current process, effectively replacing the current program with the A.out program. The following steps are required to load and run A.out:

Delete a user area that already exists。 Deletes the existing zone structure in the user portion of the current process virtual address.Mapping Private Areas。 Creates a new regional structure for the text, data, BSS, and stack areas of the new program. All of these new areas are private, copy-on-write. Text and data regions are mapped to text and data areas in the A.out file. A BSS region is a binary zero that is mapped to an anonymous file whose size is contained in the a.out. The stack and heap regions are also requesting binary zeros.Map Shared Areas。 If the A.out program is linked to a shared object (or target), such as the standard C library libc.so, then these objects are dynamically linked to the program and then mapped to a shared area in the user's virtual address space.Set Program counter (PC)。 The last thing Execve do is set up the program counter in the current process context to point to the entry point of the text area. The next time the process is dispatched, it will start executing from this entry point. Linux will swap in code and data pages as needed.


user-level memory mapping using the MMAP function [CPP]View plain copy #include <unistd.h> #include <sys/mman.h> void *mmap (void *start,size_t Length,int Pro                   T,int flags,int fd,off_t offset); Returns: A pointer to the map area if successful, map_failed (-1) If an error occurs
The MMAP function requires that the kernel create a new virtual memory area, preferably a region starting at address start, and map a contiguous slice (chunk) of the object specified by the file descriptor FD to the new region. The contiguous size of the object slice is the length byte, starting at the offset byte from the beginning of the file. The start address is only a hint and is usually defined as null.










[CPP]  View Plain copy munmap function Delete the area of the virtual storage:   #include <unistd.h>   #include <sys/mman.h >         int munmap (void *start,size_t length);       //return: 0 If successful, -1  </if error occurs

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.