pa

#include "fcntl.h"
#include "unistd.h"
#define PFN_MASK_SIZE 8
size_t virt2phy(size_t virtaddr)
{
int fd, retval;
size_t page, physaddr;
size_t virt_pfn;
size_t page_size;
off_t offset;


/* standard page size */
page_size = 4096;

fd = open("/proc/self/pagemap", O_RDONLY);
if (fd < 0) {
return -1;
}

virt_pfn = virtaddr / page_size;
offset = sizeof(size_t) * virt_pfn;
if (lseek(fd, offset, SEEK_SET) == (off_t) -1) {
close(fd);
return -2;
}

retval = read(fd, &page, sizeof(size_t));
close(fd);
if (retval < 0 || retval != sizeof(size_t)) {
return -3;
}

/*
* the pfn (page frame number) are bits 0-54 (see
* pagemap.txt in linux Documentation)
*/
physaddr = ((page & 0x7fffffffffffffULL) * page_size)
+ ((unsigned long)virtaddr % page_size);

return physaddr;
}

#include "sys/mman.h"
int main(int argc, char *argv[])
{
void *m1 = mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
void *m = mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);

uint64_t r = va_to_pa((uint64_t)m);
uint64_t r2 = virt2phy((uint64_t)m);
return 0;
}
posted @ 2021-06-21 15:14  zJanly  阅读(197)  评论(0编辑  收藏  举报