search
HomeSystem TutorialLINUXLinux kernel memory recycling mechanism: in-depth understanding of memory management

Linux kernel memory recycling mechanism: in-depth understanding of memory management

Feb 14, 2024 pm 07:51 PM
linuxlinux tutoriallinux systemlinux commandshell scriptarrangementembeddedlinuxGetting started with linuxlinux learning

Have you ever encountered various memory problems in Linux systems? Such as memory leaks, memory fragmentation, etc. These problems can be solved by in-depth understanding of the Linux kernel memory recycling mechanism.

No matter how much memory there is on the computer, it is not enough, so the Linux kernel needs to reclaim some rarely used memory pages to ensure that the system continues to use memory. There are three methods of page recycling: page writeback, page exchange and page discarding: If the backing storage of a rarely used page is a block device (such as a file mapping), the memory can be directly synchronized to the block device to free up the page. The page can be reused; if the page has no backing storage, it can be swapped to a specific swap partition, and then swapped back to the memory when it is accessed again; if the page's backing storage is a file, but the file content cannot be modified in the memory (such as executable file), it can be discarded directly if it is not currently needed.

1 Time to recycle

Linux kernel内存回收机制:深入理解内存管理

2 Which memory can be recycled

2.1 Recycling of page frames
LRU (Least Recently Used), the least recently used linked list, is arranged according to recent usage. The least used one exists at the end of the linked list, which can be seen through the following macro definition:
#define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
Each zone has 5 LRU linked lists to store various recently used pages.
enum lru_list {
LRU_INACTIVE_ANON = LRU_BASE,
LRU_ACTIVE_ANON = LRU_BASE LRU_ACTIVE,
LRU_INACTIVE_FILE = LRU_BASE LRU_FILE,
LRU_ACTIVE_FILE = LRU_BASE LRU_FILE LRU_ACTIVE,
LRU_UNEVICTABLE,
NR_LRU_LISTS
};
Among them, the pages in the four linked lists of INACTIVE_ANON, ACTIVE_ANON, INACTIVE_FILE, and ACTIVE_FILE can be recycled. ANON represents anonymous mapping, no backing storage; FILE represents file mapping.
When recycling pages, INACTIVE pages will be recycled first. Only when there are very few INACTIVE pages, ACTIVE pages will be considered for recycling.
In order to evaluate the activity of the page, the kernel introduces two flags, PG_referend and PG_active. Why do we need two bits? Assume that only one PG_active is used to identify whether the page is active. This bit is set when the page is accessed, but when is it clear? Doing this requires maintaining a large number of kernel timers, and this approach is doomed to failure.
A more elegant approach can be implemented using two flags. The core idea is: one indicating the current level of activity and one indicating whether it has been referenced recently. The following figure illustrates the basic algorithm.
Linux kernel内存回收机制:深入理解内存管理

Basically there are the following steps:
(1) If the page is active, set the PG_active bit and save it in the ACTIVE LRU list; otherwise, in INACTIVE;
(2) Each time the page is accessed, the PG_referenced bit is set. The mark_page_accessed function is responsible for this work;
(3) PG_referenced and the information provided by the reverse mapping are used to determine the degree of page activity. Each time this bit is cleared, the degree of page activity is detected. The page_referenced function implements this behavior;
(4) Enter mark_page_accessed again. If it is found that PG_referenced has been set, it means that page_referenced is not checked, so mark_page_accessed is called more frequently than page_referenced, which means that the page is frequently accessed. If the page is in the INACTIVE linked list, move it to ACTIVE. In addition, the PG_active flag will be set and PG_referenced will be cleared;
(5) Reverse transfer is also possible. When page activity decreases, page_referenced may be called twice in succession without mark_page_accessed in between.
If access to a memory page is stable, then calls to page_referenced and mark_page_accessed are balanced in nature, and the page remains in the current LRU list. This solution also ensures that memory pages will not jump quickly between ACTIVE and INACTIVE linked lists.
2.2 slab**** cache recycling
Slab cache recycling is relatively flexible, and all methods registered in shrinker_list will be executed.
The kernel registers the prune_super method for each file system by default. This function is used to recycle the dentry and inode cache that are no longer used in the file system;
Android's lowmemorykiller mechanism registers a method to selectively kill processes and reclaim the memory used by the process.
3****How ​​to recycle page frames
Linux kernel内存回收机制:深入理解内存管理

shrink_page_list is the process of actually recycling pages
Linux kernel内存回收机制:深入理解内存管理

4 Frequency of periodic recycling

4.1 kswapd
kswapd is a memory recycling thread created by the kernel for each memory node. Why does it need periodic recycling when there is a shortage recycling mechanism? Because some memory allocations are not allowed to block waiting for recovery, such as memory allocations in interrupt and exception handlers; some memory allocations are not allowed to activate I/O access. Only a few cases of memory shortage can completely execute the recycling process, so it is very necessary to use the system's idle time to reclaim memory.
This function records the allocation order used in the last balancing operation. If kswapd_max_order is greater than the last value, or classzone_idx is less than the last value, balance_pgdat is called to balance the memory domain again. Otherwise, a short sleep can be performed. The sleep time is HZ /10, for arm (HZ=100), the sleep time is 1ms.
balance_pgdat balances the operation until zone_wartermark_ok of the memory domain.
4.2 cache_reap
cache_reap is used to recycle idle objects in the slab. If the idle objects can be restored to a page, they are released back to the buddy system. Each time cache_reap is called, all slab_caches will be traversed and then sleep for 2*HZ. For arm (HZ=100), the cycle is 20ms.

In short, the Linux kernel memory recycling mechanism is a very important concept that can help you better understand memory management in Linux systems. If you want to know more about this concept, you can check out the resources provided in this article.

5 References

(1)《understanding the linux kernel》
(2)《professional linux kernel architecture》

The above is the detailed content of Linux kernel memory recycling mechanism: in-depth understanding of memory management. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:良许Linux教程网. If there is any infringement, please contact admin@php.cn delete
How does hardware compatibility differ between Linux and Windows?How does hardware compatibility differ between Linux and Windows?Apr 23, 2025 am 12:15 AM

Linux and Windows differ in hardware compatibility: Windows has extensive driver support, and Linux depends on the community and vendors. To solve Linux compatibility problems, you can manually compile drivers, such as cloning RTL8188EU driver repository, compiling and installing; Windows users need to manage drivers to optimize performance.

What are the differences in virtualization support between Linux and Windows?What are the differences in virtualization support between Linux and Windows?Apr 22, 2025 pm 06:09 PM

The main differences between Linux and Windows in virtualization support are: 1) Linux provides KVM and Xen, with outstanding performance and flexibility, suitable for high customization environments; 2) Windows supports virtualization through Hyper-V, with a friendly interface, and is closely integrated with the Microsoft ecosystem, suitable for enterprises that rely on Microsoft software.

What are the main tasks of a Linux system administrator?What are the main tasks of a Linux system administrator?Apr 19, 2025 am 12:23 AM

The main tasks of Linux system administrators include system monitoring and performance tuning, user management, software package management, security management and backup, troubleshooting and resolution, performance optimization and best practices. 1. Use top, htop and other tools to monitor system performance and tune it. 2. Manage user accounts and permissions through useradd commands and other commands. 3. Use apt and yum to manage software packages to ensure system updates and security. 4. Configure a firewall, monitor logs, and perform data backup to ensure system security. 5. Troubleshoot and resolve through log analysis and tool use. 6. Optimize kernel parameters and application configuration, and follow best practices to improve system performance and stability.

Is it hard to learn Linux?Is it hard to learn Linux?Apr 18, 2025 am 12:23 AM

Learning Linux is not difficult. 1.Linux is an open source operating system based on Unix and is widely used in servers, embedded systems and personal computers. 2. Understanding file system and permission management is the key. The file system is hierarchical, and permissions include reading, writing and execution. 3. Package management systems such as apt and dnf make software management convenient. 4. Process management is implemented through ps and top commands. 5. Start learning from basic commands such as mkdir, cd, touch and nano, and then try advanced usage such as shell scripts and text processing. 6. Common errors such as permission problems can be solved through sudo and chmod. 7. Performance optimization suggestions include using htop to monitor resources, cleaning unnecessary files, and using sy

What is the salary of Linux administrator?What is the salary of Linux administrator?Apr 17, 2025 am 12:24 AM

The average annual salary of Linux administrators is $75,000 to $95,000 in the United States and €40,000 to €60,000 in Europe. To increase salary, you can: 1. Continuously learn new technologies, such as cloud computing and container technology; 2. Accumulate project experience and establish Portfolio; 3. Establish a professional network and expand your network.

What is the main purpose of Linux?What is the main purpose of Linux?Apr 16, 2025 am 12:19 AM

The main uses of Linux include: 1. Server operating system, 2. Embedded system, 3. Desktop operating system, 4. Development and testing environment. Linux excels in these areas, providing stability, security and efficient development tools.

Does the internet run on Linux?Does the internet run on Linux?Apr 14, 2025 am 12:03 AM

The Internet does not rely on a single operating system, but Linux plays an important role in it. Linux is widely used in servers and network devices and is popular for its stability, security and scalability.

What are Linux operations?What are Linux operations?Apr 13, 2025 am 12:20 AM

The core of the Linux operating system is its command line interface, which can perform various operations through the command line. 1. File and directory operations use ls, cd, mkdir, rm and other commands to manage files and directories. 2. User and permission management ensures system security and resource allocation through useradd, passwd, chmod and other commands. 3. Process management uses ps, kill and other commands to monitor and control system processes. 4. Network operations include ping, ifconfig, ssh and other commands to configure and manage network connections. 5. System monitoring and maintenance use commands such as top, df, du to understand the system's operating status and resource usage.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.