Table of Contents
驱动层 " >驱动层
Home Operation and Maintenance Linux Operation and Maintenance Linux driver IO article - mmap operation

Linux driver IO article - mmap operation

Jul 31, 2023 pm 03:55 PM
linux

Preface

Usually when we write Linux drivers and interact with user space, we always use copy_from_userCopy the data transferred from user space. Why do you do this?

Because user space cannot directly access kernel space data, they map different address spaces, and the data can only be copied first and then operated.

If the user space needs to transfer several MB of data to the kernel, then the original copy method is obviously very inefficient and unrealistic, so what should we do?

Think about it, the reason for copying is because user space cannot directly access the kernel space. So if the buffer in the kernel space can be directly accessed, would it be solved?

To put it simply, a piece of physical memory has two mappings, that is, it has two virtual addresses, one in kernel space and one in user space. The relationship is as follows:

Linux driver IO article - mmap operation

can be achieved through mmap mapping.

Application layer

The application layer code is very simple, mainly through mmapSystem callMap, and then you can operate on the returned address. The first parameter of

char * buf;
/* 1. 打开文件 */
 fd = open("/dev/hello", O_RDWR);
 if (fd == -1)
 {
      printf("can not open file /dev/hello\n");
      return -1;
 }

/* 2. mmap
       * MAP_SHARED  : 多个APP都调用mmap映射同一块内存时, 对内存的修改大家都可以看到。
       *               就是说多个APP、驱动程序实际上访问的都是同一块内存
       * MAP_PRIVATE : 创建一个copy on write的私有映射。
       *               当APP对该内存进行修改时,其他程序是看不到这些修改的。
       *               就是当APP写内存时, 内核会先创建一个拷贝给这个APP,
       *               这个拷贝是这个APP私有的, 其他APP、驱动无法访问。
       */
buf =  mmap(NULL, 1024*8, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
Copy after login

mmap is the starting address you want to map, usually set to NULL, means that the kernel determines the starting address address.

The second parameter is the size of the memory space to be mapped.

The third parameterPROT_READ | PROT_WRITE indicates that the mapped space is readable and writable.

The fourth parameter can be filled in MAP_SHARED or MAP_PRIVATE:

  • MAP_SHARED: When multiple APP call mmap to map the same memory, everyone can see the modifications to the memory. . That is to say, multiple APP and drivers actually access the same memory .
  • MAP_PRIVATE: Create a copy on write private mapping. When APP makes modifications to this memory, other programs cannot see these modifications. That is, when APP writes to memory, the kernel will first create a copy for this APP. This copy is private to this APP, and others APP and driver cannot be accessed.

驱动层

驱动层主要是实现mmap接口,而mmap接口的实现,主要是调用了remap_pfn_range函数,函数原型如下:

int remap_pfn_range(
  struct vm_area_struct *vma, 
  unsigned long addr, 
  unsigned long pfn, 
  unsigned long size, 
  pgprot_t prot);
Copy after login

vma:描述一片映射区域的结构体指针

addr:要映射的虚拟地址起始地址

pfn:物理内存所对应的页框号,就是将物理地址除以页大小得到的值

size:映射的大小

prot:该内存区域的访问权限

驱动主要步骤:

1、使用kmalloc或者kzalloc函数分配一块内存kernel_buf,因为这样分配的内存物理地址是连续的,mmap后应用层会对这一个基地址去访问这块内存。

2、实现mmap函数

static int hello_drv_mmap(struct file *file, struct vm_area_struct *vma)
{
 /* 获得物理地址 */
 unsigned long phy = virt_to_phys(kernel_buf);//kernel_buf是内核空间分配的一块虚拟地址空间
    
    /* 设置属性:cache, buffer*/
 vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot);
    
    /* map */
    if(remap_pfn_range(vma, vma->vm_start, phy>>PAGE_SHFIT,
                      vma->vm_end - vma->start, vma->vm_page_prot)){
 printk("mmap remap_pfn_range failed\n");
    return -ENOBUFS;
 }
 return 0;
}

static struct file_operations my_fops = {
 .mmap = hello_drv_mmap,
};
Copy after login

1、通过virt_to_phys将虚拟地址转为物理地址,这里的kernel_buf是内核空间的一块虚拟地址空间

2、设置属性:不使用cache,使用buffer

3、映射:通过remap_pfn_range函数映射,phy>>PAGE_SHIFT其实就是按page映射,除了这个参数,其他的起始地址、大小和权限都可以由用户在系统调用函数中指定

当应用层调用mmap后,就会调用到驱动层的mmap函数,最终应用层的虚拟地址和驱动中的物理地址就建立了映射关系,应用层也就可以直接访问驱动的buffer了。

The above is the detailed content of Linux driver IO article - mmap operation. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
Linux Architecture: Unveiling the 5 Basic Components Linux Architecture: Unveiling the 5 Basic Components Apr 20, 2025 am 12:04 AM

The five basic components of the Linux system are: 1. Kernel, 2. System library, 3. System utilities, 4. Graphical user interface, 5. Applications. The kernel manages hardware resources, the system library provides precompiled functions, system utilities are used for system management, the GUI provides visual interaction, and applications use these components to implement functions.

vscode terminal usage tutorial vscode terminal usage tutorial Apr 15, 2025 pm 10:09 PM

vscode built-in terminal is a development tool that allows running commands and scripts within the editor to simplify the development process. How to use vscode terminal: Open the terminal with the shortcut key (Ctrl/Cmd). Enter a command or run the script. Use hotkeys (such as Ctrl L to clear the terminal). Change the working directory (such as the cd command). Advanced features include debug mode, automatic code snippet completion, and interactive command history.

How to check the warehouse address of git How to check the warehouse address of git Apr 17, 2025 pm 01:54 PM

To view the Git repository address, perform the following steps: 1. Open the command line and navigate to the repository directory; 2. Run the "git remote -v" command; 3. View the repository name in the output and its corresponding address.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

vscode terminal command cannot be used vscode terminal command cannot be used Apr 15, 2025 pm 10:03 PM

Causes and solutions for the VS Code terminal commands not available: The necessary tools are not installed (Windows: WSL; macOS: Xcode command line tools) Path configuration is wrong (add executable files to PATH environment variables) Permission issues (run VS Code as administrator) Firewall or proxy restrictions (check settings, unrestrictions) Terminal settings are incorrect (enable use of external terminals) VS Code installation is corrupt (reinstall or update) Terminal configuration is incompatible (try different terminal types or commands) Specific environment variables are missing (set necessary environment variables)

How to run java code in notepad How to run java code in notepad Apr 16, 2025 pm 07:39 PM

Although Notepad cannot run Java code directly, it can be achieved by using other tools: using the command line compiler (javac) to generate a bytecode file (filename.class). Use the Java interpreter (java) to interpret bytecode, execute the code, and output the result.

How to run sublime after writing the code How to run sublime after writing the code Apr 16, 2025 am 08:51 AM

There are six ways to run code in Sublime: through hotkeys, menus, build systems, command lines, set default build systems, and custom build commands, and run individual files/projects by right-clicking on projects/files. The build system availability depends on the installation of Sublime Text.

vscode Previous Next Shortcut Key vscode Previous Next Shortcut Key Apr 15, 2025 pm 10:51 PM

VS Code One-step/Next step shortcut key usage: One-step (backward): Windows/Linux: Ctrl ←; macOS: Cmd ←Next step (forward): Windows/Linux: Ctrl →; macOS: Cmd →

See all articles