xref: /aosp_15_r20/external/ltp/testcases/kernel/mem/mmapstress/mmapstress01.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) International Business Machines  Corp., 2003
4  * 01/02/2003	Port to LTP [email protected]
5  * 06/30/2001	Port to Linux	[email protected]
6  * 10/03/2022	Refactor to LTP framework	[email protected]
7  */
8 /*\
9  * [Description]
10  * This test stresses mmaps, without dealing with fragments or anything!
11  * It forks a specified number of children,
12  * all of whom mmap the same file, make a given number of accesses
13  * to random pages in the map (reading & writing and comparing data).
14  * Then the child exits and the parent forks another to take its place.
15  * Each time a child is forked, it stats the file and maps the full
16  * length of the file.
17  *
18  * This program continues to run until it either receives a SIGINT,
19  * or times out (if a timeout value is specified).  When either of
20  * these things happens, it cleans up its kids, then checks the
21  * file to make sure it has the correct data.
22  */
23 
24 #define _GNU_SOURCE 1
25 #include <stdio.h>
26 #include <fcntl.h>
27 #include <signal.h>
28 #include <sys/mman.h>
29 #include <sys/wait.h>
30 #include <sys/stat.h>
31 #include <unistd.h>
32 #include <stdlib.h>
33 #include <errno.h>
34 #include <sys/types.h>
35 #include <limits.h>
36 #include <float.h>
37 #include "tst_test.h"
38 
39 #if _FILE_OFFSET_BITS == 64
40 # define FSIZE_MIN LONG_MIN
41 # define FSIZE_MAX LONG_MAX
42 #else
43 # define FSIZE_MIN INT_MIN
44 # define FSIZE_MAX INT_MAX
45 #endif
46 #define MAXLOOPS	500	/* max pages for map children to write */
47 #define TEST_FILE	"mmapstress01.out"
48 
49 #ifdef roundup
50 #undef roundup
51 #endif
52 #define roundup(x, y)	((((x)+((y)-1))/(y))*(y))
53 
54 static unsigned int initrand(void);
55 static void sighandler(int);
56 
57 static char *debug;
58 static char *do_sync;
59 static char *do_offset;
60 static char *opt_filesize;
61 static char *opt_nprocs;
62 static char *opt_pattern;
63 static char *opt_sparseoffset;
64 static char *randloops;
65 
66 static int fd;
67 static volatile int finished;
68 static int nprocs;
69 static long long filesize = 4096;
70 static long long sparseoffset;
71 static size_t pagesize;
72 static int pattern;
73 
setup(void)74 static void setup(void)
75 {
76 	struct sigaction sa;
77 
78 	sa.sa_handler = sighandler;
79 	sa.sa_flags = 0;
80 	SAFE_SIGEMPTYSET(&sa.sa_mask);
81 	SAFE_SIGACTION(SIGINT, &sa, 0);
82 	SAFE_SIGACTION(SIGQUIT, &sa, 0);
83 	SAFE_SIGACTION(SIGTERM, &sa, 0);
84 	SAFE_SIGACTION(SIGALRM, &sa, 0);
85 
86 	pagesize = sysconf(_SC_PAGE_SIZE);
87 
88 	if (tst_parse_filesize(opt_filesize, &filesize, 0, FSIZE_MAX))
89 		tst_brk(TBROK, "invalid initial filesize '%s'", opt_filesize);
90 
91 	if (tst_parse_filesize(opt_sparseoffset, &sparseoffset, FSIZE_MIN, FSIZE_MAX))
92 		tst_brk(TBROK, "invalid sparse offset '%s'", opt_sparseoffset);
93 	if (sparseoffset % pagesize != 0)
94 		tst_brk(TBROK, "sparseoffset must be pagesize multiple");
95 
96 	if (tst_parse_int(opt_nprocs, &nprocs, 0, 255))
97 		tst_brk(TBROK, "invalid number of mapping children '%s'",
98 			opt_nprocs);
99 	if (!opt_nprocs)
100 		nprocs = MAX(MIN(tst_ncpus() - 1L, 20L), 1L);
101 
102 	if (tst_parse_int(opt_pattern, &pattern, 0, 255))
103 		tst_brk(TBROK, "invalid pattern '%s'", opt_pattern);
104 	if (!opt_pattern)
105 		pattern = initrand() & 0xff;
106 
107 	tst_res(TINFO, "creating file <%s> with %lld bytes, pattern %d",
108 		TEST_FILE, filesize, pattern);
109 }
110 
cleanup(void)111 static void cleanup(void)
112 {
113 	if (fd > 0)
114 		SAFE_CLOSE(fd);
115 }
116 
117 /*
118  * Child process that reads/writes map.  The child stats the file
119  * to determine the size, maps the size of the file, then reads/writes
120  * its own locations on random pages of the map (its locations being
121  * determined based on nprocs & procno).  After a specific number of
122  * iterations, it exits.
123  */
child_mapper(char * file,unsigned int procno,unsigned int nprocs)124 static void child_mapper(char *file, unsigned int procno, unsigned int nprocs)
125 {
126 	struct stat statbuf;
127 	off_t filesize;
128 	off_t offset;
129 	size_t validsize;
130 	size_t mapsize;
131 	char *maddr = NULL, *paddr;
132 	unsigned int randpage;
133 	unsigned int seed;
134 	unsigned int loopcnt;
135 	unsigned int nloops;
136 	unsigned int mappages;
137 	unsigned int i;
138 
139 	seed = initrand();
140 
141 	SAFE_STAT(file, &statbuf);
142 	filesize = statbuf.st_size;
143 
144 	fd = SAFE_OPEN(file, O_RDWR);
145 
146 	if (statbuf.st_size - sparseoffset > UINT_MAX)
147 		tst_brk(TBROK, "size_t overflow when setting up map");
148 	mapsize = (size_t) (statbuf.st_size - sparseoffset);
149 	mappages = roundup(mapsize, pagesize) / pagesize;
150 	offset = sparseoffset;
151 	if (do_offset) {
152 		int pageoffset = lrand48() % mappages;
153 		int byteoffset = pageoffset * pagesize;
154 
155 		offset += byteoffset;
156 		mapsize -= byteoffset;
157 		mappages -= pageoffset;
158 	}
159 	nloops = (randloops) ? (lrand48() % MAXLOOPS) : MAXLOOPS;
160 
161 	if (debug)
162 		tst_res(TINFO, "child %d (pid %d): seed %d, fsize %lld, mapsize %ld, off %lld, loop %d",
163 			procno, getpid(), seed, (long long)filesize,
164 			(long)mapsize, (long long)offset / pagesize, nloops);
165 
166 	maddr = SAFE_MMAP(0, mapsize, PROT_READ | PROT_WRITE, MAP_SHARED, fd,
167 			  offset);
168 	SAFE_CLOSE(fd);
169 
170 	for (loopcnt = 0; loopcnt < nloops; loopcnt++) {
171 		randpage = lrand48() % mappages;
172 		paddr = maddr + (randpage * pagesize);	/* page address */
173 
174 		if (randpage < mappages - 1 || !(mapsize % pagesize))
175 			validsize = pagesize;
176 		else
177 			validsize = mapsize % pagesize;
178 
179 		for (i = procno; i < validsize; i += nprocs) {
180 			if (*((unsigned char *)(paddr + i))
181 			    != ((procno + pattern) & 0xff))
182 				tst_brk(TFAIL, "child %d: invalid data <x%x>\n"
183 					" at pg %d off %d, exp <x%x>", procno,
184 					*((unsigned char *)(paddr + i)),
185 					randpage, i, (procno + pattern) & 0xff);
186 
187 			*(paddr + i) = (procno + pattern) & 0xff;
188 		}
189 	}
190 
191 	if (do_sync) {
192 		randpage = lrand48() % mappages;
193 		paddr = maddr + (randpage * pagesize);	/* page address */
194 		SAFE_MSYNC(paddr, (mappages - randpage) * pagesize, MS_SYNC);
195 	}
196 
197 	SAFE_MUNMAP(maddr, mapsize);
198 	exit(0);
199 }
200 
201 /* Make sure file has all the correct data. */
fileokay(char * file,unsigned char * expbuf)202 static void fileokay(char *file, unsigned char *expbuf)
203 {
204 	int cnt;
205 	size_t mapsize;
206 	struct stat statbuf;
207 	unsigned char readbuf[pagesize];
208 	unsigned int i, j;
209 	unsigned int mappages;
210 
211 	fd = SAFE_OPEN(file, O_RDONLY);
212 
213 	SAFE_FSTAT(fd, &statbuf);
214 	SAFE_LSEEK(fd, sparseoffset, SEEK_SET);
215 
216 	if (statbuf.st_size - sparseoffset > UINT_MAX)
217 		tst_brk(TBROK, "size_t overflow when setting up map");
218 	mapsize = (size_t) (statbuf.st_size - sparseoffset);
219 
220 	mappages = roundup(mapsize, pagesize) / pagesize;
221 
222 	for (i = 0; i < mappages; i++) {
223 		cnt = SAFE_READ(0, fd, readbuf, pagesize);
224 		if ((unsigned int)cnt != pagesize) {
225 			/* Okay if at last page in file... */
226 			if ((i * pagesize) + cnt != mapsize)
227 				tst_brk(TFAIL, "missing data: read %lu of %ld bytes",
228 					(i * pagesize) + cnt, (long)mapsize);
229 		}
230 		/* Compare read bytes of data. */
231 		for (j = 0; j < (unsigned int)cnt; j++) {
232 			if (expbuf[j] != readbuf[j])
233 				tst_brk(TFAIL,
234 					"read bad data: exp %c got %c, pg %d off %d, (fsize %lld)",
235 					expbuf[j], readbuf[j], i, j,
236 					(long long)statbuf.st_size);
237 		}
238 	}
239 	SAFE_CLOSE(fd);
240 }
241 
sighandler(int sig LTP_ATTRIBUTE_UNUSED)242 static void sighandler(int sig LTP_ATTRIBUTE_UNUSED)
243 {
244 	finished++;
245 }
246 
initrand(void)247 static unsigned int initrand(void)
248 {
249 	unsigned int seed;
250 
251 	/*
252 	 * Use srand/rand to diffuse the information from the
253 	 * time and pid.  If you start several processes, then
254 	 * the time and pid information don't provide much
255 	 * variation.
256 	 */
257 	srand((unsigned int)getpid());
258 	seed = rand();
259 	srand((unsigned int)time(NULL));
260 	seed = (seed ^ rand()) % 100000;
261 	srand48((long)seed);
262 	return seed;
263 }
264 
run(void)265 static void run(void)
266 {
267 	int c;
268 	int i;
269 	int wait_stat;
270 	off_t bytes_left;
271 	pid_t pid;
272 	pid_t *pidarray;
273 	size_t write_cnt;
274 	unsigned char data;
275 	unsigned char *buf;
276 
277 	alarm(tst_remaining_runtime());
278 
279 	finished = 0;
280 	fd = SAFE_OPEN(TEST_FILE, O_CREAT | O_TRUNC | O_RDWR, 0664);
281 	buf = SAFE_MALLOC(pagesize);
282 	pidarray = SAFE_MALLOC(nprocs * sizeof(pid_t));
283 
284 	for (i = 0; i < nprocs; i++)
285 		*(pidarray + i) = 0;
286 
287 	for (i = 0, data = 0; i < (int)pagesize; i++) {
288 		*(buf + i) = (data + pattern) & 0xff;
289 		if (++data == nprocs)
290 			data = 0;
291 	}
292 	SAFE_LSEEK(fd, (off_t)sparseoffset, SEEK_SET);
293 	for (bytes_left = filesize; bytes_left; bytes_left -= c) {
294 		write_cnt = MIN((long long)pagesize, (long long)bytes_left);
295 		c = SAFE_WRITE(1, fd, buf, write_cnt);
296 	}
297 	SAFE_CLOSE(fd);
298 
299 	for (i = 0; i < nprocs; i++) {
300 		pid = SAFE_FORK();
301 
302 		if (pid == 0) {
303 			child_mapper(TEST_FILE, (unsigned int)i, (unsigned int)nprocs);
304 			exit(0);
305 		} else {
306 			pidarray[i] = pid;
307 		}
308 	}
309 
310 	while (!finished) {
311 		pid = wait(&wait_stat);
312 		if (pid != -1) {
313 			if (!WIFEXITED(wait_stat)
314 			    || WEXITSTATUS(wait_stat) != 0)
315 				tst_brk(TBROK, "child exit with err <x%x>",
316 					wait_stat);
317 			for (i = 0; i < nprocs; i++)
318 				if (pid == pidarray[i])
319 					break;
320 			if (i == nprocs)
321 				tst_brk(TBROK, "unknown child pid %d, <x%x>",
322 					pid, wait_stat);
323 
324 			pid = SAFE_FORK();
325 			if (pid == 0) {
326 				child_mapper(TEST_FILE, (unsigned int)i, (unsigned int)nprocs);
327 				exit(0);
328 			} else {
329 				pidarray[i] = pid;
330 			}
331 		} else {
332 			if (errno != EINTR || !finished)
333 				tst_brk(TBROK | TERRNO,
334 					"unexpected wait error");
335 		}
336 	}
337 	alarm(0);
338 
339 	fileokay(TEST_FILE, buf);
340 	tst_res(TPASS, "file has expected data");
341 }
342 
343 static struct tst_test test = {
344 	.test_all = run,
345 	.setup = setup,
346 	.options = (struct tst_option[]) {
347 		{"d", &debug, "Enable debug output"},
348 		{"f:", &opt_filesize, "Initial filesize (default 4096)"},
349 		{"m", &do_sync, "Do random msync/fsyncs as well"},
350 		{"o", &do_offset, "Randomize the offset of file to map"},
351 		{"p:", &opt_nprocs,
352 		 "Number of mapping children to create (default 1 < ncpus < 20)"},
353 		{"P:", &opt_pattern,
354 		 "Use a fixed pattern (default random)"},
355 		{"r", &randloops,
356 		 "Randomize number of pages map children check (random % 500), "
357 		 "otherwise each child checks 500 pages"},
358 		{"S:", &opt_sparseoffset,
359 		 "When non-zero, causes the sparse area to be left before the data, "
360 		 "so that the actual initial filesize is sparseoffset + filesize "
361 		 "(default 0)"},
362 		{},
363 	},
364 	.cleanup = cleanup,
365 	.max_runtime = 12,
366 	.needs_tmpdir = 1,
367 	.forks_child = 1,
368 };
369