Skip to content

Instantly share code, notes, and snippets.

@heiher
Created November 16, 2022 03:22
Show Gist options
  • Save heiher/72919fae6b53f04cac606a9631100506 to your computer and use it in GitHub Desktop.
Save heiher/72919fae6b53f04cac606a9631100506 to your computer and use it in GitHub Desktop.
COW testcase for Huge pages
/*
============================================================================
Name : cow-huge.c
Author : hev <r@hev.cc>
Copyright : Copyright (c) 2022 hev
Description : COW testcase for Huge pages
============================================================================
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/wait.h>
static inline void
pagefill (void *ptr, size_t size, int val)
{
unsigned long i;
for (i = 0; i < size; i += 4096)
*(volatile int *)(ptr + i) = val;
}
static inline unsigned long
checksum (void *ptr, size_t size)
{
unsigned long sum = 0;
unsigned long i;
for (i = 0; i < size; i += sizeof(unsigned long))
sum += *(volatile unsigned long *)(ptr + i);
return sum;
}
int
main (int argc, char *argv[])
{
const size_t memsize = 32 * 1024 * 1024UL;
pid_t pid;
void *ptr;
ptr = mmap (NULL, memsize, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (ptr == MAP_FAILED) {
return -1;
}
for (;;) {
pagefill (ptr, memsize, 0);
pid = fork ();
switch (pid) {
case -1:
return -2;
case 0:
printf ("c sum: %lu\n", checksum (ptr, memsize));
return 0;
default:
pagefill (ptr, memsize, 1);
waitpid (pid, NULL, 0);
printf ("p sum: %lu\n", checksum (ptr, memsize));
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment