1
#define _XOPEN_SOURCE 500
7
#include <sys/sysinfo.h>
9
// 8 bytes page tables + 64 bytes mem map
10
// However may be mem_map (struct page) is already excluded?
11
#define BYTES_PER_PAGE 8
13
int main(int argc, char *argv[]) {
21
printf("Usage: %s [+]<GB>\n", argv[0]);
22
printf(" + : lock this amount of memory\n");
23
printf(" = : total memory after lock\n");
24
printf(" - : free memory after lock [default]\n");
28
f = fopen("/proc/sys/vm/drop_caches", "w");
30
printf("Failed to drop caches...\n");
38
printf("sysinfo failed with errno: %i\n", errno);
43
if ((argv[1][0] < '0')||(argv[1][0] > '9'))
44
size = atol(argv[1]+1) * 1024 * 1024 * 1024;
46
size = atol(argv[1]) * 1024 * 1024 * 1024;
48
if (argv[1][0]=='+') {
49
} else if (argv[1][0]=='=') {
50
size_t page_size = getpagesize();
54
pages = (info.totalram * info.mem_unit) / page_size;
55
page_tables = pages * BYTES_PER_PAGE;
57
printf("Detected %zu units of memory, unit size %u\n", info.totalram, info.mem_unit);
58
printf("Expected size of page tables: %zu MB, \n", page_tables / 1024 / 1024);
59
printf("Leaving aside %zu bytes\n", size);
61
if (info.totalram * info.mem_unit < size) {
62
printf("Requested more memory (%zu GB) when available (%zu GB)\n", size / 1024 / 1024 / 1024, info.totalram * info.mem_unit / 1024 / 1024 / 1024);
65
size = info.totalram * info.mem_unit - size - page_tables;
67
if (info.freeram*info.mem_unit < size) {
68
printf("Requested more memory (%zu GB) when is currently free (%zu GB)\n", size / 1024 / 1024 / 1024, info.freeram * info.mem_unit / 1024 / 1024 / 1024);
72
size = info.freeram * info.mem_unit - size;
77
printf("Trying to get %zu bytes\n", size);
81
printf("Allocation failed\n");
86
err = mlock(buf, size);
88
printf("Locking memory failed, errno: %i\n", errno);
92
printf("Locked %zu GB memory\n", size/1024/1024/1024);
b'\\ No newline at end of file'