forked from sysprog21/fibdrv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mlock.c
72 lines (59 loc) · 2.19 KB
/
mlock.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Compile with 'gcc thisfile.c -lpthread -lrt -Wall'
#include "mlock.h"
#include <limits.h>
#include <malloc.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h> // Needed for mlockall()
#include <sys/resource.h> // needed for getrusage
#include <sys/time.h> // needed for getrusage
#include <unistd.h> // needed for sysconf(int name);
bool check_pagefault(int allowed_maj, int allowed_min)
{
static int last_majflt = 0, last_minflt = 0;
struct rusage usage;
bool res = true;
getrusage(RUSAGE_SELF, &usage);
printf("major: %ld minor: %ld\n", usage.ru_majflt - last_majflt,
usage.ru_minflt - last_minflt);
if ((usage.ru_majflt - last_majflt > allowed_maj) |
(usage.ru_minflt - last_minflt > allowed_min))
res = false;
last_majflt = usage.ru_majflt;
last_minflt = usage.ru_minflt;
return res;
}
void configure_malloc_behavior(void)
{
/* Now lock all current and future pages
from preventing of being paged */
if (mlockall(MCL_CURRENT | MCL_FUTURE))
perror("mlockall failed:");
/* Turn off malloc trimming.*/
mallopt(M_TRIM_THRESHOLD, -1);
/* Turn off mmap usage. */
mallopt(M_MMAP_MAX, 0);
}
void reserve_process_memory(int size)
{
int i;
char *buffer;
buffer = malloc(size);
/* Touch each page in this piece of memory to get it mapped into RAM */
for (i = 0; i < size; i += sysconf(_SC_PAGESIZE)) {
/* Each write to this buffer will generate a pagefault.
Once the pagefault is handled a page will be locked in
memory and never given back to the system. */
buffer[i] = 0;
}
/* buffer will now be released. As Glibc is configured such that it
never gives back memory to the kernel, the memory allocated above is
locked for this process. All malloc() and new() calls come from
the memory pool reserved and locked above. Issuing free() and
delete() does NOT make this locking undone. So, with this locking
mechanism we can build C++ applications that will never run into
a major/minor pagefault, even with swapping enabled. */
free(buffer);
}