xref: /titanic_51/usr/src/cmd/backup/dump/dumpmain.c (revision db3659e514c8bf3f03bcca6dd082e363bd7b466a)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
28 /*	  All Rights Reserved	*/
29 
30 /*
31  * Copyright (c) 1980 Regents of the University of California.
32  * All rights reserved.  The Berkeley software License Agreement
33  * specifies the terms and conditions for redistribution.
34  */
35 
36 #pragma ident	"%Z%%M%	%I%	%E% SMI"
37 
38 #include "dump.h"
39 #include <rmt.h>
40 #include <sys/mtio.h>
41 #include <limits.h>
42 #include <priv_utils.h>
43 #include "roll_log.h"
44 #include <unistd.h>
45 
46 int	notify = 0;		/* notify operator flag */
47 int	blockswritten = 0;	/* number of blocks written on current tape */
48 uint_t	tapeno = 0;		/* current tape number */
49 daddr32_t filenum = 0;		/* current file number on tape */
50 int	density = 0;		/* density in bytes/0.1" */
51 int	tenthsperirg;		/* inter-record-gap in 0.1"'s */
52 uint_t	ntrec = 0;		/* # tape blocks in each tape record */
53 uint_t	saved_ntrec = 0;	/* saved value of ntrec */
54 uint_t	forceflag = 0;		/* forced to change tp_bsize */
55 int	cartridge = 0;		/* assume non-cartridge tape */
56 uint_t	tracks;			/* # tracks on a cartridge tape */
57 int	diskette = 0;		/* assume not dumping to a diskette */
58 int	printsize = 0;		/* just print estimated size and exit */
59 int	mapfd = -1;		/* if >= 0, file descriptor for mmap */
60 int32_t	tp_bsize = TP_BSIZE_MIN; /* tape block record size (frag size) */
61 #ifdef DEBUG
62 int	xflag;			/* debugging switch */
63 #endif
64 
65 char	*myname;
66 
67 /*
68  * This should be struct fs, but there are trailing bits on disk
69  * that we also need to read in as part of it.  It's an array of
70  * longs instead of char to force proper alignment.
71  */
72 static long sblock_buf[SBSIZE/sizeof (long)];
73 
74 #ifdef __STDC__
75 static char *mb(u_offset_t);
76 static void nextstate(int);
77 #else
78 static char *mb();
79 static void nextstate();
80 #endif
81 
82 extern	jmp_buf checkpoint_buf;	/* context for return from checkpoint */
83 #define	FUDGE_FACTOR	0x2000000
84 
85 int
86 main(int argc, char *argv[])
87 {
88 	char		*arg;
89 	int		bflag = 0, i, error = 0, saverr;
90 	double		fetapes = 0.0;
91 	struct	mnttab	*dt;
92 	char		msgbuf[3000], *msgp;
93 	char		kbsbuf[BUFSIZ];
94 	u_offset_t	esize_shift = 0;
95 	int32_t	new_mult = 0;
96 	time32_t	snapdate;
97 
98 	host = NULL;
99 
100 	if (myname = strrchr(argv[0], '/'))
101 		myname++;
102 	else
103 		myname = argv[0];
104 
105 	if (strcmp("hsmdump", myname) == 0) {
106 		msg(gettext("hsmdump emulation is no longer supported.\n"));
107 		Exit(X_ABORT);
108 	}
109 
110 	tape = DEFTAPE;
111 	autoload_period = 12;
112 	autoload_tries = 12;	/* traditional default of ~2.5 minutes */
113 
114 	(void) setlocale(LC_ALL, "");
115 #if !defined(TEXT_DOMAIN)
116 #define	TEXT_DOMAIN "SYS_TEST"
117 #endif  /* TEXT_DOMAIN */
118 	(void) textdomain(TEXT_DOMAIN);
119 
120 	/*
121 	 * If someone strips the set-uid bit, dump will still work for local
122 	 * tapes.  Fail when we try to access a remote tape.
123 	 */
124 	(void) __init_suid_priv(0, PRIV_NET_PRIVADDR, (char *)NULL);
125 
126 	if (sysinfo(SI_HOSTNAME, spcl.c_host, sizeof (spcl.c_host)) < 0) {
127 		saverr = errno;
128 		msg(gettext("Could not get host name: %s\n"),
129 		    strerror(saverr));
130 		bzero(spcl.c_host, sizeof (spcl.c_host));
131 	}
132 
133 	dumppid = getpid();
134 	tsize = 0;	/* no default size, detect EOT dynamically */
135 
136 	disk = NULL;
137 	dname = NULL;
138 	disk_dynamic = 0;
139 	increm = NINCREM;
140 	incno = '9';
141 	uflag = 0;
142 	arg = "u";
143 	tlabel = "none";
144 	if (argc > 1) {
145 		argv++;
146 		argc--;
147 		arg = *argv;
148 		if (*arg == '-')
149 			arg++;
150 	}
151 	while (*arg)
152 	switch (*arg++) {		/* BE CAUTIOUS OF FALLTHROUGHS */
153 	case 'M':
154 		/*
155 		 * This undocumented option causes each process to
156 		 * mkdir debug_chdir/getpid(), and chdir to it.  This is
157 		 * to ease the collection of profiling information and
158 		 * core dumps.
159 		 */
160 		if (argc > 1) {
161 			argv++;
162 			argc--;
163 			debug_chdir = *argv;
164 			msg(gettext(
165 			    "Each process shall try to chdir to %s/<pid>\n"),
166 			    debug_chdir);
167 			child_chdir();
168 		} else {
169 			msg(gettext("Missing move-to-dir (M) name\n"));
170 			dumpabort();
171 			/*NOTREACHED*/
172 		}
173 		break;
174 
175 	case 'w':
176 		lastdump('w');		/* tell us only what has to be done */
177 		exit(0);
178 		break;
179 
180 	case 'W':			/* what to do */
181 		lastdump('W');		/* tell state of what has been done */
182 		exit(0);		/* do nothing else */
183 		break;
184 
185 	case 'T':
186 		if (argc > 1) {
187 			int count;
188 			int multiplier;
189 			char units;
190 
191 			argv++;
192 			argc--;
193 			count = atoi(*argv);
194 			if (count < 1) {
195 				msg(gettext(
196 				    "Unreasonable autoload timeout period\n"));
197 				dumpabort();
198 				/*NOTREACHED*/
199 			}
200 			units = *(*argv + strlen(*argv) - 1);
201 			switch (units) {
202 			case 's':
203 				multiplier = 1;
204 				break;
205 			case 'h':
206 				multiplier = 3600;
207 				break;
208 			case '0': case '1': case '2': case '3': case '4':
209 			case '5': case '6': case '7': case '8': case '9':
210 			case 'm':
211 				multiplier = 60;
212 				break;
213 			default:
214 				msg(gettext(
215 				    "Unknown timeout units indicator `%c'\n"),
216 				    units);
217 				dumpabort();
218 				/*NOTREACHED*/
219 			}
220 			autoload_tries = 1 +
221 			    ((count * multiplier) / autoload_period);
222 		} else {
223 			msg(gettext("Missing autoload timeout period\n"));
224 			dumpabort();
225 			/*NOTREACHED*/
226 		}
227 		break;
228 
229 	case 'f':			/* output file */
230 		if (argc > 1) {
231 			argv++;
232 			argc--;
233 			tape = *argv;
234 			if (*tape == '\0') {
235 				msg(gettext("Bad output device name\n"));
236 				dumpabort();
237 				/*NOTREACHED*/
238 			}
239 		} else {
240 			msg(gettext("Missing output device name\n"));
241 			dumpabort();
242 			/*NOTREACHED*/
243 		}
244 		if (strcmp(tape, "-") == 0 && verify) {
245 			msg(gettext(
246 			"Cannot verify when dumping to standard out.\n"));
247 			dumpabort();
248 			/*NOTREACHED*/
249 		}
250 		break;
251 
252 	case 'd':			/* density, in bits per inch */
253 		if (argc > 1) {
254 			argv++;
255 			argc--;
256 			density = atoi(*argv) / 10;
257 			if (density <= 0) {
258 				msg(gettext(
259 				    "Density must be a positive integer\n"));
260 				dumpabort();
261 				/*NOTREACHED*/
262 			}
263 		} else {
264 			msg(gettext("Missing density\n"));
265 			dumpabort();
266 			/*NOTREACHED*/
267 		}
268 		break;
269 
270 	case 's':			/* tape size, feet */
271 		if (argc > 1) {
272 			argv++;
273 			argc--;
274 			tsize = atol(*argv);
275 			if ((*argv[0] == '-') || (tsize == 0)) {
276 				msg(gettext(
277 			    "Tape size must be a positive integer\n"));
278 				dumpabort();
279 				/*NOTREACHED*/
280 			}
281 		} else {
282 			msg(gettext("Missing tape size\n"));
283 			dumpabort();
284 			/*NOTREACHED*/
285 		}
286 		break;
287 
288 	case 't':			/* tracks */
289 		if (argc > 1) {
290 			argv++;
291 			argc--;
292 			tracks = atoi(*argv);
293 		} else {
294 			msg(gettext("Missing track count\n"));
295 			dumpabort();
296 			/*NOTREACHED*/
297 		}
298 		break;
299 
300 	case 'b':			/* blocks per tape write */
301 		if (argc > 1) {
302 			argv++;
303 			argc--;
304 			bflag++;
305 			/*
306 			 * We save the ntrec in case we need to change
307 			 * tp_bsize later, we will have to recalculate
308 			 * it.
309 			 */
310 			saved_ntrec = ntrec = atoi(*argv);
311 			if (ntrec == 0 || (ntrec&1) || ntrec > (MAXNTREC*2)) {
312 				msg(gettext(
313 		    "Block size must be a positive, even integer <= %d\n"),
314 				    MAXNTREC*2);
315 				dumpabort();
316 				/*NOTREACHED*/
317 			}
318 			ntrec /= (tp_bsize/DEV_BSIZE);
319 		} else {
320 			msg(gettext("Missing blocking factor\n"));
321 			dumpabort();
322 			/*NOTREACHED*/
323 		}
324 		break;
325 
326 	case 'c':			/* Tape is cart. not 9-track */
327 	case 'C':			/* 'C' to be consistent with 'D' */
328 		cartridge++;
329 		break;
330 
331 	case '0':			/* dump level */
332 	case '1':
333 	case '2':
334 	case '3':
335 	case '4':
336 	case '5':
337 	case '6':
338 	case '7':
339 	case '8':
340 	case '9':
341 		incno = arg[-1];
342 		break;
343 
344 	case 'u':			/* update /etc/dumpdates */
345 		uflag++;
346 		break;
347 
348 	case 'n':			/* notify operators */
349 		notify++;
350 		break;
351 
352 	case 'a':			/* create archive file */
353 		archive = 1;
354 		if (argc > 1) {
355 			argv++;
356 			argc--;
357 			if (**argv == '\0') {
358 				msg(gettext("Bad archive file name\n"));
359 				dumpabort();
360 				/*NOTREACHED*/
361 			}
362 			archivefile = strdup(*argv);
363 			if (archivefile == NULL) {
364 				saverr = errno;
365 				msg(gettext("Cannot allocate memory: %s\n"),
366 				    strerror(saverr));
367 				dumpabort();
368 				/*NOTREACHED*/
369 			}
370 		} else {
371 			msg(gettext("Missing archive file name\n"));
372 			dumpabort();
373 			/*NOTREACHED*/
374 		}
375 		break;
376 
377 	case 'v':
378 		verify++;
379 		doingverify++;
380 		if (strcmp(tape, "-") == 0) {
381 			msg(gettext(
382 			"Cannot verify when dumping to standard out.\n"));
383 			dumpabort();
384 			/*NOTREACHED*/
385 		}
386 		break;
387 
388 	case 'D':
389 		diskette++;
390 		break;
391 
392 	case 'N':
393 		if (argc > 1) {
394 			argv++;
395 			argc--;
396 			if (**argv == '\0') {
397 				msg(gettext("Missing name for dumpdates "
398 				    "entry.\n"));
399 				dumpabort();
400 				/*NOTREACHED*/
401 			}
402 			dname = *argv;
403 			if (strlen(dname) > MAXNAMLEN + 2) {
404 				msg(gettext("Dumpdates entry name too "
405 				    "long.\n"));
406 				dumpabort();
407 				/*NOTREACHED*/
408 			}
409 			for (i = 0; i < strlen(dname); i++) {
410 				if (isspace(*(dname+i))) {
411 					msg(gettext("Dumpdates entry name may "
412 					    "not contain white space.\n"));
413 					dumpabort();
414 					/*NOTREACHED*/
415 				}
416 			}
417 		} else {
418 			msg(gettext("Missing name for dumpdates entry.\n"));
419 			dumpabort();
420 			/*NOTREACHED*/
421 		}
422 		break;
423 	case 'L':
424 		if (argc > 1) {
425 			argv++;
426 			argc--;
427 			if (**argv == '\0') {
428 				msg(gettext("Missing tape label name\n"));
429 				dumpabort();
430 				/*NOTREACHED*/
431 			}
432 			tlabel = *argv;
433 			if (strlen(tlabel) > (sizeof (spcl.c_label) - 1)) {
434 				tlabel[sizeof (spcl.c_label) - 1] = '\0';
435 				msg(gettext(
436 		    "Truncating label to maximum supported length: `%s'\n"),
437 				    tlabel);
438 			}
439 		} else {
440 			msg(gettext("Missing tape label name\n"));
441 			dumpabort();
442 			/*NOTREACHED*/
443 		}
444 		break;
445 
446 	case 'l':
447 		autoload++;
448 		break;
449 
450 	case 'o':
451 		offline++;
452 		break;
453 
454 	case 'S':
455 		printsize++;
456 		break;
457 
458 #ifdef DEBUG
459 	case 'z':
460 		xflag++;
461 		break;
462 #endif
463 
464 	default:
465 		msg(gettext("Bad option `%c'\n"), arg[-1]);
466 		dumpabort();
467 		/*NOTREACHED*/
468 	}
469 	if (argc > 1) {
470 		argv++;
471 		argc--;
472 		if (**argv == '\0') {
473 			msg(gettext("Bad disk name\n"));
474 			dumpabort();
475 			/*NOTREACHED*/
476 		}
477 		disk = *argv;
478 		disk_dynamic = 0;
479 	}
480 	if (disk == NULL) {
481 		(void) fprintf(stderr, gettext(
482 	"Usage: %s [0123456789fustdWwnNDCcbavloS [argument]] filesystem\n"),
483 		    myname);
484 		Exit(X_ABORT);
485 	}
486 	if (!filenum)
487 		filenum = 1;
488 
489 	if (signal(SIGINT, interrupt) == SIG_IGN)
490 		(void) signal(SIGINT, SIG_IGN);
491 
492 	if (strcmp(tape, "-") == 0) {
493 		pipeout++;
494 		tape = gettext("standard output");
495 		dumpdev = sdumpdev = strdup(tape);
496 		if (dumpdev == NULL) {
497 			saverr = errno;
498 			msg(gettext("Cannot allocate memory: %s\n"),
499 			    strerror(saverr));
500 			dumpabort();
501 			/*NOTREACHED*/
502 		}
503 		/*CONSTANTCONDITION*/
504 		assert(sizeof (spcl.c_label) > 5);
505 		(void) strcpy(spcl.c_label, "none");
506 	} else if (*tape == '+') {
507 		nextdevice();
508 		(void) strcpy(spcl.c_label, tlabel);
509 	} else {
510 		/* if not already set, set diskette to default */
511 		if (diskette && strcmp(tape, DEFTAPE) == 0)
512 			tape = DISKETTE;
513 		nextdevice();
514 		(void) strcpy(spcl.c_label, tlabel);
515 	}
516 	if (cartridge && diskette) {
517 		error = 1;
518 		msg(gettext("Cannot select both cartridge and diskette\n"));
519 	}
520 	if (density && diskette) {
521 		error = 1;
522 		msg(gettext("Cannot select density of diskette\n"));
523 	}
524 	if (tracks && diskette) {
525 		error = 1;
526 		msg(gettext("Cannot select number of tracks of diskette\n"));
527 	}
528 	if (error) {
529 		dumpabort();
530 		/*NOTREACHED*/
531 	}
532 
533 	/*
534 	 * Determine how to default tape size and density
535 	 *
536 	 *		density				tape size
537 	 * 9-track	1600 bpi (160 bytes/.1")	2300 ft.
538 	 * 9-track	6250 bpi (625 bytes/.1")	2300 ft.
539 	 *
540 	 * Most Sun-2's came with 4 track (20MB) cartridge tape drives,
541 	 * while most other machines (Sun-3's and non-Sun's) come with
542 	 * 9 track (45MB) cartridge tape drives.  Some Sun-2's came with
543 	 * 9 track drives, but there is no way for the software to detect
544 	 * which drive type is installed.  Sigh...  We make the gross
545 	 * assumption that #ifdef mc68010 will test for a Sun-2.
546 	 *
547 	 * cartridge	8000 bpi (100 bytes/.1")	425 * tracks ft.
548 	 */
549 	if (density == 0)
550 		density = cartridge ? 100 : 625;
551 	if (tracks == 0)
552 		tracks = 9;
553 	if (!bflag) {
554 		if (cartridge)
555 			ntrec = CARTRIDGETREC;
556 		else if (diskette)
557 			ntrec = NTREC;
558 		else if (density >= 625)
559 			ntrec = HIGHDENSITYTREC;
560 		else
561 			ntrec = NTREC;
562 		/*
563 		 * save ntrec in case we have to change tp_bsize later.
564 		 */
565 		saved_ntrec = (ntrec * (tp_bsize/DEV_BSIZE));
566 	}
567 	if (!diskette) {
568 		tsize *= 12L*10L;
569 		if (cartridge)
570 			tsize *= tracks;
571 	}
572 	rmtinit(msg, Exit);
573 	if (host) {
574 		char	*cp = strchr(host, '@');
575 		if (cp == (char *)0)
576 			cp = host;
577 		else
578 			cp++;
579 
580 		if (rmthost(host, ntrec) == 0) {
581 			msg(gettext("Cannot connect to tape host `%s'\n"), cp);
582 			dumpabort();
583 			/*NOTREACHED*/
584 		}
585 	}
586 	if (signal(SIGHUP, sigAbort) == SIG_IGN)
587 		(void) signal(SIGHUP, SIG_IGN);
588 	if (signal(SIGTRAP, sigAbort) == SIG_IGN)
589 		(void) signal(SIGTRAP, SIG_IGN);
590 	if (signal(SIGFPE, sigAbort) == SIG_IGN)
591 		(void) signal(SIGFPE, SIG_IGN);
592 	if (signal(SIGBUS, sigAbort) == SIG_IGN)
593 		(void) signal(SIGBUS, SIG_IGN);
594 	if (signal(SIGSEGV, sigAbort) == SIG_IGN)
595 		(void) signal(SIGSEGV, SIG_IGN);
596 	if (signal(SIGTERM, sigAbort) == SIG_IGN)
597 		(void) signal(SIGTERM, SIG_IGN);
598 	if (signal(SIGUSR1, sigAbort) == SIG_IGN)
599 		(void) signal(SIGUSR1, SIG_IGN);
600 	if (signal(SIGPIPE, sigAbort) == SIG_IGN)
601 		(void) signal(SIGPIPE, SIG_IGN);
602 
603 	mnttabread();		/* /etc/fstab, /etc/mtab snarfed */
604 
605 	/*
606 	 *	disk can be either the full special file name,
607 	 *	the suffix of the special file name,
608 	 *	the special name missing the leading '/',
609 	 *	the file system name with or without the leading '/'.
610 	 *	NB:  we attempt to avoid dumping the block device
611 	 *	(using rawname) because specfs and the vm system
612 	 *	are not necessarily in sync.
613 	 */
614 
615 	/*
616 	 * Attempt to roll the log if its root user before doing the dump.
617 	 * There's nothing the user can do if we are unable to roll the log,
618 	 * so we'll silently ignore failures.
619 	 */
620 	if (getuid() == 0 && rl_roll_log(disk) != RL_SUCCESS &&
621 	    disk[0] != '/') {
622 		/* Try it again with leading '/'. */
623 		char	*slashed;
624 
625 		slashed = (char *)malloc(strlen(disk) + 2);
626 		if (slashed != (char *)NULL) {
627 			(void) sprintf(slashed, "%c%s", '/', disk);
628 			(void) rl_roll_log(slashed);
629 			free(slashed);
630 		}
631 	}
632 	dt = mnttabsearch(disk, 0);
633 	if (dt != 0) {
634 		filesystem = dt->mnt_mountp;
635 		if (disk_dynamic) {
636 			/* LINTED: disk is not NULL */
637 			free(disk);
638 		}
639 		disk = rawname(dt->mnt_special);
640 		disk_dynamic = (disk != dt->mnt_special);
641 
642 		(void) strncpy(spcl.c_dev, dt->mnt_special,
643 		    sizeof (spcl.c_dev));
644 		spcl.c_dev[sizeof (spcl.c_dev) - 1] = '\0';
645 		(void) strncpy(spcl.c_filesys, dt->mnt_mountp,
646 		    sizeof (spcl.c_filesys));
647 		spcl.c_filesys[sizeof (spcl.c_filesys) - 1] = '\0';
648 	} else {
649 		(void) strncpy(spcl.c_dev, disk, sizeof (spcl.c_dev));
650 		spcl.c_dev[sizeof (spcl.c_dev) - 1] = '\0';
651 #ifdef PARTIAL
652 		/* check for partial filesystem dump */
653 		partial_check();
654 		dt = mnttabsearch(disk, 1);
655 		if (dt != 0) {
656 			filesystem = dt->mnt_mountp;
657 			if (disk_dynamic)
658 				free(disk);
659 			disk = rawname(dt->mnt_special);
660 			disk_dynamic = (disk != dt->mnt_special);
661 
662 			(void) strncpy(spcl.c_filesys,
663 			    "a partial file system", sizeof (spcl.c_filesys));
664 			spcl.c_filesys[sizeof (spcl.c_filesys) - 1] = '\0';
665 		}
666 		else
667 #endif /* PARTIAL */
668 		{
669 			char *old_disk = disk;
670 
671 			(void) strncpy(spcl.c_filesys,
672 			    "an unlisted file system",
673 			    sizeof (spcl.c_filesys));
674 			spcl.c_filesys[sizeof (spcl.c_filesys) - 1] = '\0';
675 
676 			disk = rawname(old_disk);
677 			if (disk != old_disk) {
678 				if (disk_dynamic)
679 					free(old_disk);
680 				disk_dynamic = 1;
681 			}
682 			/*
683 			 * If disk == old_disk, then disk_dynamic's state
684 			 * does not change.
685 			 */
686 		}
687 	}
688 
689 	fi = open64(disk, O_RDONLY);
690 
691 	if (fi < 0) {
692 		saverr = errno;
693 		msg(gettext("Cannot open dump device `%s': %s\n"),
694 		    disk, strerror(saverr));
695 		Exit(X_ABORT);
696 	}
697 
698 	if (sscanf(&incno, "%1d", &spcl.c_level) != 1) {
699 		msg(gettext("Bad dump level `%c' specified\n"), incno);
700 		dumpabort();
701 		/*NOTREACHED*/
702 	}
703 	getitime();		/* /etc/dumpdates snarfed */
704 
705 	sblock = (struct fs *)&sblock_buf;
706 	sync();
707 
708 	bread((diskaddr_t)SBLOCK, (uchar_t *)sblock, (long)SBSIZE);
709 	if ((sblock->fs_magic != FS_MAGIC) &&
710 	    (sblock->fs_magic != MTB_UFS_MAGIC)) {
711 		msg(gettext(
712 	    "Warning - super-block on device `%s' is corrupt - run fsck\n"),
713 		    disk);
714 		dumpabort();
715 		/*NOTREACHED*/
716 	}
717 
718 	if (sblock->fs_magic == FS_MAGIC &&
719 	    (sblock->fs_version != UFS_EFISTYLE4NONEFI_VERSION_2 &&
720 	    sblock->fs_version != UFS_VERSION_MIN)) {
721 		msg(gettext("Unrecognized UFS version: %d\n"),
722 		    sblock->fs_version);
723 		dumpabort();
724 		/*NOTREACHED*/
725 	}
726 
727 	if (sblock->fs_magic == MTB_UFS_MAGIC &&
728 	    (sblock->fs_version < MTB_UFS_VERSION_MIN ||
729 	    sblock->fs_version > MTB_UFS_VERSION_1)) {
730 		msg(gettext("Unrecognized UFS version: %d\n"),
731 		    sblock->fs_version);
732 		dumpabort();
733 		/*NOTREACHED*/
734 	}
735 
736 	/*
737 	 * Try to set up for using mmap(2).  It only works on the block
738 	 * device, but if we can use it, things go somewhat faster.  If
739 	 * we can't open it, we'll silently fall back to the old method
740 	 * (read/memcpy). We also only try this if it's been cleanly
741 	 * unmounted. Dumping a live filesystem this way runs into
742 	 * buffer consistency problems. Of course, we don't support
743 	 * running dump on a mounted filesystem, but some people do it
744 	 * anyway.
745 	 */
746 	if (sblock->fs_clean == FSCLEAN) {
747 		char *block = unrawname(disk);
748 
749 		if (block != NULL) {
750 			mapfd = open(block, O_RDONLY, 0);
751 			free(block);
752 		}
753 	}
754 
755 restart:
756 	bread((diskaddr_t)SBLOCK, (uchar_t *)sblock, (long)SBSIZE);
757 	if ((sblock->fs_magic != FS_MAGIC) &&
758 	    (sblock->fs_magic != MTB_UFS_MAGIC)) {	/* paranoia */
759 		msg(gettext("bad super-block magic number, run fsck\n"));
760 		dumpabort();
761 		/*NOTREACHED*/
762 	}
763 
764 	if (sblock->fs_magic == FS_MAGIC &&
765 	    (sblock->fs_version != UFS_EFISTYLE4NONEFI_VERSION_2 &&
766 	    sblock->fs_version != UFS_VERSION_MIN)) {
767 		msg(gettext("Unrecognized UFS version: %d\n"),
768 		    sblock->fs_version);
769 		dumpabort();
770 		/*NOTREACHED*/
771 	}
772 
773 	if (sblock->fs_magic == MTB_UFS_MAGIC &&
774 	    (sblock->fs_version < MTB_UFS_VERSION_MIN ||
775 	    sblock->fs_version > MTB_UFS_VERSION_1)) {
776 		msg(gettext("Unrecognized UFS version: %d\n"),
777 		    sblock->fs_version);
778 		dumpabort();
779 		/*NOTREACHED*/
780 	}
781 
782 	if (!doingactive)
783 		allocino();
784 
785 	/* XXX should sanity-check the super block before trusting/using it */
786 
787 	/* LINTED XXX time truncated - tolerate until tape format changes */
788 	spcl.c_date = (time32_t)time((time_t *)NULL);
789 	bcopy(&(spcl.c_shadow), c_shadow_save, sizeof (c_shadow_save));
790 
791 	snapdate = is_fssnap_dump(disk);
792 	if (snapdate)
793 		spcl.c_date = snapdate;
794 
795 	if (!printsize) {
796 		msg(gettext("Date of this level %c dump: %s\n"),
797 		    incno, prdate(spcl.c_date));
798 		msg(gettext("Date of last level %c dump: %s\n"),
799 		    (uchar_t)lastincno, prdate(spcl.c_ddate));
800 		msg(gettext("Dumping %s "), disk);
801 		if (filesystem != 0)
802 			msgtail("(%.*s:%s) ",
803 			    /* LINTED unsigned -> signed cast ok */
804 			    (int)sizeof (spcl.c_host), spcl.c_host, filesystem);
805 		msgtail(gettext("to %s.\n"), sdumpdev);
806 	}
807 
808 	esize = f_esize = o_esize = 0;
809 	msiz = roundup(d_howmany(sblock->fs_ipg * sblock->fs_ncg, NBBY),
810 	    TP_BSIZE_MAX);
811 	if (!doingactive) {
812 		clrmap = (uchar_t *)xcalloc(msiz, sizeof (*clrmap));
813 		filmap = (uchar_t *)xcalloc(msiz, sizeof (*filmap));
814 		dirmap = (uchar_t *)xcalloc(msiz, sizeof (*dirmap));
815 		nodmap = (uchar_t *)xcalloc(msiz, sizeof (*nodmap));
816 		shamap = (uchar_t *)xcalloc(msiz, sizeof (*shamap));
817 		activemap = (uchar_t *)xcalloc(msiz, sizeof (*activemap));
818 	} else {
819 		if (clrmap == NULL || filmap == NULL || dirmap == NULL ||
820 		    nodmap == NULL || shamap == NULL || activemap == NULL) {
821 			msg(gettext(
822 	    "Internal error: NULL map pointer while re-dumping active files"));
823 			dumpabort();
824 			/*NOTREACHED*/
825 		}
826 		bzero(clrmap, msiz);
827 		bzero(filmap, msiz);
828 		bzero(dirmap, msiz);
829 		bzero(nodmap, msiz);
830 		bzero(shamap, msiz);
831 		/* retain active map */
832 	}
833 
834 	dumpstate = DS_INIT;
835 	dumptoarchive = 1;
836 
837 	/*
838 	 * Read cylinder group inode-used bitmaps to avoid reading clear inodes.
839 	 */
840 	{
841 		uchar_t *clrp = clrmap;
842 		struct cg *cgp =
843 		    (struct cg *)xcalloc((uint_t)sblock->fs_cgsize, 1);
844 
845 		for (i = 0; i < sblock->fs_ncg; i++) {
846 			bread(fsbtodb(sblock, cgtod(sblock, i)),
847 			    (uchar_t *)cgp, sblock->fs_cgsize);
848 			bcopy(cg_inosused(cgp), clrp,
849 			    (int)sblock->fs_ipg / NBBY);
850 			clrp += sblock->fs_ipg / NBBY;
851 		}
852 		free((char *)cgp);
853 		/* XXX right-shift clrmap one bit.  why? */
854 		for (i = 0; clrp > clrmap; i <<= NBBY) {
855 			i |= *--clrp & ((1<<NBBY) - 1);
856 			*clrp = i >> 1;
857 		}
858 	}
859 
860 	if (!printsize) {
861 		msgp = gettext("Mapping (Pass I) [regular files]\n");
862 		msg(msgp);
863 	}
864 
865 	ino = 0;
866 #ifdef PARTIAL
867 	if (partial_mark(argc, argv)) {
868 #endif /* PARTIAL */
869 		if (!doingactive)
870 			pass(mark, clrmap);	/* mark updates 'x'_esize */
871 		else
872 			pass(active_mark, clrmap);	/* updates 'x'_esize */
873 #ifdef PARTIAL
874 	}
875 #endif /* PARTIAL */
876 	do {
877 		if (!printsize) {
878 			msgp = gettext("Mapping (Pass II) [directories]\n");
879 			msg(msgp);
880 		}
881 		nadded = 0;
882 		ino = 0;
883 		pass(add, dirmap);
884 	} while (nadded);
885 
886 	ino = 0; /* adjust estimated size for shadow inodes */
887 	pass(markshad, nodmap);
888 	ino = 0;
889 	pass(estshad, shamap);
890 	freeshad();
891 
892 	bmapest(clrmap);
893 	bmapest(nodmap);
894 	esize = o_esize + f_esize;
895 	if (diskette) {
896 		/* estimate number of floppies */
897 		if (tsize != 0)
898 			fetapes = (double)(esize + ntrec) / (double)tsize;
899 	} else if (cartridge) {
900 		/*
901 		 * Estimate number of tapes, assuming streaming stops at
902 		 * the end of each block written, and not in mid-block.
903 		 * Assume no erroneous blocks; this can be compensated for
904 		 * with an artificially low tape size.
905 		 */
906 		tenthsperirg = 16;	/* actually 15.48, says Archive */
907 		if (tsize != 0)
908 			fetapes = ((double)esize /* blocks */
909 			    * (tp_bsize		/* bytes/block */
910 			    * (1.0/density))	/* 0.1" / byte */
911 			    +
912 			    (double)esize	/* blocks */
913 			    * (1.0/ntrec)	/* streaming-stops per block */
914 			    * tenthsperirg)	/* 0.1" / streaming-stop */
915 			    * (1.0 / tsize);	/* tape / 0.1" */
916 	} else {
917 		/* Estimate number of tapes, for old fashioned 9-track tape */
918 #ifdef sun
919 		/* sun has long irg's */
920 		tenthsperirg = (density == 625) ? 6 : 12;
921 #else
922 		tenthsperirg = (density == 625) ? 5 : 8;
923 #endif
924 		if (tsize != 0)
925 			fetapes = ((double)esize /* blocks */
926 			    * (tp_bsize		/* bytes / block */
927 			    * (1.0/density))	/* 0.1" / byte */
928 			    +
929 			    (double)esize	/* blocks */
930 			    * (1.0/ntrec)	/* IRG's / block */
931 			    * tenthsperirg)	/* 0.1" / IRG */
932 			    * (1.0 / tsize);	/* tape / 0.1" */
933 	}
934 
935 	etapes = fetapes;	/* truncating assignment */
936 	etapes++;
937 	/* count the nodemap on each additional tape */
938 	for (i = 1; i < etapes; i++)
939 		bmapest(nodmap);
940 	/*
941 	 * If the above bmapest is called, it changes o_esize and f_esize.
942 	 * So we will recalculate esize here anyway to make sure.
943 	 * Also, add tape headers and trailer records.
944 	 */
945 	esize = o_esize + f_esize + etapes + ntrec;
946 
947 	/*
948 	 * If the estimated number of tp_bsize tape blocks is greater than
949 	 * INT_MAX we have to adjust tp_bsize and ntrec to handle
950 	 * the larger dump.  esize is an estimate, so we 'fudge'
951 	 * INT_MAX a little.  If tp_bsize is adjusted, it will be adjusted
952 	 * to the size needed for this dump (2048, 4096, 8192, ...)
953 	 */
954 	if (esize > (INT_MAX - FUDGE_FACTOR)) { /* esize is too big */
955 		forceflag++;
956 		esize_shift =
957 		    ((esize + (INT_MAX - FUDGE_FACTOR) - 1)/
958 		    ((u_offset_t)(INT_MAX - FUDGE_FACTOR))) - 1;
959 		if ((esize_shift > ESIZE_SHIFT_MAX) || (ntrec == 0)) {
960 			msgp = gettext(
961 	"Block factor %d ('b' flag) is too small for this size dump.");
962 			msg(msgp, saved_ntrec);
963 			dumpabort();
964 			/*NOTREACHED*/
965 		}
966 		/*
967 		 * recalculate esize from:
968 		 * o_esize - header tape records
969 		 * (f_esize + (num_mult -1)) >> esize_shift - new non-header
970 		 *	tape records for files/maps
971 		 * etapes - TS_TAPE records
972 		 * ntrec - TS_END records
973 		 *
974 		 * ntrec is adjusted so a tape record is still 'b' flag
975 		 * number of DEV_BSIZE (512) in size
976 		 */
977 		new_mult = (tp_bsize << esize_shift)/tp_bsize;
978 		tp_bsize = (tp_bsize << esize_shift);
979 		esize = o_esize + ((f_esize +
980 		    (new_mult - 1)) >> esize_shift) + etapes + ntrec;
981 		ntrec = (saved_ntrec/(tp_bsize/DEV_BSIZE));
982 	}
983 	if (forceflag != 0) {
984 		msgp = gettext(
985 		    "Forcing larger tape block size (%d).\n");
986 		msg(msgp, tp_bsize);
987 	}
988 	alloctape();			/* allocate tape buffers */
989 
990 	assert((tp_bsize / DEV_BSIZE != 0) && (tp_bsize % DEV_BSIZE == 0));
991 	/*
992 	 * If all we wanted was the size estimate,
993 	 * just print it out and exit.
994 	 */
995 	if (printsize) {
996 		(void) printf("%llu\n", esize * tp_bsize);
997 		Exit(0);
998 	}
999 
1000 	if (tsize != 0) {
1001 		if (diskette)
1002 			msgp = gettext(
1003 			    "Estimated %lld blocks (%s) on %3.2f diskettes.\n");
1004 		else
1005 			msgp = gettext(
1006 			    "Estimated %lld blocks (%s) on %3.2f tapes.\n");
1007 
1008 		msg(msgp,
1009 		    (esize*(tp_bsize/DEV_BSIZE)), mb(esize), fetapes);
1010 	} else {
1011 		msgp = gettext("Estimated %lld blocks (%s).\n");
1012 		msg(msgp, (esize*(tp_bsize/DEV_BSIZE)), mb(esize));
1013 	}
1014 
1015 	dumpstate = DS_CLRI;
1016 
1017 	otape(1);			/* bitmap is the first to tape write */
1018 	*telapsed = 0;
1019 	(void) time(tstart_writing);
1020 
1021 	/* filmap indicates all non-directory inodes */
1022 	{
1023 		uchar_t *np, *fp, *dp;
1024 		np = nodmap;
1025 		dp = dirmap;
1026 		fp = filmap;
1027 		for (i = 0; i < msiz; i++)
1028 			*fp++ = *np++ ^ *dp++;
1029 	}
1030 
1031 	while (dumpstate != DS_DONE) {
1032 		/*
1033 		 * When we receive EOT notification from
1034 		 * the writer, the signal handler calls
1035 		 * rollforward and then jumps here.
1036 		 */
1037 		(void) setjmp(checkpoint_buf);
1038 		switch (dumpstate) {
1039 		case DS_INIT:
1040 			/*
1041 			 * We get here if a tape error occurred
1042 			 * after releasing the name lock but before
1043 			 * the volume containing the last of the
1044 			 * dir info was completed.  We have to start
1045 			 * all over in this case.
1046 			 */
1047 			{
1048 				char *rmsg = gettext(
1049 		"Warning - output error occurred after releasing name lock\n\
1050 \tThe dump will restart\n");
1051 				msg(rmsg);
1052 				goto restart;
1053 			}
1054 			/* NOTREACHED */
1055 		case DS_START:
1056 		case DS_CLRI:
1057 			ino = UFSROOTINO;
1058 			dumptoarchive = 1;
1059 			bitmap(clrmap, TS_CLRI);
1060 			nextstate(DS_BITS);
1061 			/* FALLTHROUGH */
1062 		case DS_BITS:
1063 			ino = UFSROOTINO;
1064 			dumptoarchive = 1;
1065 			if (BIT(UFSROOTINO, nodmap))	/* empty dump check */
1066 				bitmap(nodmap, TS_BITS);
1067 			nextstate(DS_DIRS);
1068 			if (!doingverify) {
1069 				msgp = gettext(
1070 				    "Dumping (Pass III) [directories]\n");
1071 				msg(msgp);
1072 			}
1073 			/* FALLTHROUGH */
1074 		case DS_DIRS:
1075 			dumptoarchive = 1;
1076 			pass(dirdump, dirmap);
1077 			nextstate(DS_FILES);
1078 			if (!doingverify) {
1079 				msgp = gettext(
1080 				    "Dumping (Pass IV) [regular files]\n");
1081 				msg(msgp);
1082 			}
1083 			/* FALLTHROUGH */
1084 		case DS_FILES:
1085 			dumptoarchive = 0;
1086 
1087 			pass(lf_dump, filmap);
1088 
1089 			flushcmds();
1090 			dumpstate = DS_END;	/* don't reset ino */
1091 			/* FALLTHROUGH */
1092 		case DS_END:
1093 			dumptoarchive = 1;
1094 			spcl.c_type = TS_END;
1095 			for (i = 0; i < ntrec; i++) {
1096 				spclrec();
1097 			}
1098 			flusht();
1099 			break;
1100 		case DS_DONE:
1101 			break;
1102 		default:
1103 			msg(gettext("Internal state error\n"));
1104 			dumpabort();
1105 			/*NOTREACHED*/
1106 		}
1107 	}
1108 
1109 	if ((! doingactive) && (! active))
1110 		trewind();
1111 	if (verify && !doingverify) {
1112 		msgp = gettext("Finished writing last dump volume\n");
1113 		msg(msgp);
1114 		Exit(X_VERIFY);
1115 	}
1116 	if (spcl.c_volume > 1)
1117 		(void) snprintf(msgbuf, sizeof (msgbuf),
1118 		    gettext("%lld blocks (%s) on %ld volumes"),
1119 		    ((uint64_t)spcl.c_tapea*(tp_bsize/DEV_BSIZE)),
1120 		    mb((u_offset_t)(unsigned)(spcl.c_tapea)),
1121 		    spcl.c_volume);
1122 	else
1123 		(void) snprintf(msgbuf, sizeof (msgbuf),
1124 		    gettext("%lld blocks (%s) on 1 volume"),
1125 		    ((uint64_t)spcl.c_tapea*(tp_bsize/DEV_BSIZE)),
1126 		    mb((u_offset_t)(unsigned)(spcl.c_tapea)));
1127 	if (timeclock((time_t)0) != (time_t)0) {
1128 		(void) snprintf(kbsbuf, sizeof (kbsbuf),
1129 		    gettext(" at %ld KB/sec"),
1130 		    (long)(((float)spcl.c_tapea / (float)timeclock((time_t)0))
1131 		    * 1000.0));
1132 		(void) strcat(msgbuf, kbsbuf);
1133 	}
1134 	(void) strcat(msgbuf, "\n");
1135 	msg(msgbuf);
1136 	(void) timeclock((time_t)-1);
1137 
1138 	if (archive)
1139 		msg(gettext("Archiving dump to `%s'\n"), archivefile);
1140 	if (active && !verify) {
1141 		nextstate(DS_INIT);
1142 		activepass();
1143 		goto restart;
1144 	}
1145 	msgp = gettext("DUMP IS DONE\n");
1146 	msg(msgp);
1147 	broadcast(msgp);
1148 	if (! doingactive)
1149 		putitime();
1150 	Exit(X_FINOK);
1151 
1152 	/*NOTREACHED*/
1153 	return (0);
1154 }
1155 
1156 void
1157 sigAbort(int sig)
1158 {
1159 	char	*sigtype;
1160 
1161 	switch (sig) {
1162 	case SIGHUP:
1163 		sigtype = "SIGHUP";
1164 		break;
1165 	case SIGTRAP:
1166 		sigtype = "SIGTRAP";
1167 		break;
1168 	case SIGFPE:
1169 		sigtype = "SIGFPE";
1170 		break;
1171 	case SIGBUS:
1172 		msg(gettext("%s  ABORTING!\n"), "SIGBUS()");
1173 		(void) signal(SIGUSR2, SIG_DFL);
1174 		abort();
1175 		/*NOTREACHED*/
1176 	case SIGSEGV:
1177 		msg(gettext("%s  ABORTING!\n"), "SIGSEGV()");
1178 		(void) signal(SIGUSR2, SIG_DFL);
1179 		abort();
1180 		/*NOTREACHED*/
1181 	case SIGALRM:
1182 		sigtype = "SIGALRM";
1183 		break;
1184 	case SIGTERM:
1185 		sigtype = "SIGTERM";
1186 		break;
1187 	case SIGPIPE:
1188 		msg(gettext("Broken pipe\n"));
1189 		dumpabort();
1190 		/*NOTREACHED*/
1191 	default:
1192 		sigtype = "SIGNAL";
1193 		break;
1194 	}
1195 	msg(gettext("%s()  try rewriting\n"), sigtype);
1196 	if (pipeout) {
1197 		msg(gettext("Unknown signal, Cannot recover\n"));
1198 		dumpabort();
1199 		/*NOTREACHED*/
1200 	}
1201 	msg(gettext("Rewriting attempted as response to unknown signal.\n"));
1202 	(void) fflush(stderr);
1203 	(void) fflush(stdout);
1204 	close_rewind();
1205 	Exit(X_REWRITE);
1206 }
1207 
1208 /* Note that returned value is malloc'd if != cp && != NULL */
1209 char *
1210 rawname(char *cp)
1211 {
1212 	struct stat64 st;
1213 	char *dp;
1214 	extern char *getfullrawname();
1215 
1216 	if (stat64(cp, &st) < 0 || (st.st_mode & S_IFMT) != S_IFBLK)
1217 		return (cp);
1218 
1219 	dp = getfullrawname(cp);
1220 	if (dp == 0)
1221 		return (0);
1222 	if (*dp == '\0') {
1223 		free(dp);
1224 		return (0);
1225 	}
1226 
1227 	if (stat64(dp, &st) < 0 || (st.st_mode & S_IFMT) != S_IFCHR) {
1228 		free(dp);
1229 		return (cp);
1230 	}
1231 
1232 	return (dp);
1233 }
1234 
1235 static char *
1236 mb(u_offset_t blks)
1237 {
1238 	static char buf[16];
1239 
1240 	if (blks < 1024)
1241 		(void) snprintf(buf, sizeof (buf), "%lldKB", blks);
1242 	else
1243 		(void) snprintf(buf, sizeof (buf), "%.2fMB",
1244 		    ((double)(blks*tp_bsize)) / (double)(1024*1024));
1245 	return (buf);
1246 }
1247 
1248 #ifdef signal
1249 void (*nsignal(int sig, void (*act)(int)))(int)
1250 {
1251 	struct sigaction sa, osa;
1252 
1253 	sa.sa_handler = act;
1254 	(void) sigemptyset(&sa.sa_mask);
1255 	sa.sa_flags = SA_RESTART;
1256 	if (sigaction(sig, &sa, &osa) < 0)
1257 		return ((void (*)(int))-1);
1258 	return (osa.sa_handler);
1259 }
1260 #endif
1261 
1262 static void
1263 nextstate(int state)
1264 {
1265 	/* LINTED assigned value never used - kept for documentary purposes */
1266 	dumpstate = state;
1267 	/* LINTED assigned value never used - kept for documentary purposes */
1268 	ino = 0;
1269 	/* LINTED assigned value never used - kept for documentary purposes */
1270 	pos = 0;
1271 	leftover = 0;
1272 }
1273 
1274 /*
1275  * timeclock() function, for keeping track of how much time we've spent
1276  * writing to the tape device.  it always returns the amount of time
1277  * already spent, in milliseconds.  if you pass it a positive, then that's
1278  * telling it that we're writing, so the time counts.  if you pass it a
1279  * zero, then that's telling it we're not writing; perhaps we're waiting
1280  * for user input.
1281  *
1282  * a state of -1 resets everything.
1283  */
1284 time32_t
1285 timeclock(time32_t state)
1286 {
1287 	static int *currentState = NULL;
1288 	static struct timeval *clockstart;
1289 	static time32_t *emilli;
1290 
1291 	struct timeval current[1];
1292 	int fd, saverr;
1293 
1294 #ifdef DEBUG
1295 	fprintf(stderr, "pid=%d timeclock ", getpid());
1296 	if (state == (time32_t)-1)
1297 		fprintf(stderr, "cleared\n");
1298 	else if (state > 0)
1299 		fprintf(stderr, "ticking\n");
1300 	else
1301 		fprintf(stderr, "paused\n");
1302 #endif /* DEBUG */
1303 
1304 	/* if we haven't setup the shared memory, init */
1305 	if (currentState == (int *)NULL) {
1306 		if ((fd = open("/dev/zero", O_RDWR)) < 0) {
1307 			saverr = errno;
1308 			msg(gettext("Cannot open `%s': %s\n"),
1309 			    "/dev/zero", strerror(saverr));
1310 			dumpabort();
1311 			/*NOTREACHED*/
1312 		}
1313 		/*LINTED [mmap always returns an aligned value]*/
1314 		currentState = (int *)mmap((char *)0, getpagesize(),
1315 		    PROT_READ|PROT_WRITE, MAP_SHARED, fd, (off_t)0);
1316 		if (currentState == (int *)-1) {
1317 			saverr = errno;
1318 			msg(gettext(
1319 			    "Cannot memory map monitor variables: %s\n"),
1320 			    strerror(saverr));
1321 			dumpabort();
1322 			/*NOTREACHED*/
1323 		}
1324 		(void) close(fd);
1325 
1326 		/* LINTED currentState is sufficiently aligned */
1327 		clockstart = (struct timeval *)(currentState + 1);
1328 		emilli = (time32_t *)(clockstart + 1);
1329 		/* Note everything is initialized to zero via /dev/zero */
1330 	}
1331 
1332 	if (state == (time32_t)-1) {
1333 		bzero(clockstart, sizeof (*clockstart));
1334 		*currentState = 0;
1335 		*emilli = (time32_t)0;
1336 		return (0);
1337 	}
1338 
1339 	(void) gettimeofday(current, NULL);
1340 
1341 	if (*currentState != 0) {
1342 		current->tv_usec += 1000000;
1343 		current->tv_sec--;
1344 
1345 		/* LINTED: result will fit in a time32_t */
1346 		*emilli += (current->tv_sec - clockstart->tv_sec) * 1000;
1347 		/* LINTED: result will fit in a time32_t */
1348 		*emilli += (current->tv_usec - clockstart->tv_usec) / 1000;
1349 	}
1350 
1351 	if (state != 0)
1352 		bcopy(current, clockstart, sizeof (current));
1353 
1354 	*currentState = state;
1355 
1356 	return (*emilli);
1357 }
1358 
1359 static int
1360 statcmp(const struct stat64 *left, const struct stat64 *right)
1361 {
1362 	int result = 1;
1363 
1364 	if ((left->st_dev == right->st_dev) &&
1365 	    (left->st_ino == right->st_ino) &&
1366 	    (left->st_mode == right->st_mode) &&
1367 	    (left->st_nlink == right->st_nlink) &&
1368 	    (left->st_uid == right->st_uid) &&
1369 	    (left->st_gid == right->st_gid) &&
1370 	    (left->st_rdev == right->st_rdev) &&
1371 	    (left->st_ctim.tv_sec == right->st_ctim.tv_sec) &&
1372 	    (left->st_ctim.tv_nsec == right->st_ctim.tv_nsec) &&
1373 	    (left->st_mtim.tv_sec == right->st_mtim.tv_sec) &&
1374 	    (left->st_mtim.tv_nsec == right->st_mtim.tv_nsec)) {
1375 		/*
1376 		 * Unlike in the ufsrestore version
1377 		 * st_blocks and st_blksiz are not
1378 		 * compared. The reason for this is
1379 		 * problems with zfs dump files. Zfs
1380 		 * changes it's statistics in those
1381 		 * fields.
1382 		 */
1383 		result = 0;
1384 	}
1385 
1386 	return (result);
1387 }
1388 
1389 /*
1390  * Safely open a file or device.
1391  */
1392 static int
1393 safe_open_common(const char *filename, int mode, int perms, int device)
1394 {
1395 	int fd;
1396 	int working_mode;
1397 	int saverr;
1398 	char *errtext;
1399 	struct stat64 pre_stat, pre_lstat;
1400 	struct stat64 post_stat, post_lstat;
1401 
1402 	/*
1403 	 * Don't want to be spoofed into trashing something we
1404 	 * shouldn't, thus the following rigamarole.  If it doesn't
1405 	 * exist, we create it and proceed.  Otherwise, require that
1406 	 * what's there be a real file with no extraneous links and
1407 	 * owned by whoever ran us.
1408 	 *
1409 	 * The silliness with using both lstat() and fstat() is to avoid
1410 	 * race-condition games with someone replacing the file with a
1411 	 * symlink after we've opened it.  If there was an flstat(),
1412 	 * we wouldn't need the fstat().
1413 	 *
1414 	 * The initial open with the hard-coded flags is ok even if we
1415 	 * are intending to open only for reading.  If it succeeds,
1416 	 * then the file did not exist, and we'll synthesize an appropriate
1417 	 * complaint below.  Otherwise, it does exist, so we won't be
1418 	 * truncating it with the open.
1419 	 */
1420 	if ((fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL|O_LARGEFILE,
1421 	    perms)) < 0) {
1422 		if (errno == EEXIST) {
1423 			if (lstat64(filename, &pre_lstat) < 0) {
1424 				return (-1);
1425 			}
1426 
1427 			if (stat64(filename, &pre_stat) < 0) {
1428 				return (-1);
1429 			}
1430 
1431 			working_mode = mode & (O_WRONLY|O_RDWR|O_RDONLY);
1432 			working_mode |= O_LARGEFILE;
1433 			if ((fd = open(filename, working_mode)) < 0) {
1434 				if (errno == ENOENT) {
1435 					errtext = gettext(
1436 "Unexpected condition detected: %s used to exist, but doesn't any longer\n");
1437 					msg(errtext, filename);
1438 					syslog(LOG_WARNING, errtext, filename);
1439 					errno = ENOENT;
1440 				}
1441 				return (-1);
1442 			}
1443 
1444 			if (lstat64(filename, &post_lstat) < 0) {
1445 				saverr = errno;
1446 				(void) close(fd);
1447 				errno = saverr;
1448 				return (-1);
1449 			}
1450 
1451 			if (fstat64(fd, &post_stat) < 0) {
1452 				saverr = errno;
1453 				(void) close(fd);
1454 				errno = saverr;
1455 				return (-1);
1456 			}
1457 
1458 			/*
1459 			 * Can't just use memcmp(3C), because the access
1460 			 * time is updated by open(2).
1461 			 */
1462 			if (statcmp(&pre_lstat, &post_lstat) != 0) {
1463 				errtext = gettext("Unexpected change detected: "
1464 				    "%s's lstat(2) information changed\n");
1465 				msg(errtext, filename);
1466 				syslog(LOG_WARNING, errtext, filename);
1467 				errno = EPERM;
1468 				return (-1);
1469 			}
1470 
1471 			if (statcmp(&pre_stat, &post_stat) != 0) {
1472 				errtext = gettext("Unexpected change detected: "
1473 				    "%s's stat(2) information changed\n"),
1474 				    msg(errtext, filename);
1475 				syslog(LOG_WARNING, errtext, filename);
1476 				errno = EPERM;
1477 				return (-1);
1478 			}
1479 
1480 			/*
1481 			 * If inode, device, or type are wrong, bail out.
1482 			 * Note using post_stat instead of post_lstat for the
1483 			 * S_ISCHR() test.  This is to allow the /dev ->
1484 			 * /devices bit to work, as long as the final target
1485 			 * is a character device (i.e., raw disk or tape).
1486 			 */
1487 			if (device && !(S_ISCHR(post_stat.st_mode)) &&
1488 			    !(S_ISFIFO(post_stat.st_mode)) &&
1489 			    !(S_ISREG(post_lstat.st_mode))) {
1490 				errtext = gettext("Unexpected condition "
1491 				    "detected: %s is not a supported device\n"),
1492 				    msg(errtext, filename);
1493 				syslog(LOG_WARNING, errtext, filename);
1494 				(void) close(fd);
1495 				errno = EPERM;
1496 				return (-1);
1497 			} else if (!device &&
1498 			    (!S_ISREG(post_lstat.st_mode) ||
1499 			    (post_stat.st_ino != post_lstat.st_ino) ||
1500 			    (post_stat.st_dev != post_lstat.st_dev))) {
1501 				errtext = gettext("Unexpected condition "
1502 				    "detected: %s is not a regular file\n"),
1503 				    msg(errtext, filename);
1504 				syslog(LOG_WARNING, errtext, filename);
1505 				(void) close(fd);
1506 				errno = EPERM;
1507 				return (-1);
1508 			}
1509 
1510 			/*
1511 			 * Bad link count implies someone's linked our
1512 			 * target to something else, which we probably
1513 			 * shouldn't step on.
1514 			 */
1515 			if (post_lstat.st_nlink != 1) {
1516 				errtext = gettext("Unexpected condition "
1517 				    "detected: %s must have exactly one "
1518 				    "link\n"), msg(errtext, filename);
1519 				syslog(LOG_WARNING, errtext, filename);
1520 				(void) close(fd);
1521 				errno = EPERM;
1522 				return (-1);
1523 			}
1524 			/*
1525 			 * Root might make a file, but non-root might
1526 			 * need to open it.  If the permissions let us
1527 			 * get this far, then let it through.
1528 			 */
1529 			if (post_lstat.st_uid != getuid() &&
1530 			    post_lstat.st_uid != 0) {
1531 				errtext = gettext("Unsupported "
1532 				    "condition detected: %s "
1533 				    "must be owned by uid %ld or 0\n"),
1534 				    msg(errtext, filename, (long)getuid());
1535 				syslog(LOG_WARNING, errtext, filename,
1536 				    (long)getuid());
1537 				(void) close(fd);
1538 				errno = EPERM;
1539 				return (-1);
1540 			}
1541 			if (mode & O_TRUNC) {
1542 				if (ftruncate(fd, (off_t)0) < 0) {
1543 					msg("ftruncate(%s): %s\n",
1544 					    filename, strerror(errno));
1545 					(void) close(fd);
1546 					return (-1);
1547 				}
1548 			}
1549 		} else {
1550 			/*
1551 			 * Didn't exist, but couldn't open it.
1552 			 */
1553 			return (-1);
1554 		}
1555 	} else {
1556 		/*
1557 		 * If truncating open succeeded for a read-only open,
1558 		 * bail out, as we really shouldn't have succeeded.
1559 		 */
1560 		if (mode & O_RDONLY) {
1561 			/* Undo the O_CREAT */
1562 			(void) unlink(filename);
1563 			msg("open(%s): %s\n",
1564 			    filename, strerror(ENOENT));
1565 			(void) close(fd);
1566 			errno = ENOENT;
1567 			return (-1);
1568 		}
1569 	}
1570 
1571 	return (fd);
1572 }
1573 
1574 /*
1575  * Safely open a file.
1576  */
1577 int
1578 safe_file_open(const char *filename, int mode, int perms)
1579 {
1580 	return (safe_open_common(filename, mode, perms, 0));
1581 }
1582 
1583 /*
1584  * Safely open a device.
1585  */
1586 int
1587 safe_device_open(const char *filename, int mode, int perms)
1588 {
1589 	return (safe_open_common(filename, mode, perms, 1));
1590 }
1591 
1592 /*
1593  * STDIO version of safe_open
1594  */
1595 FILE *
1596 safe_fopen(const char *filename, const char *smode, int perms)
1597 {
1598 	int fd;
1599 	int bmode;
1600 
1601 	/*
1602 	 * accepts only modes  "r", "r+", and "w"
1603 	 */
1604 	if (smode[0] == 'r') {
1605 		if (smode[1] == '\0') {
1606 			bmode = O_RDONLY;
1607 		} else if ((smode[1] == '+') && (smode[2] == '\0')) {
1608 			bmode = O_RDWR;
1609 		}
1610 	} else if ((smode[0] == 'w') && (smode[1] == '\0')) {
1611 		bmode = O_WRONLY;
1612 	} else {
1613 		msg(gettext("internal error: safe_fopen: invalid mode `%s'\n"),
1614 		    smode);
1615 		return (NULL);
1616 	}
1617 
1618 	fd = safe_file_open(filename, bmode, perms);
1619 
1620 	/*
1621 	 * caller is expected to report error.
1622 	 */
1623 	if (fd >= 0)
1624 		return (fdopen(fd, smode));
1625 
1626 	return ((FILE *)NULL);
1627 }
1628 
1629 void
1630 child_chdir(void)
1631 {
1632 	char name[MAXPATHLEN];
1633 
1634 	if (debug_chdir != NULL) {
1635 		snprintf(name, sizeof (name), "%s/%ld",
1636 		    debug_chdir, (long)getpid());
1637 		if (mkdir(name, 0755) < 0)
1638 			msg("mkdir(%s): %s", name, strerror(errno));
1639 		if (chdir(name) < 0)
1640 			msg("chdir(%s): %s", name, strerror(errno));
1641 	}
1642 }
1643