1/* IBM Corporation */
2/* 01/02/2003	Port to LTP avenkat@us.ibm.com */
3/* 06/30/2001	Port to Linux	nsharoff@us.ibm.com */
4/*
5 *   Copyright (c) International Business Machines  Corp., 2003
6 *
7 *
8 *   This program is free software;  you can redistribute it and/or modify
9 *   it under the terms of the GNU General Public License as published by
10 *   the Free Software Foundation; either version 2 of the License, or
11 *   (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY;  without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
16 *   the GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program;  if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#define _GNU_SOURCE 1
24#include <stdio.h>
25#include <fcntl.h>
26#include <signal.h>
27#include <sys/mman.h>
28#include <sys/wait.h>
29#include <sys/stat.h>
30#include <unistd.h>
31#include <stdlib.h>
32#include <errno.h>
33#include <sys/types.h>
34#include <limits.h>
35/*****  LTP Port        *****/
36#include "test.h"
37#define FAILED 0
38#define PASSED 1
39
40int local_flag = PASSED;
41char *TCID = "mmapstress01";	//tmnoextend
42FILE *temp;
43int TST_TOTAL = 1;
44
45int anyfail();
46void ok_exit();
47/*****  **      **      *****/
48
49/*
50 *  This test stresses mmaps, without dealing with fragments or anything!
51 *  It forks a specified number of children,
52 *  all of whom mmap the same file, make a given number of accesses
53 *  to random pages in the map (reading & writing and comparing data).
54 *  Then the child exits and the parent forks another to take its place.
55 *  Each time a child is forked, it stats the file and maps the full
56 *  length of the file.
57 *
58 *  This program continues to run until it either receives a SIGINT,
59 *  or times out (if a timeout value is specified).  When either of
60 *  these things happens, it cleans up its kids, then checks the
61 *  file to make sure it has the correct data.
62 *
63 *  usage:
64 *	tmnoextend -p nprocs [-t minutes -f filesize -S sparseoffset
65 *			      -r -o -m -l -d]
66 *  where:
67 *	-p nprocs	- specifies the number of mapping children
68 *			  to create.  (nprocs + 1 children actually
69 *			  get created, since one is the writer child)
70 *	-t minutes	- specifies minutes to run.  If not specified,
71 *			  default is to run forever until a SIGINT
72 *			  is received.
73 *	-f filesize	- initial filesize (defaults to FILESIZE)
74 *	-S sparseoffset - when non-zero, causes a sparse area to
75 *			  be left before the data, meaning that the
76 *			  actual initial file size is sparseoffset +
77 *			  filesize.  Useful for testing large files.
78 *			  (default is 0).
79 *	-r		- randomize number of pages map children check.
80 *			  (random % MAXLOOPS).  If not specified, each
81 *			  child checks MAXLOOPS pages.
82 *	-o		- randomize offset of file to map. (default is 0)
83 *	-m		- do random msync/fsyncs as well
84 *	-l		- if set, the output file is not removed on
85 *			  program exit.
86 *	-d		- enable debug output
87 *
88 *  Compile with -DLARGE_FILE to enable file sizes > 2 GB.
89 */
90
91#define MAXLOOPS	500	/* max pages for map children to write */
92#define	FILESIZE	4096	/* initial filesize set up by parent */
93
94#ifdef roundup
95#undef roundup
96#endif
97#define roundup(x, y)	((((x)+((y)-1))/(y))*(y))
98#define min(x, y)	(((x) < (y)) ? (x) : (y))
99
100extern time_t time(time_t *);
101extern char *ctime(const time_t *);
102extern void *malloc(size_t);
103extern long lrand48(void);
104extern void srand(unsigned);
105extern void srand48(long);
106extern int rand(void);
107extern int atoi(const char *);
108
109char *usage =
110    "-p nprocs [-t minutes -f filesize -S sparseoffset -r -o -m -l -d]";
111
112typedef unsigned char uchar_t;
113#define SIZE_MAX UINT_MAX
114
115unsigned int initrand(void);
116void finish(int sig);
117void child_mapper(char *file, unsigned procno, unsigned nprocs);
118int fileokay(char *file, uchar_t * expbuf);
119int finished = 0;
120int leavefile = 0;
121
122int debug = 0;
123#ifdef LARGE_FILE
124off64_t filesize = FILESIZE;
125off64_t sparseoffset = 0;
126#else /* LARGE_FILE */
127off_t filesize = FILESIZE;
128off_t sparseoffset = 0;
129#endif /* LARGE_FILE */
130unsigned randloops = 0;
131unsigned dosync = 0;
132unsigned do_offset = 0;
133unsigned pattern = 0;
134
135int main(int argc, char *argv[])
136{
137	char *progname;
138	int fd;
139	int c;
140	extern char *optarg;
141	unsigned nprocs = 0;
142	unsigned procno;
143	pid_t *pidarray = NULL;
144	pid_t pid;
145	uchar_t *buf = NULL;
146	unsigned int seed;
147	int pagesize = sysconf(_SC_PAGE_SIZE);
148	float alarmtime = 0;
149	struct sigaction sa;
150	unsigned i;
151	int write_cnt;
152	uchar_t data;
153	int no_prob = 0;
154	int wait_stat;
155	time_t t;
156#ifdef LARGE_FILE
157	off64_t bytes_left;
158#else /* LARGE_FILE */
159	off_t bytes_left;
160#endif /* LARGE_FILE */
161	const char *filename = "mmapstress01.out";
162
163	progname = *argv;
164	tst_tmpdir();
165	if (argc < 2) {
166		tst_brkm(TBROK, NULL, "usage: %s %s\n", progname, usage);
167	}
168
169	while ((c = getopt(argc, argv, "S:omdlrf:p:t:")) != -1) {
170		switch (c) {
171		case 'd':
172			debug = 1;
173			break;
174		case 't':
175			alarmtime = atof(optarg) * 60;
176			break;
177		case 'p':
178			nprocs = atoi(optarg);
179			break;
180		case 'l':
181			leavefile = 1;
182			break;
183		case 'f':
184#ifdef LARGE_FILE
185			filesize = atoll(optarg);
186#else /* LARGE_FILE */
187			filesize = atoi(optarg);
188#endif /* LARGE_FILE */
189			if (filesize < 0) {
190				(void)fprintf(stderr, "error: negative "
191					      "filesize\n");
192				anyfail();
193			}
194			break;
195		case 'r':
196			randloops = 1;
197			break;
198		case 'm':
199			dosync = 1;
200			break;
201		case 'o':
202			do_offset = 1;
203			break;
204		case 'S':
205#ifdef LARGE_FILE
206			sparseoffset = atoll(optarg);
207#else /* LARGE_FILE */
208			sparseoffset = atoi(optarg);
209#endif /* LARGE_FILE */
210			if (sparseoffset % pagesize != 0) {
211				fprintf(stderr,
212					"sparseoffset must be pagesize multiple\n");
213				anyfail();
214			}
215			break;
216		default:
217			(void)fprintf(stderr, "usage: %s %s\n", progname,
218				      usage);
219			tst_exit();
220		}
221	}
222
223	/* nprocs is >= 0 since it's unsigned */
224	if (nprocs > 255) {
225		(void)fprintf(stderr, "invalid nprocs %d - (range 0-255)\n",
226			      nprocs);
227		anyfail();
228	}
229
230	(void)time(&t);
231
232	seed = initrand();
233	pattern = seed & 0xff;
234
235	if (debug) {
236#ifdef LARGE_FILE
237		(void)printf("creating file <%s> with %Ld bytes, pattern %d\n",
238			     filename, filesize, pattern);
239#else /* LARGE_FILE */
240		(void)printf("creating file <%s> with %ld bytes, pattern %d\n",
241			     filename, filesize, pattern);
242#endif /* LARGE_FILE */
243		if (alarmtime)
244			(void)printf("running for %f minutes\n",
245				     alarmtime / 60);
246		else
247			(void)printf("running with no time limit\n");
248	}
249
250	/*
251	 *  Plan for death by signal.  User may have specified
252	 *  a time limit, in which set an alarm and catch SIGALRM.
253	 *  Also catch and cleanup with SIGINT.
254	 */
255	sa.sa_handler = finish;
256	sa.sa_flags = 0;
257	if (sigemptyset(&sa.sa_mask)) {
258		perror("sigemptyset error");
259		goto cleanup;
260	}
261
262	if (sigaction(SIGINT, &sa, 0) == -1) {
263		perror("sigaction error SIGINT");
264		goto cleanup;
265	}
266	if (sigaction(SIGQUIT, &sa, 0) == -1) {
267		perror("sigaction error SIGQUIT");
268		goto cleanup;
269	}
270	if (sigaction(SIGTERM, &sa, 0) == -1) {
271		perror("sigaction error SIGTERM");
272		goto cleanup;
273	}
274
275	if (alarmtime) {
276		if (sigaction(SIGALRM, &sa, 0) == -1) {
277			perror("sigaction error");
278			goto cleanup;
279		}
280		(void)alarm(alarmtime);
281	}
282#ifdef LARGE_FILE
283	if ((fd = open64(filename, O_CREAT | O_TRUNC | O_RDWR, 0664)) == -1) {
284#else /* LARGE_FILE */
285	if ((fd = open(filename, O_CREAT | O_TRUNC | O_RDWR, 0664)) == -1) {
286#endif /* LARGE_FILE */
287		perror("open error");
288		anyfail();
289	}
290
291	if ((buf = malloc(pagesize)) == NULL
292	    || (pidarray = malloc(nprocs * sizeof(pid_t))) == NULL) {
293		perror("malloc error");
294		anyfail();
295	}
296
297	for (i = 0; i < nprocs; i++)
298		*(pidarray + i) = 0;
299
300	for (i = 0, data = 0; i < pagesize; i++) {
301		*(buf + i) = (data + pattern) & 0xff;
302		if (++data == nprocs)
303			data = 0;
304	}
305#ifdef LARGE_FILE
306	if (lseek64(fd, sparseoffset, SEEK_SET) < 0) {
307#else /* LARGE_FILE */
308	if (lseek(fd, sparseoffset, SEEK_SET) < 0) {
309#endif /* LARGE_FILE */
310		perror("lseek");
311		anyfail();
312	}
313	for (bytes_left = filesize; bytes_left; bytes_left -= c) {
314		write_cnt = min(pagesize, bytes_left);
315		if ((c = write(fd, buf, write_cnt)) != write_cnt) {
316			if (c == -1) {
317				perror("write error");
318			} else {
319				(void)fprintf(stderr, "write: wrote %d of %d "
320					      "bytes\n", c, write_cnt);
321			}
322			(void)close(fd);
323			(void)unlink(filename);
324			anyfail();
325		}
326	}
327
328	(void)close(fd);
329
330	/*
331	 *  Fork off mmap children.
332	 */
333	for (procno = 0; procno < nprocs; procno++) {
334		switch (pid = fork()) {
335
336		case -1:
337			perror("fork error");
338			goto cleanup;
339
340		case 0:
341			child_mapper(filename, procno, nprocs);
342			exit(0);
343
344		default:
345			pidarray[procno] = pid;
346		}
347	}
348
349	/*
350	 *  Now wait for children and refork them as needed.
351	 */
352
353	while (!finished) {
354		pid = wait(&wait_stat);
355		/*
356		 *  Block signals while processing child exit.
357		 */
358
359		if (sighold(SIGALRM) || sighold(SIGINT)) {
360			perror("sighold error");
361			goto cleanup;
362		}
363
364		if (pid != -1) {
365			/*
366			 *  Check exit status, then refork with the
367			 *  appropriate procno.
368			 */
369			if (!WIFEXITED(wait_stat)
370			    || WEXITSTATUS(wait_stat) != 0) {
371				(void)fprintf(stderr, "child exit with err "
372					      "<x%x>\n", wait_stat);
373				goto cleanup;
374			}
375			for (i = 0; i < nprocs; i++)
376				if (pid == pidarray[i])
377					break;
378			if (i == nprocs) {
379				(void)fprintf(stderr, "unknown child pid %d, "
380					      "<x%x>\n", pid, wait_stat);
381				goto cleanup;
382			}
383
384			if ((pid = fork()) == -1) {
385				perror("fork error");
386				pidarray[i] = 0;
387				goto cleanup;
388			} else if (pid == 0) {	/* child */
389				child_mapper(filename, i, nprocs);
390				exit(0);
391			} else
392				pidarray[i] = pid;
393		} else {
394			/*
395			 *  wait returned an error.  If EINTR, then
396			 *  normal finish, else it's an unexpected
397			 *  error...
398			 */
399			if (errno != EINTR || !finished) {
400				perror("unexpected wait error");
401				goto cleanup;
402			}
403		}
404		if (sigrelse(SIGALRM) || sigrelse(SIGINT)) {
405			perror("sigrelse error");
406			goto cleanup;
407		}
408	}
409
410	/*
411	 *  Finished!  Check the file for sanity, then kill all
412	 *  the children and done!.
413	 */
414
415	if (sighold(SIGALRM)) {
416		perror("sighold error");
417		goto cleanup;
418	}
419	(void)alarm(0);
420	no_prob = 1;
421
422cleanup:
423	for (i = 0; i < nprocs; i++)
424		(void)kill(pidarray[i], SIGKILL);
425
426	while (wait(&wait_stat) != -1 || errno != ECHILD)
427		continue;
428
429	if (no_prob) {		/* only check file if no errors */
430		if (!fileokay(filename, buf)) {
431			(void)fprintf(stderr, "file data incorrect!\n");
432			(void)printf("  leaving file <%s>\n", filename);
433			/***** LTP Port *****/
434			local_flag = FAILED;
435			anyfail();
436			/*****	**	*****/
437		} else {
438			(void)printf("file data okay\n");
439			if (!leavefile)
440				(void)unlink(filename);
441		}
442	} else
443		(void)printf("  leaving file <%s>\n", filename);
444
445	(void)time(&t);
446	//(void)printf("%s: Finished %s", argv[0], ctime(&t)); LTP Port
447	ok_exit();
448	tst_exit();
449}
450
451/*
452 *  Child process that reads/writes map.  The child stats the file
453 *  to determine the size, maps the size of the file, then reads/writes
454 *  its own locations on random pages of the map (its locations being
455 *  determined based on nprocs & procno).  After a specific number of
456 *  iterations, it exits.
457 */
458void child_mapper(char *file, unsigned procno, unsigned nprocs)
459{
460#ifdef LARGE_FILE
461	struct stat64 statbuf;
462	off64_t filesize;
463	off64_t offset;
464#else /* LARGE_FILE */
465	struct stat statbuf;
466	off_t filesize;
467	off_t offset;
468#endif /* LARGE_FILE */
469	size_t validsize;
470	size_t mapsize;
471	char *maddr = NULL, *paddr;
472	int fd;
473	size_t pagesize = sysconf(_SC_PAGE_SIZE);
474	unsigned randpage;
475	unsigned int seed;
476	unsigned loopcnt;
477	unsigned nloops;
478	unsigned mappages;
479	unsigned i;
480
481	seed = initrand();	/* initialize random seed */
482
483#ifdef LARGE_FILE
484	if (stat64(file, &statbuf) == -1) {
485#else /* LARGE_FILE */
486	if (stat(file, &statbuf) == -1) {
487#endif /* LARGE_FILE */
488		perror("stat error");
489		anyfail();
490	}
491	filesize = statbuf.st_size;
492
493#ifdef LARGE_FILE
494	if ((fd = open64(file, O_RDWR)) == -1) {
495#else /* LARGE_FILE */
496	if ((fd = open(file, O_RDWR)) == -1) {
497#endif /* LARGE_FILE */
498		perror("open error");
499		anyfail();
500	}
501
502	if (statbuf.st_size - sparseoffset > SIZE_MAX) {
503		fprintf(stderr, "size_t overflow when setting up map\n");
504		anyfail();
505	}
506	mapsize = (size_t) (statbuf.st_size - sparseoffset);
507	mappages = roundup(mapsize, pagesize) / pagesize;
508	offset = sparseoffset;
509	if (do_offset) {
510		int pageoffset = lrand48() % mappages;
511		int byteoffset = pageoffset * pagesize;
512		offset += byteoffset;
513		mapsize -= byteoffset;
514		mappages -= pageoffset;
515	}
516	nloops = (randloops) ? (lrand48() % MAXLOOPS) : MAXLOOPS;
517
518	if (debug) {
519#ifdef LARGE_FILE
520		(void)printf("child %d (pid %ld): seed %d, fsize %Ld, "
521			     "mapsize %d, off %Ld, loop %d\n",
522			     procno, getpid(), seed, filesize, mapsize,
523			     offset / pagesize, nloops);
524#else /* LARGE_FILE */
525		(void)printf("child %d (pid %d): seed %d, fsize %ld, "
526			     "mapsize %ld, off %ld, loop %d\n",
527			     procno, getpid(), seed, filesize, (long)mapsize,
528			     offset / pagesize, nloops);
529#endif /* LARGE_FILE */
530	}
531#ifdef LARGE_FILE
532	if ((maddr = mmap64(0, mapsize, PROT_READ | PROT_WRITE, MAP_SHARED,
533			    fd, offset)) == (caddr_t) - 1) {
534#else /* LARGE_FILE */
535	if ((maddr = mmap(0, mapsize, PROT_READ | PROT_WRITE, MAP_SHARED,
536			  fd, offset)) == (caddr_t) - 1) {
537#endif /* LARGE_FILE */
538		perror("mmap error");
539		anyfail();
540	}
541
542	(void)close(fd);
543
544	/*
545	 *  Now loop read/writing random pages.
546	 */
547	for (loopcnt = 0; loopcnt < nloops; loopcnt++) {
548		randpage = lrand48() % mappages;
549		paddr = maddr + (randpage * pagesize);	/* page address */
550
551		if (randpage < mappages - 1 || !(mapsize % pagesize))
552			validsize = pagesize;
553		else
554			validsize = mapsize % pagesize;
555
556		for (i = procno; i < validsize; i += nprocs) {
557			if (*((unsigned char *)(paddr + i))
558			    != ((procno + pattern) & 0xff)) {
559				(void)fprintf(stderr, "child %d: invalid data "
560					      "<x%x>", procno,
561					      *((unsigned char *)(paddr + i)));
562				(void)fprintf(stderr, " at pg %d off %d, exp "
563					      "<x%x>\n", randpage, i,
564					      (procno + pattern) & 0xff);
565				anyfail();
566			}
567
568			/*
569			 *  Now write it.
570			 */
571			*(paddr + i) = (procno + pattern) & 0xff;
572		}
573	}
574	if (dosync) {
575		/*
576		 * Exercise msync() as well!
577		 */
578		randpage = lrand48() % mappages;
579		paddr = maddr + (randpage * pagesize);	/* page address */
580		if (msync(paddr, (mappages - randpage) * pagesize,
581			  MS_SYNC) == -1) {
582			anyfail();
583		}
584	}
585	if (munmap(maddr, mapsize) == -1) {
586		perror("munmap failed");
587		local_flag = FAILED;
588		anyfail();
589	}
590	exit(0);
591}
592
593/*
594 *  Make sure file has all the correct data.
595 */
596int fileokay(char *file, uchar_t * expbuf)
597{
598#ifdef LARGE_FILE
599	struct stat64 statbuf;
600#else /* LARGE_FILE */
601	struct stat statbuf;
602#endif /* LARGE_FILE */
603	size_t mapsize;
604	unsigned mappages;
605	unsigned pagesize = sysconf(_SC_PAGE_SIZE);
606	uchar_t readbuf[pagesize];
607	int fd;
608	int cnt;
609	unsigned i, j;
610
611#ifdef LARGE_FILE
612	if ((fd = open64(file, O_RDONLY)) == -1) {
613#else /* LARGE_FILE */
614	if ((fd = open(file, O_RDONLY)) == -1) {
615#endif /* LARGE_FILE */
616		perror("open error");
617		/***** LTP Port *****/
618		local_flag = FAILED;
619		anyfail();
620		/*****	**	*****/
621		return 0;
622	}
623#ifdef LARGE_FILE
624	if (fstat64(fd, &statbuf) == -1) {
625#else /* LARGE_FILE */
626	if (fstat(fd, &statbuf) == -1) {
627#endif /* LARGE_FILE */
628		perror("stat error");
629		/***** LTP Port *****/
630		local_flag = FAILED;
631		anyfail();
632		/*****	**	*****/
633		return 0;
634	}
635#ifdef LARGE_FILE
636	if (lseek64(fd, sparseoffset, SEEK_SET) < 0) {
637#else /* LARGE_FILE */
638	if (lseek(fd, sparseoffset, SEEK_SET) < 0) {
639#endif /* LARGE_FILE */
640		perror("lseek");
641		anyfail();
642	}
643
644	if (statbuf.st_size - sparseoffset > SIZE_MAX) {
645		fprintf(stderr, "size_t overflow when setting up map\n");
646		anyfail();
647	}
648	mapsize = (size_t) (statbuf.st_size - sparseoffset);
649
650	mappages = roundup(mapsize, pagesize) / pagesize;
651
652	for (i = 0; i < mappages; i++) {
653		cnt = read(fd, readbuf, pagesize);
654		if (cnt == -1) {
655			perror("read error");
656			/***** LTP Port *****/
657			local_flag = FAILED;
658			anyfail();
659			/*****	**	*****/
660			return 0;
661		} else if (cnt != pagesize) {
662			/*
663			 *  Okay if at last page in file...
664			 */
665			if ((i * pagesize) + cnt != mapsize) {
666				(void)fprintf(stderr, "read %d of %ld bytes\n",
667					      (i * pagesize) + cnt,
668					      (long)mapsize);
669				close(fd);
670				return 0;
671			}
672		}
673		/*
674		 *  Compare read bytes of data.
675		 */
676		for (j = 0; j < cnt; j++) {
677			if (expbuf[j] != readbuf[j]) {
678				(void)fprintf(stderr,
679					      "read bad data: exp %c got %c)",
680					      expbuf[j], readbuf[j]);
681#ifdef LARGE_FILE
682				(void)fprintf(stderr, ", pg %d off %d, "
683					      "(fsize %Ld)\n", i, j,
684					      statbuf.st_size);
685#else /* LARGE_FILE */
686				(void)fprintf(stderr, ", pg %d off %d, "
687					      "(fsize %ld)\n", i, j,
688					      statbuf.st_size);
689#endif /* LARGE_FILE */
690				close(fd);
691				return 0;
692			}
693		}
694	}
695	close(fd);
696
697	return 1;
698}
699
700 /*ARGSUSED*/ void finish(int sig)
701{
702	finished++;
703	return;
704}
705
706unsigned int initrand(void)
707{
708	unsigned int seed;
709
710	/*
711	 *  Initialize random seed...  Got this from a test written
712	 *  by scooter:
713	 *      Use srand/rand to diffuse the information from the
714	 *      time and pid.  If you start several processes, then
715	 *      the time and pid information don't provide much
716	 *      variation.
717	 */
718	srand((unsigned int)getpid());
719	seed = rand();
720	srand((unsigned int)time(NULL));
721	seed = (seed ^ rand()) % 100000;
722	srand48((long int)seed);
723	return (seed);
724}
725
726/*****  LTP Port        *****/
727void ok_exit(void)
728{
729	tst_resm(TPASS, "Test passed");
730	tst_rmdir();
731	tst_exit();
732}
733
734int anyfail(void)
735{
736	tst_brkm(TFAIL, tst_rmdir, "Test failed");
737}
738
739/*****  **      **      *****/
740