Linux下获取虚拟地址对应的物理地址的方式

* /proc/pid/pagemap. this file lets a userspace process find out which
physical frame each virtual page is mapped to. it contains one 64-bit
value for each virtual page, containing the following data (from
fs/proc/task_mmu.c, above pagemap_read):
* bits 0-54 page frame number (pfn) if present
* bits 0-4 swap type if swapped
* bits 5-54 swap offset if swapped
* bit 55 pte is soft-dirty (see documentation/vm/soft-dirty.txt)
* bits 56-60 zero
* bit 61 page is file-page or shared-anon
* bit 62 page swapped
* bit 63 page present
if the page is not present but in swap, then the pfn contains an
encoding of the swap file number and the page‘s offset into the
swap. unmapped pages return a null pfn. this allows determining
precisely which pages are mapped (or in swap) and comparing mapped
pages between processes.
接下来,我们根据上述描述,给出获取虚拟地址对应的物理地址的代码
#include 《stdio.h》
#include 《stdint.h》
#include 《sys/types.h》
#include 《sys/stat.h》
#include 《fcntl.h》
#include 《unistd.h》
#define page_map_file “/proc/self/pagemap”
#define pfn_mask ((((uint64_t)1)《《55)-1)
#define pfn_present_flag (((uint64_t)1)《《63)
int mem_addr_vir2phy(unsigned long vir, unsigned long *phy)
{
int fd;
int page_size=getpagesize();
unsigned long vir_page_idx = vir/page_size;
unsigned long pfn_item_offset = vir_page_idx*sizeof(uint64_t);
uint64_t pfn_item;
fd = open(page_map_file, o_rdonly);
if (fd《0)
{
printf(“open %s failed”, page_map_file);
return -1;
}
if ((off_t)-1 == lseek(fd, pfn_item_offset, seek_set))
{
printf(“lseek %s failed”, page_map_file);
return -1;
}
if (sizeof(uint64_t) != read(fd, &pfn_item, sizeof(uint64_t)))
{
printf(“read %s failed”, page_map_file);
return -1;
}
if (0==(pfn_item & pfn_present_flag))
{
printf(“page is not present”);
return -1;
}
*phy = (pfn_item & pfn_mask)*page_size + vir % page_size;
return 0;
}
如果担心vir地址对应的页面不在内存中,可以在调用mem_addr_vir2phy之前,先访问一下此地址。
例如, int a=*(int *)(void *)vir;
如果担心linux的swap功能将进程的页面交换到硬盘上从而导致页面的物理地址变化,可以关闭swap功能。
下面两个c库函数可以阻止linux将当前进程的部分或全部页面交换到硬盘上。
int mlock(const void *addr, size_t len);
int mlockall(int flags);

「技术前沿」蓝牙将致力于推动哪些领域的连接?
「移动机器人行业应用分析」锂电行业
微雪电子EP2C FPGA NIOSII开发板简介
首次实现了基于蚕丝蛋白的高容量生物存储技术
移频键控信号测量系统设计[图]
Linux下获取虚拟地址对应的物理地址的方式
iOS 13.4现已支持高德地图分屏功能 导航点歌两不误
【Renesas GUI挑战】变电站巡检机器人控制系统开发
春季新机集体抛弃3D人脸识别,2D人脸识别缺陷明显
关于新兴NVM存储技术分析介绍及工艺选择的分析
树莓派-GPIO功能及复用功能表
如何将两个转换器并联使得DC-DC转换器的负载电流倍增
微软砍单英伟达H100减少至8万台
行业协会标准免费下载|《有机发光二极管照明 术语和文字符号》
M12连接器3芯电气设备性能
复印机显影系统
量子点显示技术(QLED)电视已成主流 TCL电视发力
导热硅脂用在电器中是否安全
NPN晶体管BD139的用途和电路案例
AI最终目的是服务于人类 AI+医疗是最具争论的AI市场