xref: /freebsd/tools/regression/fsx/fsx.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
1 /*
2  * Copyright (c) 1998-2001 Apple Computer, Inc. All rights reserved.
3  *
4  * @APPLE_LICENSE_HEADER_START@
5  *
6  * The contents of this file constitute Original Code as defined in and
7  * are subject to the Apple Public Source License Version 1.2 (the
8  * "License").  You may not use this file except in compliance with the
9  * License.  Please obtain a copy of the License at
10  * http://www.apple.com/publicsource and read it before using this file.
11  *
12  * This Original Code and all software distributed under the License are
13  * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
17  * License for the specific language governing rights and limitations
18  * under the License.
19  *
20  * @APPLE_LICENSE_HEADER_END@
21  *
22  *	File:	fsx.c
23  *	Author:	Avadis Tevanian, Jr.
24  *
25  *	File system exerciser.
26  *
27  *	Rewrite and enhancements 1998-2001 Conrad Minshall -- conrad@mac.com
28  *
29  *	Various features from Joe Sokol, Pat Dirks, and Clark Warner.
30  *
31  *	Small changes to work under Linux -- davej@suse.de
32  *
33  *	Sundry porting patches from Guy Harris 12/2001
34  *
35  *	Checks for mmap last-page zero fill.
36  *
37  * $FreeBSD$
38  *
39  */
40 
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #ifdef _UWIN
44 # include <sys/param.h>
45 # include <limits.h>
46 # include <time.h>
47 # include <strings.h>
48 #endif
49 #include <fcntl.h>
50 #include <sys/mman.h>
51 #ifndef MAP_FILE
52 # define MAP_FILE 0
53 #endif
54 #include <limits.h>
55 #include <signal.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60 #include <stdarg.h>
61 #include <errno.h>
62 
63 #define NUMPRINTCOLUMNS 32	/* # columns of data to print on each line */
64 
65 /*
66  *	A log entry is an operation and a bunch of arguments.
67  */
68 
69 struct log_entry {
70 	int	operation;
71 	int	args[3];
72 };
73 
74 #define	LOGSIZE	1000
75 
76 struct log_entry	oplog[LOGSIZE];	/* the log */
77 int			logptr = 0;	/* current position in log */
78 int			logcount = 0;	/* total ops */
79 
80 /*
81  *	Define operations
82  */
83 
84 #define	OP_READ		1
85 #define OP_WRITE	2
86 #define OP_TRUNCATE	3
87 #define OP_CLOSEOPEN	4
88 #define OP_MAPREAD	5
89 #define OP_MAPWRITE	6
90 #define OP_SKIPPED	7
91 
92 int page_size;
93 int page_mask;
94 
95 char	*original_buf;			/* a pointer to the original data */
96 char	*good_buf;			/* a pointer to the correct data */
97 char	*temp_buf;			/* a pointer to the current data */
98 char	*fname;				/* name of our test file */
99 int	fd;				/* fd for our test file */
100 
101 off_t		file_size = 0;
102 off_t		biggest = 0;
103 char		state[256];
104 unsigned long	testcalls = 0;		/* calls to function "test" */
105 
106 unsigned long	simulatedopcount = 0;	/* -b flag */
107 int	closeprob = 0;			/* -c flag */
108 int	debug = 0;			/* -d flag */
109 unsigned long	debugstart = 0;		/* -D flag */
110 unsigned long	maxfilelen = 256 * 1024;	/* -l flag */
111 int	sizechecks = 1;			/* -n flag disables them */
112 int	maxoplen = 64 * 1024;		/* -o flag */
113 int	quiet = 0;			/* -q flag */
114 unsigned long progressinterval = 0;	/* -p flag */
115 int	readbdy = 1;			/* -r flag */
116 int	style = 0;			/* -s flag */
117 int	truncbdy = 1;			/* -t flag */
118 int	writebdy = 1;			/* -w flag */
119 long	monitorstart = -1;		/* -m flag */
120 long	monitorend = -1;		/* -m flag */
121 int	lite = 0;			/* -L flag */
122 long	numops = -1;			/* -N flag */
123 int	randomoplen = 1;		/* -O flag disables it */
124 int	seed = 1;			/* -S flag */
125 int     mapped_writes = 1;	      /* -W flag disables */
126 int 	mapped_reads = 1;		/* -R flag disables it */
127 int	fsxgoodfd = 0;
128 FILE *	fsxlogf = NULL;
129 int badoff = -1;
130 int closeopen = 0;
131 
132 
133 void
134 vwarnc(code, fmt, ap)
135 	int code;
136 	const char *fmt;
137 	va_list ap;
138 {
139 	fprintf(stderr, "fsx: ");
140 	if (fmt != NULL) {
141 		vfprintf(stderr, fmt, ap);
142 		fprintf(stderr, ": ");
143 	}
144 	fprintf(stderr, "%s\n", strerror(code));
145 }
146 
147 
148 void
149 warn(const char * fmt, ...)
150 {
151 	va_list ap;
152 	va_start(ap, fmt);
153 	vwarnc(errno, fmt, ap);
154 	va_end(ap);
155 }
156 
157 
158 void
159 prt(char *fmt, ...)
160 {
161 	va_list args;
162 
163 	va_start(args, fmt);
164 	vfprintf(stdout, fmt, args);
165 	if (fsxlogf)
166 		vfprintf(fsxlogf, fmt, args);
167 	va_end(args);
168 }
169 
170 void
171 prterr(char *prefix)
172 {
173 	prt("%s%s%s\n", prefix, prefix ? ": " : "", strerror(errno));
174 }
175 
176 
177 void
178 log4(int operation, int arg0, int arg1, int arg2)
179 {
180 	struct log_entry *le;
181 
182 	le = &oplog[logptr];
183 	le->operation = operation;
184 	if (closeopen)
185 		le->operation = ~ le->operation;
186 	le->args[0] = arg0;
187 	le->args[1] = arg1;
188 	le->args[2] = arg2;
189 	logptr++;
190 	logcount++;
191 	if (logptr >= LOGSIZE)
192 		logptr = 0;
193 }
194 
195 
196 void
197 logdump(void)
198 {
199 	int	i, count, down;
200 	struct log_entry	*lp;
201 
202 	prt("LOG DUMP (%d total operations):\n", logcount);
203 	if (logcount < LOGSIZE) {
204 		i = 0;
205 		count = logcount;
206 	} else {
207 		i = logptr;
208 		count = LOGSIZE;
209 	}
210 	for ( ; count > 0; count--) {
211 		int opnum;
212 
213 		opnum = i+1 + (logcount/LOGSIZE)*LOGSIZE;
214 		prt("%d(%d mod 256): ", opnum, opnum%256);
215 		lp = &oplog[i];
216 		if ((closeopen = lp->operation < 0))
217 			lp->operation = ~ lp->operation;
218 
219 		switch (lp->operation) {
220 		case OP_MAPREAD:
221 			prt("MAPREAD\t0x%x thru 0x%x\t(0x%x bytes)",
222 			    lp->args[0], lp->args[0] + lp->args[1] - 1,
223 			    lp->args[1]);
224 			if (badoff >= lp->args[0] && badoff <
225 						     lp->args[0] + lp->args[1])
226 				prt("\t***RRRR***");
227 			break;
228 		case OP_MAPWRITE:
229 			prt("MAPWRITE 0x%x thru 0x%x\t(0x%x bytes)",
230 			    lp->args[0], lp->args[0] + lp->args[1] - 1,
231 			    lp->args[1]);
232 			if (badoff >= lp->args[0] && badoff <
233 						     lp->args[0] + lp->args[1])
234 				prt("\t******WWWW");
235 			break;
236 		case OP_READ:
237 			prt("READ\t0x%x thru 0x%x\t(0x%x bytes)",
238 			    lp->args[0], lp->args[0] + lp->args[1] - 1,
239 			    lp->args[1]);
240 			if (badoff >= lp->args[0] &&
241 			    badoff < lp->args[0] + lp->args[1])
242 				prt("\t***RRRR***");
243 			break;
244 		case OP_WRITE:
245 			prt("WRITE\t0x%x thru 0x%x\t(0x%x bytes)",
246 			    lp->args[0], lp->args[0] + lp->args[1] - 1,
247 			    lp->args[1]);
248 			if (lp->args[0] > lp->args[2])
249 				prt(" HOLE");
250 			else if (lp->args[0] + lp->args[1] > lp->args[2])
251 				prt(" EXTEND");
252 			if ((badoff >= lp->args[0] || badoff >=lp->args[2]) &&
253 			    badoff < lp->args[0] + lp->args[1])
254 				prt("\t***WWWW");
255 			break;
256 		case OP_TRUNCATE:
257 			down = lp->args[0] < lp->args[1];
258 			prt("TRUNCATE %s\tfrom 0x%x to 0x%x",
259 			    down ? "DOWN" : "UP", lp->args[1], lp->args[0]);
260 			if (badoff >= lp->args[!down] &&
261 			    badoff < lp->args[!!down])
262 				prt("\t******WWWW");
263 			break;
264 		case OP_SKIPPED:
265 			prt("SKIPPED (no operation)");
266 			break;
267 		default:
268 			prt("BOGUS LOG ENTRY (operation code = %d)!",
269 			    lp->operation);
270 		}
271 		if (closeopen)
272 			prt("\n\t\tCLOSE/OPEN");
273 		prt("\n");
274 		i++;
275 		if (i == LOGSIZE)
276 			i = 0;
277 	}
278 }
279 
280 
281 void
282 save_buffer(char *buffer, off_t bufferlength, int fd)
283 {
284 	off_t ret;
285 	ssize_t byteswritten;
286 
287 	if (fd <= 0 || bufferlength == 0)
288 		return;
289 
290 	if (bufferlength > SSIZE_MAX) {
291 		prt("fsx flaw: overflow in save_buffer\n");
292 		exit(67);
293 	}
294 	if (lite) {
295 		off_t size_by_seek = lseek(fd, (off_t)0, SEEK_END);
296 		if (size_by_seek == (off_t)-1)
297 			prterr("save_buffer: lseek eof");
298 		else if (bufferlength > size_by_seek) {
299 			warn("save_buffer: .fsxgood file too short... will save 0x%llx bytes instead of 0x%llx\n", (unsigned long long)size_by_seek,
300 			     (unsigned long long)bufferlength);
301 			bufferlength = size_by_seek;
302 		}
303 	}
304 
305 	ret = lseek(fd, (off_t)0, SEEK_SET);
306 	if (ret == (off_t)-1)
307 		prterr("save_buffer: lseek 0");
308 
309 	byteswritten = write(fd, buffer, (size_t)bufferlength);
310 	if (byteswritten != bufferlength) {
311 		if (byteswritten == -1)
312 			prterr("save_buffer write");
313 		else
314 			warn("save_buffer: short write, 0x%x bytes instead of 0x%llx\n",
315 			     (unsigned)byteswritten,
316 			     (unsigned long long)bufferlength);
317 	}
318 }
319 
320 
321 void
322 report_failure(int status)
323 {
324 	logdump();
325 
326 	if (fsxgoodfd) {
327 		if (good_buf) {
328 			save_buffer(good_buf, file_size, fsxgoodfd);
329 			prt("Correct content saved for comparison\n");
330 			prt("(maybe hexdump \"%s\" vs \"%s.fsxgood\")\n",
331 			    fname, fname);
332 		}
333 		close(fsxgoodfd);
334 	}
335 	exit(status);
336 }
337 
338 
339 #define short_at(cp) ((unsigned short)((*((unsigned char *)(cp)) << 8) | \
340 					*(((unsigned char *)(cp)) + 1)))
341 
342 void
343 check_buffers(unsigned offset, unsigned size)
344 {
345 	unsigned char c, t;
346 	unsigned i = 0;
347 	unsigned n = 0;
348 	unsigned op = 0;
349 	unsigned bad = 0;
350 
351 	if (memcmp(good_buf + offset, temp_buf, size) != 0) {
352 		prt("READ BAD DATA: offset = 0x%x, size = 0x%x\n",
353 		    offset, size);
354 		prt("OFFSET\tGOOD\tBAD\tRANGE\n");
355 		while (size > 0) {
356 			c = good_buf[offset];
357 			t = temp_buf[i];
358 			if (c != t) {
359 				if (n == 0) {
360 					bad = short_at(&temp_buf[i]);
361 					prt("0x%5x\t0x%04x\t0x%04x", offset,
362 					    short_at(&good_buf[offset]), bad);
363 					op = temp_buf[offset & 1 ? i+1 : i];
364 				}
365 				n++;
366 				badoff = offset;
367 			}
368 			offset++;
369 			i++;
370 			size--;
371 		}
372 		if (n) {
373 			prt("\t0x%5x\n", n);
374 			if (bad)
375 				prt("operation# (mod 256) for the bad data may be %u\n", ((unsigned)op & 0xff));
376 			else
377 				prt("operation# (mod 256) for the bad data unknown, check HOLE and EXTEND ops\n");
378 		} else
379 			prt("????????????????\n");
380 		report_failure(110);
381 	}
382 }
383 
384 
385 void
386 check_size(void)
387 {
388 	struct stat	statbuf;
389 	off_t	size_by_seek;
390 
391 	if (fstat(fd, &statbuf)) {
392 		prterr("check_size: fstat");
393 		statbuf.st_size = -1;
394 	}
395 	size_by_seek = lseek(fd, (off_t)0, SEEK_END);
396 	if (file_size != statbuf.st_size || file_size != size_by_seek) {
397 		prt("Size error: expected 0x%llx stat 0x%llx seek 0x%llx\n",
398 		    (unsigned long long)file_size,
399 		    (unsigned long long)statbuf.st_size,
400 		    (unsigned long long)size_by_seek);
401 		report_failure(120);
402 	}
403 }
404 
405 
406 void
407 check_trunc_hack(void)
408 {
409 	struct stat statbuf;
410 
411 	ftruncate(fd, (off_t)0);
412 	ftruncate(fd, (off_t)100000);
413 	fstat(fd, &statbuf);
414 	if (statbuf.st_size != (off_t)100000) {
415 		prt("no extend on truncate! not posix!\n");
416 		exit(130);
417 	}
418 	ftruncate(fd, (off_t)0);
419 }
420 
421 
422 void
423 doread(unsigned offset, unsigned size)
424 {
425 	off_t ret;
426 	unsigned iret;
427 
428 	offset -= offset % readbdy;
429 	if (size == 0) {
430 		if (!quiet && testcalls > simulatedopcount)
431 			prt("skipping zero size read\n");
432 		log4(OP_SKIPPED, OP_READ, offset, size);
433 		return;
434 	}
435 	if (size + offset > file_size) {
436 		if (!quiet && testcalls > simulatedopcount)
437 			prt("skipping seek/read past end of file\n");
438 		log4(OP_SKIPPED, OP_READ, offset, size);
439 		return;
440 	}
441 
442 	log4(OP_READ, offset, size, 0);
443 
444 	if (testcalls <= simulatedopcount)
445 		return;
446 
447 	if (!quiet && ((progressinterval &&
448 			testcalls % progressinterval == 0) ||
449 		       (debug &&
450 			(monitorstart == -1 ||
451 			 (offset + size > monitorstart &&
452 			  (monitorend == -1 || offset <= monitorend))))))
453 		prt("%lu read\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
454 		    offset, offset + size - 1, size);
455 	ret = lseek(fd, (off_t)offset, SEEK_SET);
456 	if (ret == (off_t)-1) {
457 		prterr("doread: lseek");
458 		report_failure(140);
459 	}
460 	iret = read(fd, temp_buf, size);
461 	if (iret != size) {
462 		if (iret == -1)
463 			prterr("doread: read");
464 		else
465 			prt("short read: 0x%x bytes instead of 0x%x\n",
466 			    iret, size);
467 		report_failure(141);
468 	}
469 	check_buffers(offset, size);
470 }
471 
472 
473 void
474 check_eofpage(char *s, unsigned offset, char *p, int size)
475 {
476 	unsigned last_page, should_be_zero;
477 
478 	if (offset + size <= (file_size & ~page_mask))
479 		return;
480 	/*
481 	 * we landed in the last page of the file
482 	 * test to make sure the VM system provided 0's
483 	 * beyond the true end of the file mapping
484 	 * (as required by mmap def in 1996 posix 1003.1)
485 	 */
486 	last_page = ((int)p + (offset & page_mask) + size) & ~page_mask;
487 
488 	for (should_be_zero = last_page + (file_size & page_mask);
489 	     should_be_zero < last_page + page_size;
490 	     should_be_zero++)
491 		if (*(char *)should_be_zero) {
492 			prt("Mapped %s: non-zero data past EOF (0x%llx) page offset 0x%x is 0x%04x\n",
493 			    s, file_size - 1, should_be_zero & page_mask,
494 			    short_at(should_be_zero));
495 			report_failure(205);
496 		}
497 }
498 
499 
500 void
501 domapread(unsigned offset, unsigned size)
502 {
503 	unsigned pg_offset;
504 	unsigned map_size;
505 	char    *p;
506 
507 	offset -= offset % readbdy;
508 	if (size == 0) {
509 		if (!quiet && testcalls > simulatedopcount)
510 			prt("skipping zero size read\n");
511 		log4(OP_SKIPPED, OP_MAPREAD, offset, size);
512 		return;
513 	}
514 	if (size + offset > file_size) {
515 		if (!quiet && testcalls > simulatedopcount)
516 			prt("skipping seek/read past end of file\n");
517 		log4(OP_SKIPPED, OP_MAPREAD, offset, size);
518 		return;
519 	}
520 
521 	log4(OP_MAPREAD, offset, size, 0);
522 
523 	if (testcalls <= simulatedopcount)
524 		return;
525 
526 	if (!quiet && ((progressinterval &&
527 			testcalls % progressinterval == 0) ||
528 		       (debug &&
529 			(monitorstart == -1 ||
530 			 (offset + size > monitorstart &&
531 			  (monitorend == -1 || offset <= monitorend))))))
532 		prt("%lu mapread\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
533 		    offset, offset + size - 1, size);
534 
535 	pg_offset = offset & page_mask;
536 	map_size  = pg_offset + size;
537 
538 	if ((p = (char *)mmap(0, map_size, PROT_READ, MAP_FILE | MAP_SHARED, fd,
539 			      (off_t)(offset - pg_offset))) == (char *)-1) {
540 		prterr("domapread: mmap");
541 		report_failure(190);
542 	}
543 	memcpy(temp_buf, p + pg_offset, size);
544 
545 	check_eofpage("Read", offset, p, size);
546 
547 	if (munmap(p, map_size) != 0) {
548 		prterr("domapread: munmap");
549 		report_failure(191);
550 	}
551 
552 	check_buffers(offset, size);
553 }
554 
555 
556 void
557 gendata(char *original_buf, char *good_buf, unsigned offset, unsigned size)
558 {
559 	while (size--) {
560 		good_buf[offset] = testcalls % 256;
561 		if (offset % 2)
562 			good_buf[offset] += original_buf[offset];
563 		offset++;
564 	}
565 }
566 
567 
568 void
569 dowrite(unsigned offset, unsigned size)
570 {
571 	off_t ret;
572 	unsigned iret;
573 
574 	offset -= offset % writebdy;
575 	if (size == 0) {
576 		if (!quiet && testcalls > simulatedopcount)
577 			prt("skipping zero size write\n");
578 		log4(OP_SKIPPED, OP_WRITE, offset, size);
579 		return;
580 	}
581 
582 	log4(OP_WRITE, offset, size, file_size);
583 
584 	gendata(original_buf, good_buf, offset, size);
585 	if (file_size < offset + size) {
586 		if (file_size < offset)
587 			memset(good_buf + file_size, '\0', offset - file_size);
588 		file_size = offset + size;
589 		if (lite) {
590 			warn("Lite file size bug in fsx!");
591 			report_failure(149);
592 		}
593 	}
594 
595 	if (testcalls <= simulatedopcount)
596 		return;
597 
598 	if (!quiet && ((progressinterval &&
599 			testcalls % progressinterval == 0) ||
600 		       (debug &&
601 			(monitorstart == -1 ||
602 			 (offset + size > monitorstart &&
603 			  (monitorend == -1 || offset <= monitorend))))))
604 		prt("%lu write\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
605 		    offset, offset + size - 1, size);
606 	ret = lseek(fd, (off_t)offset, SEEK_SET);
607 	if (ret == (off_t)-1) {
608 		prterr("dowrite: lseek");
609 		report_failure(150);
610 	}
611 	iret = write(fd, good_buf + offset, size);
612 	if (iret != size) {
613 		if (iret == -1)
614 			prterr("dowrite: write");
615 		else
616 			prt("short write: 0x%x bytes instead of 0x%x\n",
617 			    iret, size);
618 		report_failure(151);
619 	}
620 }
621 
622 
623 void
624 domapwrite(unsigned offset, unsigned size)
625 {
626 	unsigned pg_offset;
627 	unsigned map_size;
628 	off_t    cur_filesize;
629 	char    *p;
630 
631 	offset -= offset % writebdy;
632 	if (size == 0) {
633 		if (!quiet && testcalls > simulatedopcount)
634 			prt("skipping zero size write\n");
635 		log4(OP_SKIPPED, OP_MAPWRITE, offset, size);
636 		return;
637 	}
638 	cur_filesize = file_size;
639 
640 	log4(OP_MAPWRITE, offset, size, 0);
641 
642 	gendata(original_buf, good_buf, offset, size);
643 	if (file_size < offset + size) {
644 		if (file_size < offset)
645 			memset(good_buf + file_size, '\0', offset - file_size);
646 		file_size = offset + size;
647 		if (lite) {
648 			warn("Lite file size bug in fsx!");
649 			report_failure(200);
650 		}
651 	}
652 
653 	if (testcalls <= simulatedopcount)
654 		return;
655 
656 	if (!quiet && ((progressinterval &&
657 			testcalls % progressinterval == 0) ||
658 		       (debug &&
659 			(monitorstart == -1 ||
660 			 (offset + size > monitorstart &&
661 			  (monitorend == -1 || offset <= monitorend))))))
662 		prt("%lu mapwrite\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
663 		    offset, offset + size - 1, size);
664 
665 	if (file_size > cur_filesize) {
666 		if (ftruncate(fd, file_size) == -1) {
667 			prterr("domapwrite: ftruncate");
668 			exit(201);
669 		}
670 	}
671 	pg_offset = offset & page_mask;
672 	map_size  = pg_offset + size;
673 
674 	if ((p = (char *)mmap(0, map_size, PROT_READ | PROT_WRITE,
675 			      MAP_FILE | MAP_SHARED, fd,
676 			      (off_t)(offset - pg_offset))) == (char *)-1) {
677 		prterr("domapwrite: mmap");
678 		report_failure(202);
679 	}
680 	memcpy(p + pg_offset, good_buf + offset, size);
681 	if (msync(p, map_size, 0) != 0) {
682 		prterr("domapwrite: msync");
683 		report_failure(203);
684 	}
685 
686 	check_eofpage("Write", offset, p, size);
687 
688 	if (munmap(p, map_size) != 0) {
689 		prterr("domapwrite: munmap");
690 		report_failure(204);
691 	}
692 }
693 
694 
695 void
696 dotruncate(unsigned size)
697 {
698 	int oldsize = file_size;
699 
700 	size -= size % truncbdy;
701 	if (size > biggest) {
702 		biggest = size;
703 		if (!quiet && testcalls > simulatedopcount)
704 			prt("truncating to largest ever: 0x%x\n", size);
705 	}
706 
707 	log4(OP_TRUNCATE, size, (unsigned)file_size, 0);
708 
709 	if (size > file_size)
710 		memset(good_buf + file_size, '\0', size - file_size);
711 	file_size = size;
712 
713 	if (testcalls <= simulatedopcount)
714 		return;
715 
716 	if ((progressinterval && testcalls % progressinterval == 0) ||
717 	    (debug && (monitorstart == -1 || monitorend == -1 ||
718 		       size <= monitorend)))
719 		prt("%lu trunc\tfrom 0x%x to 0x%x\n", testcalls, oldsize, size);
720 	if (ftruncate(fd, (off_t)size) == -1) {
721 		prt("ftruncate1: %x\n", size);
722 		prterr("dotruncate: ftruncate");
723 		report_failure(160);
724 	}
725 }
726 
727 
728 void
729 writefileimage()
730 {
731 	ssize_t iret;
732 
733 	if (lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) {
734 		prterr("writefileimage: lseek");
735 		report_failure(171);
736 	}
737 	iret = write(fd, good_buf, file_size);
738 	if ((off_t)iret != file_size) {
739 		if (iret == -1)
740 			prterr("writefileimage: write");
741 		else
742 			prt("short write: 0x%x bytes instead of 0x%llx\n",
743 			    iret, (unsigned long long)file_size);
744 		report_failure(172);
745 	}
746 	if (lite ? 0 : ftruncate(fd, file_size) == -1) {
747 		prt("ftruncate2: %llx\n", (unsigned long long)file_size);
748 		prterr("writefileimage: ftruncate");
749 		report_failure(173);
750 	}
751 }
752 
753 
754 void
755 docloseopen(void)
756 {
757 	if (testcalls <= simulatedopcount)
758 		return;
759 
760 	if (debug)
761 		prt("%lu close/open\n", testcalls);
762 	if (close(fd)) {
763 		prterr("docloseopen: close");
764 		report_failure(180);
765 	}
766 	fd = open(fname, O_RDWR, 0);
767 	if (fd < 0) {
768 		prterr("docloseopen: open");
769 		report_failure(181);
770 	}
771 }
772 
773 
774 void
775 test(void)
776 {
777 	unsigned long	offset;
778 	unsigned long	size = maxoplen;
779 	unsigned long	rv = random();
780 	unsigned long	op = rv % (3 + !lite + mapped_writes);
781 
782 	/* turn off the map read if necessary */
783 
784 	if (op == 2 && !mapped_reads)
785 	    op = 0;
786 
787 	if (simulatedopcount > 0 && testcalls == simulatedopcount)
788 		writefileimage();
789 
790 	testcalls++;
791 
792 	if (closeprob)
793 		closeopen = (rv >> 3) < (1 << 28) / closeprob;
794 
795 	if (debugstart > 0 && testcalls >= debugstart)
796 		debug = 1;
797 
798 	if (!quiet && testcalls < simulatedopcount && testcalls % 100000 == 0)
799 		prt("%lu...\n", testcalls);
800 
801 	/*
802 	 * READ:	op = 0
803 	 * WRITE:	op = 1
804 	 * MAPREAD:     op = 2
805 	 * TRUNCATE:	op = 3
806 	 * MAPWRITE:    op = 3 or 4
807 	 */
808 	if (lite ? 0 : op == 3 && style == 0) /* vanilla truncate? */
809 		dotruncate(random() % maxfilelen);
810 	else {
811 		if (randomoplen)
812 			size = random() % (maxoplen+1);
813 		if (lite ? 0 : op == 3)
814 			dotruncate(size);
815 		else {
816 			offset = random();
817 			if (op == 1 || op == (lite ? 3 : 4)) {
818 				offset %= maxfilelen;
819 				if (offset + size > maxfilelen)
820 					size = maxfilelen - offset;
821 				if (op != 1)
822 					domapwrite(offset, size);
823 				else
824 					dowrite(offset, size);
825 			} else {
826 				if (file_size)
827 					offset %= file_size;
828 				else
829 					offset = 0;
830 				if (offset + size > file_size)
831 					size = file_size - offset;
832 				if (op != 0)
833 					domapread(offset, size);
834 				else
835 					doread(offset, size);
836 			}
837 		}
838 	}
839 	if (sizechecks && testcalls > simulatedopcount)
840 		check_size();
841 	if (closeopen)
842 		docloseopen();
843 }
844 
845 
846 void
847 cleanup(sig)
848 	int	sig;
849 {
850 	if (sig)
851 		prt("signal %d\n", sig);
852 	prt("testcalls = %lu\n", testcalls);
853 	exit(sig);
854 }
855 
856 
857 void
858 usage(void)
859 {
860 	fprintf(stdout, "usage: %s",
861 		"fsx [-dnqLOW] [-b opnum] [-c Prob] [-l flen] [-m start:end] [-o oplen] [-p progressinterval] [-r readbdy] [-s style] [-t truncbdy] [-w writebdy] [-D startingop] [-N numops] [-P dirpath] [-S seed] fname\n\
862 	-b opnum: beginning operation number (default 1)\n\
863 	-c P: 1 in P chance of file close+open at each op (default infinity)\n\
864 	-d: debug output for all operations\n\
865 	-l flen: the upper bound on file size (default 262144)\n\
866 	-m startop:endop: monitor (print debug output) specified byte range (default 0:infinity)\n\
867 	-n: no verifications of file size\n\
868 	-o oplen: the upper bound on operation size (default 65536)\n\
869 	-p progressinterval: debug output at specified operation interval\n\
870 	-q: quieter operation\n\
871 	-r readbdy: 4096 would make reads page aligned (default 1)\n\
872 	-s style: 1 gives smaller truncates (default 0)\n\
873 	-t truncbdy: 4096 would make truncates page aligned (default 1)\n\
874 	-w writebdy: 4096 would make writes page aligned (default 1)\n\
875 	-D startingop: debug output starting at specified operation\n\
876 	-L: fsxLite - no file creations & no file size changes\n\
877 	-N numops: total # operations to do (default infinity)\n\
878 	-O: use oplen (see -o flag) for every op (default random)\n\
879 	-P dirpath: save .fsxlog and .fsxgood files in dirpath (default ./)\n\
880 	-S seed: for random # generator (default 1) 0 gets timestamp\n\
881 	-W: mapped write operations DISabled\n\
882 	-R: mapped read operations DISabled)\n\
883 	fname: this filename is REQUIRED (no default)\n");
884 	exit(90);
885 }
886 
887 
888 int
889 getnum(char *s, char **e)
890 {
891 	int ret = -1;
892 
893 	*e = (char *) 0;
894 	ret = strtol(s, e, 0);
895 	if (*e)
896 		switch (**e) {
897 		case 'b':
898 		case 'B':
899 			ret *= 512;
900 			*e = *e + 1;
901 			break;
902 		case 'k':
903 		case 'K':
904 			ret *= 1024;
905 			*e = *e + 1;
906 			break;
907 		case 'm':
908 		case 'M':
909 			ret *= 1024*1024;
910 			*e = *e + 1;
911 			break;
912 		case 'w':
913 		case 'W':
914 			ret *= 4;
915 			*e = *e + 1;
916 			break;
917 		}
918 	return (ret);
919 }
920 
921 
922 int
923 main(int argc, char **argv)
924 {
925 	int	i, ch;
926 	char	*endp;
927 	char goodfile[1024];
928 	char logfile[1024];
929 
930 	goodfile[0] = 0;
931 	logfile[0] = 0;
932 
933 	page_size = getpagesize();
934 	page_mask = page_size - 1;
935 
936 	setvbuf(stdout, (char *)0, _IOLBF, 0); /* line buffered stdout */
937 
938 	while ((ch = getopt(argc, argv, "b:c:dl:m:no:p:qr:s:t:w:D:LN:OP:RS:W"))
939 	       != EOF)
940 		switch (ch) {
941 		case 'b':
942 			simulatedopcount = getnum(optarg, &endp);
943 			if (!quiet)
944 				fprintf(stdout, "Will begin at operation %ld\n",
945 					simulatedopcount);
946 			if (simulatedopcount == 0)
947 				usage();
948 			simulatedopcount -= 1;
949 			break;
950 		case 'c':
951 			closeprob = getnum(optarg, &endp);
952 			if (!quiet)
953 				fprintf(stdout,
954 					"Chance of close/open is 1 in %d\n",
955 					closeprob);
956 			if (closeprob <= 0)
957 				usage();
958 			break;
959 		case 'd':
960 			debug = 1;
961 			break;
962 		case 'l':
963 			maxfilelen = getnum(optarg, &endp);
964 			if (maxfilelen <= 0)
965 				usage();
966 			break;
967 		case 'm':
968 			monitorstart = getnum(optarg, &endp);
969 			if (monitorstart < 0)
970 				usage();
971 			if (!endp || *endp++ != ':')
972 				usage();
973 			monitorend = getnum(endp, &endp);
974 			if (monitorend < 0)
975 				usage();
976 			if (monitorend == 0)
977 				monitorend = -1; /* aka infinity */
978 			debug = 1;
979 		case 'n':
980 			sizechecks = 0;
981 			break;
982 		case 'o':
983 			maxoplen = getnum(optarg, &endp);
984 			if (maxoplen <= 0)
985 				usage();
986 			break;
987 		case 'p':
988 			progressinterval = getnum(optarg, &endp);
989 			if (progressinterval < 0)
990 				usage();
991 			break;
992 		case 'q':
993 			quiet = 1;
994 			break;
995 		case 'r':
996 			readbdy = getnum(optarg, &endp);
997 			if (readbdy <= 0)
998 				usage();
999 			break;
1000 		case 's':
1001 			style = getnum(optarg, &endp);
1002 			if (style < 0 || style > 1)
1003 				usage();
1004 			break;
1005 		case 't':
1006 			truncbdy = getnum(optarg, &endp);
1007 			if (truncbdy <= 0)
1008 				usage();
1009 			break;
1010 		case 'w':
1011 			writebdy = getnum(optarg, &endp);
1012 			if (writebdy <= 0)
1013 				usage();
1014 			break;
1015 		case 'D':
1016 			debugstart = getnum(optarg, &endp);
1017 			if (debugstart < 1)
1018 				usage();
1019 			break;
1020 		case 'L':
1021 			lite = 1;
1022 			break;
1023 		case 'N':
1024 			numops = getnum(optarg, &endp);
1025 			if (numops < 0)
1026 				usage();
1027 			break;
1028 		case 'O':
1029 			randomoplen = 0;
1030 			break;
1031 		case 'P':
1032 			strncpy(goodfile, optarg, sizeof(goodfile));
1033 			strcat(goodfile, "/");
1034 			strncpy(logfile, optarg, sizeof(logfile));
1035 			strcat(logfile, "/");
1036 			break;
1037 		case 'R':
1038 			mapped_reads = 0;
1039 			break;
1040 		case 'S':
1041 			seed = getnum(optarg, &endp);
1042 			if (seed == 0)
1043 				seed = time(0) % 10000;
1044 			if (!quiet)
1045 				fprintf(stdout, "Seed set to %d\n", seed);
1046 			if (seed < 0)
1047 				usage();
1048 			break;
1049 		case 'W':
1050 			mapped_writes = 0;
1051 			if (!quiet)
1052 				fprintf(stdout, "mapped writes DISABLED\n");
1053 			break;
1054 
1055 		default:
1056 			usage();
1057 			/* NOTREACHED */
1058 		}
1059 	argc -= optind;
1060 	argv += optind;
1061 	if (argc != 1)
1062 		usage();
1063 	fname = argv[0];
1064 
1065 	signal(SIGHUP,	cleanup);
1066 	signal(SIGINT,	cleanup);
1067 	signal(SIGPIPE,	cleanup);
1068 	signal(SIGALRM,	cleanup);
1069 	signal(SIGTERM,	cleanup);
1070 	signal(SIGXCPU,	cleanup);
1071 	signal(SIGXFSZ,	cleanup);
1072 	signal(SIGVTALRM,	cleanup);
1073 	signal(SIGUSR1,	cleanup);
1074 	signal(SIGUSR2,	cleanup);
1075 
1076 	initstate(seed, state, 256);
1077 	setstate(state);
1078 	fd = open(fname, O_RDWR|(lite ? 0 : O_CREAT|O_TRUNC), 0666);
1079 	if (fd < 0) {
1080 		prterr(fname);
1081 		exit(91);
1082 	}
1083 	strncat(goodfile, fname, 256);
1084 	strcat (goodfile, ".fsxgood");
1085 	fsxgoodfd = open(goodfile, O_RDWR|O_CREAT|O_TRUNC, 0666);
1086 	if (fsxgoodfd < 0) {
1087 		prterr(goodfile);
1088 		exit(92);
1089 	}
1090 	strncat(logfile, fname, 256);
1091 	strcat (logfile, ".fsxlog");
1092 	fsxlogf = fopen(logfile, "w");
1093 	if (fsxlogf == NULL) {
1094 		prterr(logfile);
1095 		exit(93);
1096 	}
1097 	if (lite) {
1098 		off_t ret;
1099 		file_size = maxfilelen = lseek(fd, (off_t)0, SEEK_END);
1100 		if (file_size == (off_t)-1) {
1101 			prterr(fname);
1102 			warn("main: lseek eof");
1103 			exit(94);
1104 		}
1105 		ret = lseek(fd, (off_t)0, SEEK_SET);
1106 		if (ret == (off_t)-1) {
1107 			prterr(fname);
1108 			warn("main: lseek 0");
1109 			exit(95);
1110 		}
1111 	}
1112 	original_buf = (char *) malloc(maxfilelen);
1113 	for (i = 0; i < maxfilelen; i++)
1114 		original_buf[i] = random() % 256;
1115 	good_buf = (char *) malloc(maxfilelen);
1116 	memset(good_buf, '\0', maxfilelen);
1117 	temp_buf = (char *) malloc(maxoplen);
1118 	memset(temp_buf, '\0', maxoplen);
1119 	if (lite) {	/* zero entire existing file */
1120 		ssize_t written;
1121 
1122 		written = write(fd, good_buf, (size_t)maxfilelen);
1123 		if (written != maxfilelen) {
1124 			if (written == -1) {
1125 				prterr(fname);
1126 				warn("main: error on write");
1127 			} else
1128 				warn("main: short write, 0x%x bytes instead of 0x%x\n",
1129 				     (unsigned)written, maxfilelen);
1130 			exit(98);
1131 		}
1132 	} else
1133 		check_trunc_hack();
1134 
1135 	while (numops == -1 || numops--)
1136 		test();
1137 
1138 	if (close(fd)) {
1139 		prterr("close");
1140 		report_failure(99);
1141 	}
1142 	prt("All operations completed A-OK!\n");
1143 
1144 	exit(0);
1145 	return 0;
1146 }
1147 
1148