Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a simple "page fault generator"?

For my course project on Linux Kernel, I need to simulate a situation where there is a lot of page swapping due to low memory.

I want to write a program which needs a lot of physical memory, so that pages accessed by this program have to be swapped in and out multiple times.

like image 262
Neo Avatar asked Oct 31 '22 05:10

Neo


1 Answers

Of, so first of all you really need to allocate a buffer larger than your RAM size. I hope you run on a 64bit OS or you have PAE enabled. If have let's say 4GB of RAM, you need something like:

double* pBigArray = (double*)malloc(sizeof(double) * 536870912); 
// You actually need more than that. This is just 4GB.

Now, just having an array, larger than your RAM size is not enough. It matters how you access it. If you just read elements consecutively, the hardware prefetchers in your CPU will bring some of the data your program will read, into the cache.

To generate many page faults, you need to read from an address that is not in the RAM.

To do that this is a simple method, by reading from the array randomly:

double lfBigChecksum = 0.0;
while (true)
{
   int iIndex = rand() % BUFFER_SIZE;
   lfBigChecksum += pBigArray[iIndex];
}

If you have an array of 8GB and 4GB of RAM, half of the reads will be page faults (and served from the swap space in the hard disk).

like image 110
VAndrei Avatar answered Nov 15 '22 06:11

VAndrei