Home  >  Article  >  System Tutorial  >  Linux virtual memory, do you understand it well?

Linux virtual memory, do you understand it well?

WBOY
WBOYforward
2024-02-05 12:42:14971browse

Preface

Recently, there is a sharing topic in the group that I am very looking forward to: "Linux Virtual Memory". One night when we were working overtime, we were discussing the concept of virtual memory. Our leader found that several colleagues did not understand virtual memory clearly enough, so he specially selected this topic for this colleague (laughs).

Before, I had some understanding of the concept of operating systems, but after graduation, I felt a little regretful about the waste of my four-year computer major in college. Therefore, after work, I took time to watch Harbin Institute of Technology's open operating system class on NetEase Cloud Classroom, and also read a book "Linux Kernel Design and Implementation" that explains the basic concepts of operating systems. In addition, last year I wrote a simple server using C language and learned more about the underlying system. This knowledge gave me a better grasp of the application layer and helped me a lot during a recent troubleshooting.

A few days ago, another colleague asked me another question related to virtual memory. I realized that my understanding of virtual memory was not deep enough, and some concepts were even contradictory. Therefore, I went through some information and reorganized this knowledge, hoping to be more fluent in practical application next time.

origin


Virtual Memory

There is no doubt that virtual memory is definitely one of the most important concepts in the operating system. I think it's mainly because of the importance of memory in the entire system. The CPU is very fast, but has limited capacity and a single function. Other I/O hardware supports various fancy functions, but they are slower than the CPU. Therefore, they need a lubricant to act as a buffer between them, and this is where memory comes into play.

In modern operating systems, multitasking has become standard. Multi-tasking parallelism greatly improves CPU utilization, but it also brings about conflicts in memory operations between multiple processes. The concept of virtual memory is to solve this problem.

Linux virtual memory, do you understand it well?

The above picture is the simplest and most intuitive explanation of virtual memory.

The operating system has a piece of physical memory (the middle part) and two processes (actually more) P1 and P2. The operating system secretly tells P1 and P2 respectively that my entire memory is yours, use it as you like. , enough care. But in fact, the operating system just gave them a big pie. These memories were said to be given to P1 and P2, but in fact they were only given a serial number. Only when P1 and P2 actually start to use these memories, the system starts to move around and piece together the various blocks for the process. P2 thinks that it is using A memory, but in fact it has been quietly redirected to the real B by the system. Even when P1 and P2 share C memory, they don't know.

This method of deceiving the process of the operating system is virtual memory. For processes such as P1 and P2, they all think that they occupy the entire memory, and they do not know and do not need to care which address of the physical memory they use.

Paging and page tables

Virtual memory is a concept in the operating system. To the operating system, virtual memory is a comparison table. When P1 obtains the data in A memory, it should go to the A address of the physical memory and look for it in the B memory. The data should go to the C address of physical memory.

We know that the basic unit in the system is Byte. If each Byte of virtual memory is mapped to the address of physical memory, each entry requires at least 8 bytes (32-bit virtual address -> 32-bit physical address), in the case of 4G memory, 32GB of space is needed to store the comparison table, so this table is too big to fit even the real physical address, so the operating system introduces Pagethe concept of.

When the system starts, the operating system divides the entire physical memory into pages in units of 4K. When memory is allocated in the future, the unit is page, so the mapping table of virtual memory pages corresponding to physical memory pages is greatly reduced. 4G memory only requires an 8M mapping table. Some processes do not use virtual memory. There is no need to save the mapping relationship, and Linux also designs a multi-level page table for large memory, which can advance a page to reduce memory consumption. The mapping table between operating system virtual memory and physical memory is called page table.

Memory addressing and allocation

We know that through the virtual memory mechanism, each process thinks that it occupies all the memory. When the process accesses the memory, the operating system will convert the virtual memory address provided by the process into a physical address, and then obtain the data at the corresponding physical address. . There is a kind of hardware in the CPU, Memory Management Unit MMU (Memory Management Unit) is specially used to translate virtual memory addresses. The CPU also sets a cache strategy for page table addressing. Due to the locality of the program, its cache hit rate can reach 98%.

The above situation is the mapping of virtual address to physical address in the page table memory. If the physical address accessed by the process has not been allocated, the system will generate a Page Missing Interrupt. During interrupt processing, The system switches to kernel mode and allocates a physical address to the process virtual address.

Function


Virtual memory not only solves the problem of memory access conflicts between multiple processes through memory address translation, but also brings more benefits.

Process Memory Management

It helps the process to manage memory, mainly reflected in:

  • Memory integrity: Due to the "deception" of virtual memory on the process, each process thinks that the memory it obtains is a continuous address. When we write an application, we don't need to consider the allocation of large blocks of address. We always think that the system has enough large blocks of memory.
  • Security: Since when a process accesses memory, it must be addressed through the page table. The operating system can implement memory permission control by adding various access permission flags to each item in the page table.

data sharing

It is easier to share memory and data through virtual memory.

When a process loads a system library, it always allocates a piece of memory first and loads the library file on the disk into this memory. When using physical memory directly, because the physical memory address is unique, even if the system finds that the same library is in It is loaded twice in the system, but the loading memory specified by each process is different, and the system is unable to do anything.

When using virtual memory, the system only needs to point the virtual memory address of the process to the physical memory address where the library file is located. As shown in the figure above, the B addresses of processes P1 and P2 both point to physical address C.

It is also very simple to use shared memory by using virtual memory. The system only needs to point the virtual memory address of each process to the shared memory address allocated by the system.

SWAP

Virtual memory allows the process to "expand" memory.

We mentioned earlier that virtual memory allocates physical memory to the process through page fault interrupts. Memory is always limited. What if all physical memory is occupied?

Linux proposes the concept of SWAP. SWAP partitions can be used in Linux. When physical memory is allocated but the available memory is insufficient, the temporarily unused memory data will be placed on the disk first, allowing processes in need to use it first, and then wait for the process to use it again. When the data needs to be used, the data is loaded into the memory. Through this "swapping" technology, Linux can allow the process to use more memory.

common problem


I also had a lot of questions when understanding virtual memory.

32-bit and 64-bit

The most common problem is 32-bit and 64-bit.

CPU accesses memory through the physical bus, so the range of access addresses is limited by the number of machine buses. On a 32-bit machine, there are 32 buses. Each bus has two potentials, high and low, representing bits 1 and 0 respectively. , then the maximum accessible address is 2^32bit = 4GB, so it is invalid to insert memory larger than 4G on a 32-bit machine, and the CPU cannot access memory larger than 4G.

But 64-bit machines do not have a 64-bit bus, and their maximum memory is limited by the operating system. Linux currently supports a maximum of 256G memory.

According to the concept of virtual memory, it is okay to run 64-bit software on a 32-bit system. However, due to the system's structural design of virtual memory addresses, 64-bit virtual addresses cannot be used in 32-bit systems.

Directly operate physical memory

The operating system uses virtual memory. What should we do if we want to directly operate the memory?

Linux will map each device to a file in the /dev/ directory. We can directly operate the hardware through these device files, and memory is no exception. In Linux, the memory settings are mapped to /dev/mem, and the root user can directly operate the memory by reading and writing this file.

The JVM process occupies too much virtual memory

When using TOP to view system performance, we will find that in the VIRT column, the Java process will occupy a large amount of virtual memory.

Linux virtual memory, do you understand it well?

The reason for this problem is that Java uses Glibc's Arena memory pool to allocate a large amount of virtual memory and not use it. In addition, files read by Java will also be mapped into virtual memory. Under the default configuration of the virtual machine, each Java thread stack will occupy 1M of virtual memory. For details, you can check why multi-threaded programs under Linux consume so much virtual memory.

The actual physical memory occupied depends on the RES (resident) column. The value of this column is the size that is actually mapped to the physical memory.

Common management commands


We can also manage Linux virtual memory ourselves.

View system memory status

There are many ways to check the system memory status. free, vmstat and other commands can output the memory status of the current system. It should be noted that the available memory is not just the free column. Due to the lazy characteristics of the operating system, a large number of buffers/cache will not be cleared immediately after the process is no longer used. If the process that previously used them can continue to be used again, they can also be used when necessary.

In addition, through cat /proc/meminfo you can view the details of system memory usage, including dirty page status, etc. Details can be found at: /PROC/MEMINFO Mystery.

pmap

If you want to view the virtual memory distribution of a process individually, you can use the pmap pid command, which will list the occupancy of each virtual memory segment from low address to high address.

You can add -XX parameters to output more detailed information.

Modify memory configuration

We can also modify the Linux system configuration, use sysctl vm [-options] CONFIG or directly read and write files in the /proc/sys/vm/ directory to view and Change setting.

SWAP Operation

The SWAP feature of virtual memory is not always beneficial. Allowing the process to continuously exchange large amounts of data between memory and disk will greatly occupy the CPU and reduce system operating efficiency, so sometimes we do not want to use swap.

We can modify vm.swappiness=0 to set the memory to use swap as little as possible, or simply use the swapoff command to disable SWAP.

summary


The concept of virtual memory is very easy to understand, but it will derive a series of very complex knowledge. This article only talks about some basic principles and skips many details, such as the use of mid-segment registers in virtual memory addressing, the operating system's use of virtual memory to enhance cache and buffer applications, etc. If there is an opportunity, I will talk about it separately.

The above is the detailed content of Linux virtual memory, do you understand it well?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:lxlinux.net. If there is any infringement, please contact admin@php.cn delete