Memory application technology in Linux drivers: principles and methods
Memory is one of the most important resources in a Linux system. It can be used to store data, code, stacks, etc. Memory application and release is one of the most basic operations in Linux driver development. It involves concepts such as kernel space and user space, static allocation and dynamic allocation, continuous memory and non-contiguous memory. In this article, we will introduce the memory application technology in Linux drivers, including kmalloc, vmalloc, get_free_pages, dma_alloc_coherent and other functions, and give examples to illustrate their usage and precautions.
Let’s start with the basics. The picture below is the memory mapping model of Linux
- Each process has its own process space. 0-3G of the process space is user space, and 3G-4G is kernel space
- The user space of each process is not in the same physical memory page, but the kernel space of all processes corresponds to the same physical address
- The address allocated by vmalloc can be high-end memory or low-end memory
- Physical addresses of 0-896MB are linearly mapped to the physical mapping area.
“
”
Dynamic memory application
Like the application layer, the kernel program also needs to dynamically allocate memory. The difference is that the kernel process can control whether the allocated memory is in user space or kernel space. The former can be used to allocate memory to the heap area of user space, eg , the malloc of the user space of the user process will eventually call back the memory allocation function of the kernel space through a system call. At this time, the memory allocation function belongs to the user process, and can allocate space in the heap area of the user process and return it, ultimately making A user process obtains memory allocation in its own user space; the latter is only allocated in the kernel space, so the user process cannot directly access the space, so it is mostly used to meet the memory needs of the kernel program itself. The following is a common API for Linux kernel space application memory :
kmalloc – kfree
The memory requested by kmalloc is continuous in physical memory. They have only a fixed offset from the real physical address, so there is a simple conversion relationship. This API is mostly used to apply for memory that is less than one page size. The bottom layer of kmalloc needs to call **__get_free_pages. The gtp_t flags indicating the memory type in the parameter is the abbreviation of this function. Commonly used memory types include GFP_USER, GFP_KERNEL, GFP_ATOMIC**.
- GFP_USER means allocating memory for user space pages and can be blocked;
- GFP_KERNEL is the most commonly used flag. Note that when using this flag to apply for memory, if it cannot be satisfied temporarily, it will cause the process to block. So, must not be used in interrupt processing functions, tasklets and kernel timers. Use GFP_KERNEL in non-process context! ! !
- GFP_ATOMIC can be used in the above three scenarios. This flag indicates that if the requested memory cannot be used, it will return immediately.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
The same series of APIs also have
1 |
|
__get_free_pages – free_pages
__get_free_pages(), like kmalloc(), is physically continuous memory. This series of functions is the lowest-level method in the Linux kernel for obtaining free memory, because the underlying buddy algorithm is based on **(2^n )×PAGE_SIZE to manage memory, so theyalways allocate memory in units of pages**
1 2 |
|
The same series of APIs also have
1 2 3 4 |
|
vmalloc – vfree
vmalloc在虚拟内存空间给出一块连续的内存区,实质上,这片连续的虚拟内存在物理内存中并不一定连续,所以vmalloc申请的虚拟内存和物理内存之间也就没有简单的换算关系,正因如此,vmalloc()通常用于分配远大于__get_free_pages()的内存空间,它的实现需要建立新的页表,此外还会调用使用GFP_KERN的kmalloc,so,一定不要在中断处理函数,tasklet和内核定时器等非进程上下文中使用vmalloc!
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
同系列的API还有
1 2 3 4 5 6 7 |
|
slab缓存
我们知道,页是内存映射的基本单位,但内核中很多频繁创建的对象所需内存都不到一页,此时如果仍然按照页映射的方式,频繁的进行分配和释放就会造成资源的浪费,同时也会降低系统性能。为了解决的这样的问题,内核引入了slab机制,使对象在前后两次被使用时被分配在同一块内存或同一类内存空间,且保留了基本的数据结构,就可以大大提高效率。kmalloc的底层即是使用slab算法管理分配的内存的。注意,slab依然是以页为单位进行映射,只是映射之后分割这些页为相同的更小的单元,从而节省了内存。slab分配的单元不能小于32B或大于128K。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
|
范例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
内存池
除了slab机制,内核还提供了传统的内存池机制来管理小块内存的分配。内存池主要是用来解决可能出现的内存不足的情况,因为一个内存池在创建的时候就已经分配好了一内存,当我们用mempool_alloc向一个已经创建好的内存池申请申请内存时,该函数首先会尝试回调内存池创建时的分配内存函数,如果已经没有内存可以分配,他就会使用内存池创建时预先分配的内存,这样就可以避免因为无内存分配而陷入休眠,当然,如果预分配的内存也已经使用完毕,还是会陷入休眠。slab机制的目的是提高内存使用率以及内存管理效率,内存池的目的是避免内存的分配失败。下面是内核中提供的关于内存池的API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
|
通过本文,我们了解了Linux驱动中的内存申请技术,它们各有优缺点和适用场景。我们应该根据实际需求选择合适的函数,并遵循一些基本原则,如匹配申请和释放函数,检查返回值是否为空,避免内存泄漏等。内存申请技术是Linux驱动开发中不可或缺的一部分,它可以保证驱动程序的正常运行和数据交换,也可以提升驱动程序的性能和稳定性。希望本文能够对你有所帮助和启发。
The above is the detailed content of Memory application technology in Linux drivers: principles and methods. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



DeepSeek is a powerful intelligent search and analysis tool that provides two access methods: web version and official website. The web version is convenient and efficient, and can be used without installation; the official website provides comprehensive product information, download resources and support services. Whether individuals or corporate users, they can easily obtain and analyze massive data through DeepSeek to improve work efficiency, assist decision-making and promote innovation.

There are many ways to install DeepSeek, including: compile from source (for experienced developers) using precompiled packages (for Windows users) using Docker containers (for most convenient, no need to worry about compatibility) No matter which method you choose, Please read the official documents carefully and prepare them fully to avoid unnecessary trouble.

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

BITGet is a cryptocurrency exchange that provides a variety of trading services including spot trading, contract trading and derivatives. Founded in 2018, the exchange is headquartered in Singapore and is committed to providing users with a safe and reliable trading platform. BITGet offers a variety of trading pairs, including BTC/USDT, ETH/USDT and XRP/USDT. Additionally, the exchange has a reputation for security and liquidity and offers a variety of features such as premium order types, leveraged trading and 24/7 customer support.

Gate.io is a popular cryptocurrency exchange that users can use by downloading its installation package and installing it on their devices. The steps to obtain the installation package are as follows: Visit the official website of Gate.io, click "Download", select the corresponding operating system (Windows, Mac or Linux), and download the installation package to your computer. It is recommended to temporarily disable antivirus software or firewall during installation to ensure smooth installation. After completion, the user needs to create a Gate.io account to start using it.

Ouyi OKX, the world's leading digital asset exchange, has now launched an official installation package to provide a safe and convenient trading experience. The OKX installation package of Ouyi does not need to be accessed through a browser. It can directly install independent applications on the device, creating a stable and efficient trading platform for users. The installation process is simple and easy to understand. Users only need to download the latest version of the installation package and follow the prompts to complete the installation step by step.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Ouyi, also known as OKX, is a world-leading cryptocurrency trading platform. The article provides a download portal for Ouyi's official installation package, which facilitates users to install Ouyi client on different devices. This installation package supports Windows, Mac, Android and iOS systems. Users can choose the corresponding version to download according to their device type. After the installation is completed, users can register or log in to the Ouyi account, start trading cryptocurrencies and enjoy other services provided by the platform.
