


Linux driver IO article - mmap operation
Preface
Usually when we write Linux drivers and interact with user space, we always use copy_from_user
Copy 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:

can be achieved through mmap
mapping.
Application layer
The application layer code is very simple, mainly through mmap
System 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);
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 multipleAPP
callmmap
to map the same memory, everyone can see the modifications to the memory. . That is to say, multipleAPP
and drivers actually access the same memory .MAP_PRIVATE
: Create acopy on write
private mapping. WhenAPP
makes modifications to this memory, other programs cannot see these modifications. That is, whenAPP
writes to memory, the kernel will first create a copy for thisAPP
. This copy is private to thisAPP
, 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);
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, };
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!

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

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

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



How to use Docker Desktop? Docker Desktop is a tool for running Docker containers on local machines. The steps to use include: 1. Install Docker Desktop; 2. Start Docker Desktop; 3. Create Docker image (using Dockerfile); 4. Build Docker image (using docker build); 5. Run Docker container (using docker run).

The key differences between CentOS and Ubuntu are: origin (CentOS originates from Red Hat, for enterprises; Ubuntu originates from Debian, for individuals), package management (CentOS uses yum, focusing on stability; Ubuntu uses apt, for high update frequency), support cycle (CentOS provides 10 years of support, Ubuntu provides 5 years of LTS support), community support (CentOS focuses on stability, Ubuntu provides a wide range of tutorials and documents), uses (CentOS is biased towards servers, Ubuntu is suitable for servers and desktops), other differences include installation simplicity (CentOS is thin)

Troubleshooting steps for failed Docker image build: Check Dockerfile syntax and dependency version. Check if the build context contains the required source code and dependencies. View the build log for error details. Use the --target option to build a hierarchical phase to identify failure points. Make sure to use the latest version of Docker engine. Build the image with --t [image-name]:debug mode to debug the problem. Check disk space and make sure it is sufficient. Disable SELinux to prevent interference with the build process. Ask community platforms for help, provide Dockerfiles and build log descriptions for more specific suggestions.

Docker process viewing method: 1. Docker CLI command: docker ps; 2. Systemd CLI command: systemctl status docker; 3. Docker Compose CLI command: docker-compose ps; 4. Process Explorer (Windows); 5. /proc directory (Linux).

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

VS Code To switch Chinese mode: Open the settings interface (Windows/Linux: Ctrl, macOS: Cmd,) Search for "Editor: Language" settings Select "Chinese" in the drop-down menu Save settings and restart VS Code

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.
