Skip to content

Instantly share code, notes, and snippets.

@rdunnington
Created April 29, 2024 06:47
Show Gist options
  • Select an option

  • Save rdunnington/fa646aa8103087902fcdff0b5b825c43 to your computer and use it in GitHub Desktop.

Select an option

Save rdunnington/fa646aa8103087902fcdff0b5b825c43 to your computer and use it in GitHub Desktop.
A program to test overcommit behavior on linux.
#include <sys/mman.h>
#include <stdio.h>
const size_t KB = 1024;
const size_t MB = KB * 1024;
const size_t GB = MB * 1024;
const int map = MAP_PRIVATE | MAP_ANONYMOUS;
const int fd = -1;
const int offset = 0;
void test_large_blocks(void)
{
#define UNIT(size) \
size_t unit = size; \
const char* unit_str = #size;
UNIT(GB)
size_t total = 16;
void* p = mmap(NULL, total * unit, PROT_NONE, map, fd, offset);
printf("%zu %s reservation at %p\n", total, unit_str, p);
if (p == MAP_FAILED)
{
return;
}
printf("mapping %zu reservation in 1 %s chunks...\n", total, unit_str);
size_t total_mapped = 0;
for (size_t i = 0; i < total; i += 1)
{
void* pp = (char*)p + (i * unit);
void* m = mmap(pp, unit, PROT_WRITE | PROT_READ, map, fd, offset);
if (m != MAP_FAILED)
{
++total_mapped;
}
else
{
break;
}
}
printf("mapped %zu / %zu %s\n", total_mapped, total, unit_str);
munmap(p, total * unit);
}
void alloc_individual_blocks(void)
{
size_t increment = 2;
size_t total_mapped = 0;
for (size_t i = 0; i < GB * 8; i += (increment * MB))
{
void* m = mmap(NULL, increment * MB, PROT_WRITE | PROT_READ, map, fd, offset);
if (m != MAP_FAILED)
{
total_mapped += increment;
}
else
{
break;
}
}
printf("total mapped: %zu MB\n", total_mapped);
}
int main(void)
{
FILE* overcommit_status = fopen("/proc/sys/vm/overcommit_memory", "rb");
char buf[256];
int read = fread(buf, 1, sizeof(buf), overcommit_status);
buf[read] = 0;
fclose(overcommit_status);
printf("overcommit_status: %s\n", buf);
printf("==================================\n");
printf("running test: alloc_large_blocks\n");
printf("==================================\n");
test_large_blocks();
printf("==================================\n");
printf("running test: alloc_individual_blocks\n");
printf("==================================\n");
alloc_individual_blocks();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment