I wrote a program which calculates the physical address of a given virtual address. This program always return 0. Which means that particular page is not found. Why is that page not available?
What this code does is: This code creates a memory of a file and that memory mapped virtual address is converted to physical address using a function that I took from https://stackoverflow.com/a/28987409/6941772.
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h> // O_RDONLY
//#include <stddef.h> // to get NULL definition. NULL not a built in const.
#include <string.h> // NULL is also defined in string.h, stdlib.h
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include "inttypes.h"
uint64_t vtop(uint64_t vaddr) {
FILE *pagemap;
uint64_t paddr = 0;
unsigned long long int offset = (vaddr / sysconf(_SC_PAGESIZE)) * sizeof(uint64_t);
uint64_t e;
// https://www.kernel.org/doc/Documentation/vm/pagemap.txt
if ((pagemap = fopen("/proc/self/pagemap", "r"))) {
if (lseek(fileno(pagemap), offset, SEEK_SET) == offset) {
if (fread(&e, sizeof(uint64_t), 1, pagemap)) {
if (e & (1ULL << 63)) { // page present ?
paddr = e & ((1ULL << 54) - 1); // pfn mask
paddr = paddr * sysconf(_SC_PAGESIZE);
// add offset within page
paddr = paddr | (vaddr & (sysconf(_SC_PAGESIZE) - 1));
printf(" paddr %lu \n", paddr);
}
else {
printf("page not found\n");
}
}
}
fclose(pagemap);
}
return paddr;
}
int main() {
int oflag = O_RDONLY;
const char *path = "file.json";
const int fd = open(path, oflag);
// use stat to find the file size
struct stat stat;
int ret = fstat(fd, &stat);
int mflags = MAP_PRIVATE; // information about handling the mapped data
int mprot = PROT_READ|PROT_WRITE; // access permissions to the data being mapped
size_t size = stat.st_size;
void *addr = mmap(NULL, size, mprot, mflags, fd, 0);
printf("virtual addres is %p\n", addr);
printf("physical addres is %ld\n", vtop((uint64_t)addr));
return 0;
}
When I use malloc, instead of mmap, I get the physical address as 0x670
what is the speciality of this number?