/perf/perftools

To get this branch, use:
bzr branch http://darksoft.org/webbzr/perf/perftools
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/mman.h>
#include <sys/sysinfo.h>

    // 8 bytes page tables + 64 bytes mem map
    // However may be mem_map (struct page) is already excluded?
#define BYTES_PER_PAGE 8

int main(int argc, char *argv[]) {
    int err;
    size_t size;
    void *buf;
    FILE *f;
    struct sysinfo info;
    
    if (argc < 2) {
	printf("Usage: %s [+]<GB>\n", argv[0]);
	printf("  + : lock this amount of memory\n");
	printf("  = : total memory after lock\n");
	printf("  - : free memory after lock [default]\n");
	exit(0);
    }

    f = fopen("/proc/sys/vm/drop_caches", "w");
    if (!f) {
	printf("Failed to drop caches...\n");
	exit(-1);
    }
    fprintf(f, "3\n");
    fclose(f);

    err = sysinfo(&info);
    if (err) {
        printf("sysinfo failed with errno: %i\n", errno);
        exit(-1);
    }

    
    if ((argv[1][0] < '0')||(argv[1][0] > '9'))
	size = atol(argv[1]+1) * 1024 * 1024 * 1024;
    else
	size = atol(argv[1]) * 1024 * 1024 * 1024;
    
    if  (argv[1][0]=='+') {
    } else if  (argv[1][0]=='=') {
	size_t page_size = getpagesize();
	size_t pages;
	size_t page_tables;
	
	pages = (info.totalram * info.mem_unit) / page_size;
	page_tables = pages * BYTES_PER_PAGE;
	
	printf("Detected %zu units of memory, unit size %u\n", info.totalram, info.mem_unit);
	printf("Expected size of page tables: %zu MB, \n", page_tables / 1024 / 1024);
	printf("Leaving aside %zu bytes\n", size);

	if (info.totalram * info.mem_unit < size) {
	    printf("Requested more memory (%zu GB) when available (%zu GB)\n", size / 1024 / 1024 / 1024, info.totalram * info.mem_unit / 1024 / 1024 / 1024);
	    exit(-1);
	}
	size = info.totalram * info.mem_unit - size - page_tables;
    } else {
	if (info.freeram*info.mem_unit < size) {
	    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);
	    exit(-1);
	}

	size = info.freeram * info.mem_unit - size;
    }
    
    if (!size) exit(0);

    printf("Trying to get %zu bytes\n", size);

    buf = malloc(size);
    if (!buf) {
	printf("Allocation failed\n");
	exit(-1);
    }
    
    
    err = mlock(buf, size);
    if (err) {
	printf("Locking memory failed, errno: %i\n", errno);
	exit(-1);
    }
    
    printf("Locked %zu GB memory\n", size/1024/1024/1024);
    while (1) sleep(60);
}