]> git.saurik.com Git - apple/xnu.git/blame - tools/tests/perf_index/test_fault_helper.c
xnu-4903.241.1.tar.gz
[apple/xnu.git] / tools / tests / perf_index / test_fault_helper.c
CommitLineData
fe8ab488
A
1#include "test_fault_helper.h"
2#include "fail.h"
3#include <sys/mman.h>
4#include <stdlib.h>
5#include <unistd.h>
6#include <assert.h>
7#include <TargetConditionals.h>
8
5ba3f43e
A
9#if TARGET_OS_EMBEDDED
10#define MEMSIZE (1L<<28)
11#else
fe8ab488 12#define MEMSIZE (1L<<30)
5ba3f43e 13#endif
fe8ab488
A
14
15static char* memblock;
16
17int test_fault_setup() {
18 char *ptr;
19 int pgsz = getpagesize();
20 int retval;
21
22 memblock = (char *)mmap(NULL, MEMSIZE, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
23 VERIFY(memblock != MAP_FAILED, "mmap failed");
24
25 /* make sure memory is paged */
26 for(ptr = memblock; ptr<memblock+MEMSIZE; ptr+= pgsz) {
27 *ptr = 1;
28 }
29
30 /* set to read only, then back to read write so it faults on first write */
31 retval = mprotect(memblock, MEMSIZE, PROT_READ);
32 VERIFY(retval == 0, "mprotect failed");
33
34 retval = mprotect(memblock, MEMSIZE, PROT_READ | PROT_WRITE);
35 VERIFY(retval == 0, "mprotect failed");
36
37 return PERFINDEX_SUCCESS;
38}
39
40int test_fault_helper(int thread_id, int num_threads, long long length, testtype_t testtype) {
41 char *ptr;
42 int pgsz = getpagesize();
43 int retval;
44
45 long long num_pages = MEMSIZE / pgsz;
46 long long region_len = num_pages/num_threads;
47 long long region_start = region_len * thread_id;
48 long long region_end;
49
50 if(thread_id < num_pages % num_threads) {
51 region_start += thread_id;
52 region_len++;
53 }
54 else {
55 region_start += num_pages % num_threads;
56 }
57
58 region_start *= pgsz;
59 region_len *= pgsz;
60 region_end = region_start + region_len;
61
62 long long left = length;
63
64 while(1) {
65 for(ptr = memblock+region_start; ptr<memblock+region_end; ptr+= pgsz) {
66 *ptr = 1;
67 left--;
68 if(left==0)
69 break;
70 }
71
72 if(left==0)
73 break;
74
75 if(testtype == TESTFAULT) {
76 retval = mprotect(memblock+region_start, region_len, PROT_READ) == 0;
77 VERIFY(retval == 0, "mprotect failed");
78 retval = mprotect(memblock+region_start, region_len, PROT_READ | PROT_WRITE) == 0;
79 VERIFY(retval == 0, "mprotect failed");
80 }
81
82 else if(testtype == TESTZFOD) {
83 retval = munmap(memblock+region_start, region_len) == 0;
84 VERIFY(retval == 0, "munmap failed");
85 ptr = mmap(memblock+region_start, region_len, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE | MAP_FIXED, -1, 0);
86 VERIFY(ptr != 0, "mmap failed");
87 }
88 }
89 return PERFINDEX_SUCCESS;
90}