1 /* $OpenBSD: mmaptest.c,v 1.7 2019/05/09 23:13:31 guenther Exp $ */
2 /*
3 * Written by Artur Grabowski <art@openbsd.org>, 2001 Public Domain
4 */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <unistd.h>
9 #include <err.h>
10 #include <string.h>
11
12 #include <sys/types.h>
13 #include <sys/mman.h>
14
15 /*
16 * Map the same physical page in two places in memory.
17 * Should cause a cache alias on virtual-aliased cache architectures.
18 */
19
20 #define MAGIC "The voices in my head are trying to ignore me."
21
22 int
main(int argc,char * argv[])23 main(int argc, char *argv[])
24 {
25 char fname[25] = "/tmp/mmaptestXXXXXXXXXX";
26 int page_size;
27 int fd;
28 char *v1, *v2;
29
30 if ((fd = mkstemp(fname)) < 0)
31 err(1, "mkstemp");
32
33 if (remove(fname) < 0)
34 err(1, "remove");
35
36 if ((page_size = sysconf(_SC_PAGESIZE)) < 0)
37 err(1, "sysconf");
38
39 if (ftruncate(fd, 2 * page_size) < 0)
40 err(1, "ftruncate");
41
42 /* map two pages, then map the first page over the second */
43
44 v1 = mmap(NULL, 2 * page_size, PROT_READ|PROT_WRITE,
45 MAP_SHARED, fd, 0);
46 if (v1 == MAP_FAILED)
47 err(1, "mmap 1");
48
49 /* No need to unmap, mmap is supposed to do that for us if MAP_FIXED */
50
51 v2 = mmap(v1 + page_size, page_size, PROT_READ|PROT_WRITE,
52 MAP_SHARED|MAP_FIXED, fd, 0);
53 if (v2 == MAP_FAILED)
54 err(1, "mmap 2");
55
56 memcpy(v1, MAGIC, sizeof(MAGIC));
57
58 if (memcmp(v2, MAGIC, sizeof(MAGIC)) != 0)
59 errx(1, "comparison 1 failed");
60
61 if (memcmp(v1, v2, sizeof(MAGIC)) != 0)
62 errx(1, "comparison 2 failed");
63
64 if (munmap(v1, 2 * page_size) < 0)
65 errx(1, "munmap");
66
67 close(fd);
68
69 return 0;
70 }
71
72