当前位置:网站首页>It is interesting to understand MMAP in this way!
It is interesting to understand MMAP in this way!
2022-07-01 09:53:00 【Embedded Linux,】
Probably Emperor Yongzheng never thought of it , I am in the Western calendar 2022 In the eyes of young boys and girls , There will be two different images .
1
Based on my observation of my classmates and friends around me , Most boys like to watch 《 Yongzheng Dynasty 》, Yongzheng in their eyes , It's about a promotion “ The fire is consumed ”、“ Spread small into Mu ” And so on , Tax relief and other policies Reformer , It's a thrilling experience of nine sons' seizing the throne 、 Dark belly Politician , He was also conscientious after he ascended the throne , Stay up late 996 Of workaholic .
And most girls like to watch 《 Zhen Huan preach 》, Yongzheng in their eyes , yes “ Big fat orange ”, yes “ unfaithful man ”, It was played by concubines in the harem , Yes N A green hat , Finally, he was angry with Niu cobalt Lu Zhen Huan Cheating on men who play with women's affections .
I haven't seen the legend of Zhen Huan completely , But I was lucky to watch several episodes with my family during dinner .
As the saying goes There are three thousand beauties in the harem , Grind an iron pestle into an embroidery needle ... ( No
There are too many concubines , The emperor is only one , It is inevitable that they will be jealous of each other . The high ranking imperial concubine's bullying , Some little concubines can't fight back directly , Naturally, I will use some other strange skills , Prick a villain It is one of the most frequent methods .
According to my summary , The core idea of this technology is : The user can't get to the master , You can only take a piece of cloth and other objects around you to simulate a little man , Draw the meridians and veins of Zhengzhu on it , Write your name , Cast some kind of magic , Then use a needle to pierce a certain acupoint of the villain at hand , The corresponding part of the remote Lord will suffer the same torture .
Although it is a bit magical , Enviable but not available . But in linux Kernel development , But you can use mmap A similar effect is achieved by the mechanism of .
2
mmap The core idea of : The user cannot directly operate the physical address of the register in the user state , So through mmap Method for memory mapping , Map the physical address to the virtual address of the user state , Then the user reads and writes the virtual address at hand , You can read the physical address / write in .
What they have in common is , because The target cannot be operated directly , So in some way , Set up a kind of mapping Relationship , So as to achieve arm and finger , Where to hit , The effect of hitting and hurting .
As long as the mapping to the target can be established , What can we do with this mapping , Naturally, there is a lot of imagination . therefore mmap There are many uses , Some people use it to realize interprocess communication , Someone uses it to carry data , For our embedded engineers , We can use it to light a lamp . Hey , Surprised? !
Listen to me .
3
As an embedded Engineer , Fancy lighting is a necessary skill . Whether it's writing bare metal code GPIO mouth , Or remote control through the cloud of the Internet of things LED, From a hardware point of view , The core principle is to find the connection LED Of GPIO mouth , Let it output an electrical signal . From the software point of view , The ultimate goal is to find this GPIO Mouth correspondence The address of the register , According to the actual circuit requirements , Give Way CPU Write it a 1 perhaps 0.
During bare metal development , We can directly find the physical address for operation . And in the Linux The system is slightly different . Because there is kernel space in the operating system , The programs we write run in user mode , You need to drive the hardware through the kernel , Cannot directly manipulate physical address .
Of course you can choose for this LED Write a driver , Thus in the user space through read,write To operate its state . However, some students have to write a drive when they listen to it , I just want to sing a song about how difficult it is to express my flinch . So if you haven't learned about driver, you can also choose to use a more direct way :mmap.
It's like you can choose to drug the imperial concubine to control her , However, this method of medication needs to be proficient in Pharmacology 、 Control the timing , The high cost , Is difficult . As long as the goal can be achieved , Sometimes it's more economical to stick with a villain .
When I was in my last company, I used ARM Cortex-A9 Chip has done a project , The development process is probably to agree a protocol with the hardware colleagues first , Then I go through GPIO The input and output of the port simulate this Protocol , It is used to read and write registers , Driver hardware ADC sampling , Then the collected data is passed DMA transmission , Finally, it goes to the application layer for analysis and processing . Which drives GPIO The mouth part is used mmap.
Great project , For more than half a year , It's unrealistic to want to be completely clear , But we can drive GPIO This is the starting point , Experience the mysterious process of software driving hardware . Smart you can draw inferences from one instance .
4
As a software engineer , When you get the board , The hardware engineer will usually give you a document , Like this :
This document will indicate , If you want to operate this GPIO Words of mouth , You need to use GPIO Add the base address of the peripheral and the offset address to find the corresponding register address , And then the bit operation is applied to the specified bit Write command .
But because of FPGA There will also be some , So in our company FPGA Of Block Diagram I built it all . finish building FPGA After the hardware engineering, do a comprehensive , from Address Map You can see what I want to use GPIO The address is . Pictured :
No matter what , Now you have the so-called hardware register address , Then we can stab it with a villain .
I got the above picture 0x43C00000 For example , This is the address of the register , Can I put... Directly in the application 0x43C00000 Assign to a pointer , Then read and write it ?
This is true when playing bare metal . But it says ,Linux The system has Virtual memory The existence of , You can't do that . Because theoretically, I can drive in the system 100 A process , this 100 There are all processes 0x43C00000 This address , What about this 100 Which address is the real register address ? It may not be . Because in the process 0x43C00000 It's virtual. , Where is its real physical address , No one knows . To map a virtual address to a physical address , You have to use it. mmap Do memory mapping .
5
mmap The function interface of is defined as follows :
void mmap(void addr,size_t length,
int prot,int flags,
int fd,off_t offset);
There are many parameters . among addr Generally designated as NULL,prot Is used to set the permissions of the mapping area , For example, whether it is readable or writable ;flags Is used to specify whether the mapping is shared or private ; and fd,offset,length These three parameters indicate that fd Corresponding file , from offset From the position , The length will be length The content of the process is mapped to the address space of the process .
We need to pay attention to mmap The operation unit of is page , That is, the last mapped offset Parameter must be An integer multiple of the size of a memory page , and Linux The system memory page size is generally 4096 byte .
An example of my call in the program :
#define AXI_GPIO_BASEADDR 0x43C00000
int memfd = open("/dev/mem", O_RDWR
| O_SYNC);
if (-1 == memfd) {
printf("Can't open /dev/mem\n");
return -1;
}
unsigned int* led_gpio =
(unsigned int*)(mmap(
NULL, MMAP_SIZE,
PROT_READ | PROT_WRITE,
MAP_SHARED, memfd,
AXI_GPIO_BASEADDR));
call mmap after , We get a pointer , Do any operation on the pointed address through this pointer , The corresponding register physical address will have the same effect . So we assign it circularly 0101, Controlled by the corresponding register GPIO The port outputs an electrical signal , So the light on the board flashes successfully , Similar to the energy lamp when Altman is out of strength .
6
Say two more words , Except to operate GPIO/ Outside the character device ,mmap Another common scenario is to operate a block device . It is different from the traditional use read,write The difference between , The key is Save a copy .
For example, to read the data of a file on the disk , use read write Words , Because it involves system calls , Processes cannot access the kernel directly , So in read Before the system call returns , The kernel needs to put the data From the kernel Copy to process designated buffer in .
But if use mmap Words , Then this data will be copied to memory as Page caching ( namely page cache). use mmap Will this period of Memory mapping To user space , Then the process can read and write directly through the pointer page cache, No more unnecessary system calls and memory copies .
But although one copy is missing , but mmap Will trigger Missing pages interruption (page fault), Compared to memory copy , Page missing interrupt It's more expensive . So in terms of performance mmap In most cases, it is not better than read/write It is better to .
Speaking of page caching , When I was developing projects in my last company , Has also been Dirty page delay This thing has gone through . And the limit of the length , Page cache involves page break , Dirty page , Delay writing back ,sync Forced writeback, etc , Let's talk more about it next time .
7
Okay , So we learned to use mmap Light up a light . Imagine the next scene :
You tell the most beautiful female colleague in the R & D Department of the company ,
“hi, The leader gave our group a new task , You write a drive to control it LED Well ?”
“ ah ? Driving is so hard , I won't ”
“ Oh, it's okay , That you use mmap Well ”
“ Hey, how can you swear !”
边栏推荐
- SQL 化是 ETL 增量生产的第一步,这样的架构的核心能力是什么?
- HMS core audio editing service 3D audio technology helps create an immersive auditory feast
- button按钮清除边框
- PHP 字符串与二进制相互转换
- Centos 配置discuz 提示请检查 mysql 模块是否正确加载
- 谁拥有穿越周期的眼光?
- 苹果放大招!这件事干的太漂亮了……
- Problems caused by delete and delete[]
- In terms of use
- Get the list of a column in phpexcel get the letters of a column
猜你喜欢
Dotnet console uses microsoft Maui. Getting started with graphics and skia
Fried money, lost 10million.
Cortex M4 systick details
吃一个女富豪的瓜。。。
IPv6 learning notes
dotnet 控制台 使用 Microsoft.Maui.Graphics 配合 Skia 进行绘图入门
Hololens2 development -6-eyetracking and speech recognition
Flinkv1.13实现金融反诈骗案例
LVGL V8.2字符串显示在Keil MDK上需要注意的事项(以小熊派为例)
The market is relatively weak recently
随机推荐
Weidongshan board compilation kernel problem solving
What is cloud primordial? Will it be the trend of future development?
[unity rendering] customized screen post-processing
[unity shader] substitution of bool type in the property definition
Wechat applet WebView prohibits page scrolling without affecting the implementation of overflow scrolling in the business
谁拥有穿越周期的眼光?
项目采购管理
我喜欢两个男人。。。
BSN长话短说之十:如何保证NFT的安全
SSH服务器拒绝密码,再试一次;PermitRootLogin yes无效问题
ES6 const essence and completely immutable implementation (object.free)
How did the data center change from "Britney Spears" to "Mrs. cow"?
怎么理解JS Promise
持续进阶,软通动力稳步推动云智能战略
PHP string to binary conversion
The stock position building rate of global funds and asset management reached a new low in 15 years
项目必用的全局异常处理器,你学会了吗
IPv6 learning notes
How to understand JS promise
Construction of esp8266 FreeRTOS development environment