aboutsummaryrefslogtreecommitdiffstats
path: root/usemem_ksm.c
blob: 0d3ff1deeff90cfb2c06650dd36652cbb1d06151 (plain)
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
/*
 * usemem_ksm.c exercises the ksm.c file in the mm
 *
 * It takes one argument 'size' and mmaps anonymous memory of 'size'
 *
 * into the process virtual address space.
 */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>

#define SLEEP_TIME (60)

void usage(char *name)
{
	fprintf(stderr, "usage: %s SIZE\n", name);
	exit(1);
}

/* calls madvise with the the specified flag */

void call_madvise (unsigned long *pointer_to_address, unsigned long size, int advise)
{
	if ((madvise(pointer_to_address, size, advise)) == -1) {
		fprintf(stderr, "madvise failed with error : %s\n", strerror(errno));
		munmap(pointer_to_address, size);
		exit(1);
	}
}

int main(int argc, char *argv[])
{
	/*int PS = getpagesize();*/

	if (argc != 2) usage(argv[0]);

	unsigned long size = atoi(argv[1]);

	unsigned long *p;

	p = mmap(NULL, size, PROT_READ|PROT_WRITE,
		  MAP_POPULATE|MAP_ANON|MAP_PRIVATE, -1, 0);

	if (p == MAP_FAILED) {
		fprintf(stderr, "anon  mmap failed: %s\n", strerror(errno));
		exit(1);
	}

	/* call madvise with MERGEABLE flags to enable ksm scanning */
	call_madvise(p, size, MADV_MERGEABLE);

	/* sleep for SLEEP_TIME seconds*/
	sleep(SLEEP_TIME);

	/* disable the MERGEABLE flag*/
	call_madvise(p, size, MADV_UNMERGEABLE);

	/* HUGEPAGE advised -- not related to ksm */
	call_madvise(p, size, MADV_HUGEPAGE);

	/* unmap mapped memory */
	munmap(p, size);
	return 0;

}