When I create a copy-on-write mapping (a MAP_PRIVATE) using mmap, then some pages of this mapping will be copied as soon as I write to specific addresses. At a certain point in my program I would like to figure out which pages have actually been copied. There is a call, called ‘mincore’, but that only reports whether the page is in memory or not, which is not the same as the page being copied or not.
In order to figure out what pages have been copied, the pagemap and kpageflags can be used. Below a quick test to check whether a page is in memory ‘SWAPBACKED’ as it is called. One problem remains of course, which is the problem that kpageflags is only accessible to the root.
int main(int argc, char* argv)
unsigned long long pagesize=getpagesize();
int fd=open("test.dat", O_RDWR);
printf("Created test.dat testfile\n");
char* M=(char*)mmap(NULL, filesize, PROT_READ|PROT_WRITE, MAP_PRIVATE,fd,0);
printf("Successfully create private mapping\n");
The test setup contains 4 pages. page 0 and 2 are dirty
strcpy(M,"I feel so dirty\n");
strcpy(M+pagesize*2,"Christ on crutches\n");
page 3 has been read from.
page 1 will not be accessed
The pagemap file maps the process its virtual memory to actual pages, which can then be retrieved from the global kpageflags file later on. Read the file /usr/src/linux/Documentation/vm/pagemap.txt
unsigned long long target=((unsigned long)(void*)M)/pagesize;
err=lseek64(mapfd, target*8, SEEK_SET);
Here we read the page frame numbers for each of our virtual pages
unsigned long long page2pfn[pagecount];
printf("Could only read %d bytes\n",err);
Now we are about to read for each virtual frame, the actual pageflags
for(int i = 0 ; i < pagecount; i++)
unsigned long long v2a=page2pfn[i];
printf("Page: %d, flag %llx\n",i,page2pfn[i]);
if(v2a&0x8000000000000000LL) // Is the virtual page present ?
unsigned long long pfn=v2a&0x3fffffffffffffLL;
unsigned long long pf;
printf("pageflags are %llx with SWAPBACKED: %d\n",pf,(pf>>14)&1);
All in all, I’m not particularly happy with this approach since it requires access to a file that we in general can’t access and it is bloody complicated (how about a simple kernel call to retrieve the pageflags ?).