Linux driver mmap Memory Map __linux

Source: Internet
Author: User
mmap where Linux is.

what is mmap.

On the illustrated, Mmap is a way to operate these devices, the so-called operating equipment, such as IO port (light an LED), LCD controller, disk controller, is actually to the physical address of the device read and write data.

However, because the application cannot directly manipulate the device hardware address, the operating system provides such a mechanism-memory mapping, mapping the device address to the process virtual address, and Mmap is the interface that implements the memory map.

There are many other ways to operate the equipment, such as IOCTL, IOREMAP

The advantage of Mmap is that mmap the device memory to the virtual memory, the user operation virtual memory is equivalent to the direct operation of the device, eliminating the user space to the kernel space of the replication process, relative IO operation, increase the throughput of the data.


What is a memory map.

Since mmap is the interface that implements memory mapping, what is memory mapping? Look at the picture.

Each process has a separate process address space, through the page table and MMU, the virtual address can be converted to physical address, each process has a separate page table data, which can explain why two different processes the same virtual address, but corresponding to different physical addresses.


What is the virtual address space.

Each process has a 4G virtual address space, where 3G user space, 1G kernel space (Linux), each process sharing kernel space, independent user space, the image below to express this

The driver runs in kernel space, so the driver is oriented to all processes.

There are two ways to switch user space to kernel space:

(1) system call, that is, soft interrupt

(2) Hardware interruption


What is inside the virtual address space.

Knowing what a virtual address space is, what is inside the virtual address space. Look at the picture.

Virtual space installed is probably the above data, memory mapping is probably the device address map to the red section of the image above, for the time being called "Memory Map segment", as to which address is mapped to by the operating system, the operating system will divide the process space into three parts:

(1) Unassigned, that is, the process has not yet used the address

(2) cached, slow-existing pages in RAM

(3) Not cached, not cached in RAM

The operating system allocates a virtual address in the unallocated address space to map the device's address, and the mapping is later revealed.

Now you probably understand what "memory mapping" is, so how does the kernel manage these address spaces? Any complex theory is ultimately represented by a variety of data structures, and this is the process descriptor. Looking at the kernel, process is the carrier of allocating system resources (CPU, memory), in order to manage process, the kernel must have a clear description of what each process does, this is the process descriptor, the kernel uses the TASK_STRUCT structure to represent the process, and maintains a list of the structure body to manage all processes. The structure contains a number of process status, scheduling information, such as thousands of members, we focus on the process descriptor inside the memory descriptor (struct mm_struct mm)


Memory Descriptor

Specific structure, please refer to the following figure

The memory map is now known to map the device address to the process space address (note: Not all memory mappings are mapped to the process address space, Ioremap is mapped to the kernel virtual space, mmap is mapped to the process virtual address), essentially allocating a vm_area_ The struct structure is added to the address space of the process, that is, mapping the device address to the structure, the mapping process is what the driver is going to do.


Realization of memory mapping

In the case of character device drive, the general operation of the character device is as follows block diagram

The main task of memory mapping is to implement the mmap () function in kernel space, first to understand the framework of character device drivers

The following is the source code for MMAP_DRIVER.C

All module codes contain the following two header files #include <linux/module.h> #include <linux/init.h> #include <linux/types.h>// Define the dev_t type #include <linux/cdev.h>//define struct CDEV structure and related operations #include <linux/slab.h>//define Kmalloc interface #include <asm/io.h>//defines Virt_to_phys interface #include <linux/mm.h>//remap_pfn_range #include <linux/fs.h> #define
Major_num 990 #define Mm_size 4096 static char driver_name[] = "mmap_driver1";//driver module name static int dev_major = Major_num;
static int dev_minor = 0;
char *buf = NULL;

struct Cdev *cdev = NULL;
	static int Device_open (struct inode *inode, struct file *file) {PRINTK (kern_alert "Device open\n");
BUF = (char *) kmalloc (mm_size, Gfp_kernel);//kernel request memory can only be requested by page to request the memory so that it is later treated as a virtual device return 0;
	static int device_close (struct inode *indoe, struct file *file) {PRINTK ("Device close\n");
	if (BUF) {kfree (BUF);
return 0; The static int device_mmap (struct file *file, struct vm_area_struct *vma) {vma->vm_flags |= vm_io;//represents a mapping of the device IO space vma- >vm_flaGS |= vm_reserved;//logo This memory area can not be swapped out, in the device driver virtual page and physical page relationship should be long-term, should be retained, can not be casually replaced by other virtual pages if (Remap_pfn_range (vma,//virtual memory region,
					   That is, the device address will be mapped here vma->vm_start,//the starting address of the virtual space Virt_to_phys (BUF) >>page_shift,//the page frame number corresponding to the physical memory, and the physical address is shifted to the right 12 bits
	vma->vm_end-vma->vm_start,//map area size, generally the page size of the integer multiple Vma->vm_page_prot)//protection properties, {Return-eagain;
return 0;
	static struct File_operations Device_fops = {. Owner = This_module,. Open = Device_open,. Release = Device_close,

. mmap = Device_mmap,};
	static int __init char_device_init (void) {int result;
	The dev_t dev;//High 12 digits indicates the main device number, and the low 20-bit indicates the secondary device number PRINTK (kern_alert "Module init2323\n");
	PRINTK ("dev=%d", Dev);
	dev = Mkdev (dev_major, Dev_minor);
	Cdev = Cdev_alloc ();//Allocate space for character device Cdev PRINTK (kern_alert "Module init\n");
	if (dev_major) {result = Register_chrdev_region (dev, 1, driver_name);//static allocation device number PRINTK ("result =%d\n", result);
else {result = Alloc_chrdev_region (&dev, 0, 1, driver_name);//dynamic allocation device number Dev_major = major (Dev);	} if (Result < 0) {PRINTK (kern_warning "cant ' t get major%d\n", dev_major);
	return result;
	} cdev_init (Cdev, &device_fops);//Initialize character device Cdev cdev->ops = &device_fops;
	
	Cdev->owner = This_module;
	result = Cdev_add (Cdev, Dev, 1);//register character device to kernel printk ("DFFD =%d\n", result);
return 0;
	} static void __exit char_device_exit (void) {PRINTK (kern_alert "Module exit\n");
	Cdev_del (Cdev);
Unregister_chrdev_region (Mkdev (Dev_major, Dev_minor), 1);
} module_init (Char_device_init);//Module loading module_exit (char_device_exit);//Module Exit Module_license ("GPL"); Module_author ("Chenshengfa");


Here is the test code TEST_MMAP.C

#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <stdlib.h >
#include <string.h>

int main (void)
{
	int fd;
	char *buffer;
	char *mapbuf;
	FD = open ("/dev/mmap_driver", O_RDWR);//Open the device file, the kernel can get the index node of the device file, fill the inode structure
	if (fd<0)
	{
		printf (" Open device is ERROR,FD =%d\n ", FD);
		return-1;
	}
	/* Test One: View memory map segment
	/printf ("before mmap\n");
	Sleep (15);//Sleeps 15 seconds, view memory graph before mapping cat/proc/pid/maps
	buffer = (char *) malloc (1024);
	memset (buffer, 0, 1024);
	Mapbuf = mmap (NULL, 1024, prot_read| Prot_write, map_shared, FD, 0);//memory mapping, will invoke the driven mmap function
	printf ("after Mmap\n");
	Sleep (15);//Morpheus 15 seconds, at the command line to view the mapped memory graph, if more out of the mapping section, the mapping success/
	
	* Test two: Read and write data to the mapping section to see if success
	/strcpy (Mapbuf, "Driver Test"); /write data to the mapping segment
	memset (buffer, 0, 1024);
	strcpy (buffer, MAPBUF)//Read data from the map segment
	printf ("buf =%s\n", buffer);//If the read data is consistent with the data written, the mapping segment does succeed
	
	
	Munmap ( MAPBUF, 1024);//Remove map free
	(buffer);
	Close (FD);//Closes the file, and the final call to the driver is closed return
	0;
}

Here's the makefile file.

Ifneq ($ (kernelrelease),)

obj-m: = mmap_driver.o

Else
kdir: =/lib/modules/3.2.0-52-generic/build

All:
	make-c $ (kdir) m=$ (PWD) modules clean
:
	rm-f *.ko

*.o *.mod.o *.mod.c *~ *.symvers *.order endif


The following command demonstrates the driver's compilation, installation, and testing process (note: Other users will need chmod to change permissions after Mknod)

# make//compile drive

# Insmod Mmap_driver.ko//installation drive

# Mknod/dev/mmap_driver C 999 0//Create device files

# gcc Test_mmap.c-o TEST.O//Compiling application

#./TEST.O//Run the application to test the driver


Expand:

There are some terms involved in this process

(1) Device files: Linux hardware virtual into device files, the normal file of various operations are applicable to equipment files

(2) Index node: Linux uses index nodes to record file information (such as file length, creation modification time), it is stored in disk, read into memory is an INODE structure, file system maintains an array of index nodes, each element and file or directory one by one corresponding.

(3) Main equipment number: As above 999, indicating the type of equipment, such as the device is LCD or USB, etc.

(4) Sub-equipment number: As above 0, indicating that the different equipment on this type of equipment

(5) Three structures of documents (ordinary or equipment files)

① file operation: struct file_operations

② Files object: struct file

③ File index node: struct inode


For the implementation of memory mapping in the driver, first understand the open and close process

(1) Device driven open process

① Application calls open ("/dev/mmap_driver", O_RDWR);

②open will find the index node (inode) of the device through the VFS, mknod the driver's file_operations structure to the index node according to the device number (about Mknod/dev/mmap_driver c 999 0, this instruction creates a device file that, when the driver (INSMOD) is installed, runs the driver's initialization program (MODULE_INIT), which registers its main device number into the system (CDEV_ADD) in the initialization program. If the main device number 999 in the Mknod does not exist in the system, which is different from the registered main device number, the above instruction fails and the device file cannot be created.

③ then invokes the driven open method based on the open pointer in the file_operations in the index node of the device file.

④ generates a file object files_struct structure, the system maintains a files_struct list of all open files in the system

⑤ returns the file descriptor fd, adding FD to the process's File descriptor table


(2) device driver close process

The application calls Close (FD), which ultimately invokes the drive close, and why the driven close function can be found based on a simple int fd. This is closely related to the three structures mentioned above (struct file_operations, struct file, struct inode), if FD = 3


(3) Equipment Drive mmap Process

By open and close, for the same reason, the application call Mmap will eventually call into the driver Mmap method

Mmap functions in ① application test.mmap.c

void* mmap (void *addr, size_t length, int prot, int flags, int fd, off_t offset);

Addr: The starting address of the virtual address after mapping, usually null, and the kernel is automatically allocated

Length: Size of map area

Prot: Page access rights (Prot_read, Prot_write, Prot_exec, Prot_none)

Flags: Reference Network information

FD: File descriptor

Offset: File map start offset


mmap function in mmap_driver.c of ② driver

Above said, Mmap's main work is to map the device address to the process virtual address, also is a vm_area_struct structure, the mapping here, is a very hanging thing, then it in the program performance is what? --page table, yes, is the page table, mapping is to create a page table. The process address space can be mapped to the device address by the page table (software) and MMU (hardware).

Virt_to_phys (BUF), BUF is the address in open, where the use of Virt_to_phys to convert buf to physical address, is a simulation of a hardware device, that is, the virtual device map to the virtual address, in fact, you can directly use the physical address.


Summarize

① from the above, the various modules of the kernel are intricate and overlapping.

② simple a small drive module, which involves process management (process address space), Memory Management (page table and page frame mapping), virtual file system (Structfile, Structinode)

③ Not all device drivers can be mapped using mmap, such as serial ports and other streaming-oriented devices, and must be mapped by page size.


reference materials

"Linux kernel design and implementation"

"Deep understanding of computer systems"

"Linux Device Drivers"

Deep understanding of the Linux kernel

"The self-cultivation of the programmer"

"Linux device Driver development detailed"


At last, you reader hard.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.