search
HomeOperation and MaintenanceLinux Operation and MaintenanceLinux driver IO article - mmap operation

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);

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);

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!

Statement
This article is reproduced at:嵌入式Linux充电站. If there is any infringement, please contact admin@php.cn delete
What is Maintenance Mode in Linux? ExplainedWhat is Maintenance Mode in Linux? ExplainedApr 22, 2025 am 12:06 AM

MaintenanceModeinLinuxisaspecialbootenvironmentforcriticalsystemmaintenancetasks.Itallowsadministratorstoperformtaskslikeresettingpasswords,repairingfilesystems,andrecoveringfrombootfailuresinaminimalenvironment.ToenterMaintenanceMode,interrupttheboo

Linux: A Deep Dive into Its Fundamental PartsLinux: A Deep Dive into Its Fundamental PartsApr 21, 2025 am 12:03 AM

The core components of Linux include kernel, file system, shell, user and kernel space, device drivers, and performance optimization and best practices. 1) The kernel is the core of the system, managing hardware, memory and processes. 2) The file system organizes data and supports multiple types such as ext4, Btrfs and XFS. 3) Shell is the command center for users to interact with the system and supports scripting. 4) Separate user space from kernel space to ensure system stability. 5) The device driver connects the hardware to the operating system. 6) Performance optimization includes tuning system configuration and following best practices.

Linux Architecture: Unveiling the 5 Basic ComponentsLinux Architecture: Unveiling the 5 Basic ComponentsApr 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.

Linux Operations: Utilizing the Maintenance ModeLinux Operations: Utilizing the Maintenance ModeApr 19, 2025 am 12:08 AM

Linux maintenance mode can be entered through the GRUB menu. The specific steps are: 1) Select the kernel in the GRUB menu and press 'e' to edit, 2) Add 'single' or '1' at the end of the 'linux' line, 3) Press Ctrl X to start. Maintenance mode provides a secure environment for tasks such as system repair, password reset and system upgrade.

Linux: How to Enter Recovery Mode (and Maintenance)Linux: How to Enter Recovery Mode (and Maintenance)Apr 18, 2025 am 12:05 AM

The steps to enter Linux recovery mode are: 1. Restart the system and press the specific key to enter the GRUB menu; 2. Select the option with (recoverymode); 3. Select the operation in the recovery mode menu, such as fsck or root. Recovery mode allows you to start the system in single-user mode, perform file system checks and repairs, edit configuration files, and other operations to help solve system problems.

Linux's Essential Components: Explained for BeginnersLinux's Essential Components: Explained for BeginnersApr 17, 2025 am 12:08 AM

The core components of Linux include the kernel, file system, shell and common tools. 1. The kernel manages hardware resources and provides basic services. 2. The file system organizes and stores data. 3. Shell is the interface for users to interact with the system. 4. Common tools help complete daily tasks.

Linux: A Look at Its Fundamental StructureLinux: A Look at Its Fundamental StructureApr 16, 2025 am 12:01 AM

The basic structure of Linux includes the kernel, file system, and shell. 1) Kernel management hardware resources and use uname-r to view the version. 2) The EXT4 file system supports large files and logs and is created using mkfs.ext4. 3) Shell provides command line interaction such as Bash, and lists files using ls-l.

Linux Operations: System Administration and MaintenanceLinux Operations: System Administration and MaintenanceApr 15, 2025 am 12:10 AM

The key steps in Linux system management and maintenance include: 1) Master the basic knowledge, such as file system structure and user management; 2) Carry out system monitoring and resource management, use top, htop and other tools; 3) Use system logs to troubleshoot, use journalctl and other tools; 4) Write automated scripts and task scheduling, use cron tools; 5) implement security management and protection, configure firewalls through iptables; 6) Carry out performance optimization and best practices, adjust kernel parameters and develop good habits.

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor