xref: /netbsd/sbin/dump/tape.c (revision c4a72b64)
1 /*	$NetBSD: tape.c,v 1.38 2002/08/18 08:03:35 yamt Exp $	*/
2 
3 /*-
4  * Copyright (c) 1980, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 #ifndef lint
38 #if 0
39 static char sccsid[] = "@(#)tape.c	8.4 (Berkeley) 5/1/95";
40 #else
41 __RCSID("$NetBSD: tape.c,v 1.38 2002/08/18 08:03:35 yamt Exp $");
42 #endif
43 #endif /* not lint */
44 
45 #include <sys/param.h>
46 #include <sys/socket.h>
47 #include <sys/time.h>
48 #include <sys/wait.h>
49 #include <ufs/ufs/dinode.h>
50 #include <sys/ioctl.h>
51 #include <sys/mtio.h>
52 
53 #include <protocols/dumprestore.h>
54 
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <setjmp.h>
58 #include <signal.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <time.h>
63 #include <unistd.h>
64 
65 #include "dump.h"
66 #include "pathnames.h"
67 
68 int	writesize;		/* size of malloc()ed buffer for tape */
69 long	lastspclrec = -1;	/* tape block number of last written header */
70 int	trecno = 0;		/* next record to write in current block */
71 extern	long blocksperfile;	/* number of blocks per output file */
72 long	blocksthisvol;		/* number of blocks on current output file */
73 extern	int ntrec;		/* blocking factor on tape */
74 extern	int cartridge;
75 extern	char *host;
76 char	*nexttape;
77 
78 static	ssize_t atomic_read(int, char *, int);
79 static	ssize_t atomic_write(int, char *, int);
80 static	void doslave(int, int);
81 static	void enslave(void);
82 static	void flushtape(void);
83 static	void killall(void);
84 static	void proceed(int);
85 static	void rollforward(void);
86 static	void sigpipe(int);
87 static	void tperror(int);
88 
89 /*
90  * Concurrent dump mods (Caltech) - disk block reading and tape writing
91  * are exported to several slave processes.  While one slave writes the
92  * tape, the others read disk blocks; they pass control of the tape in
93  * a ring via signals. The parent process traverses the file system and
94  * sends writeheader()'s and lists of daddr's to the slaves via pipes.
95  * The following structure defines the instruction packets sent to slaves.
96  */
97 struct req {
98 	daddr_t dblk;
99 	int count;
100 };
101 int reqsiz;
102 
103 #define SLAVES 3		/* 1 slave writing, 1 reading, 1 for slack */
104 struct slave {
105 	int tapea;		/* header number at start of this chunk */
106 	int count;		/* count to next header (used for TS_TAPE */
107 				/* after EOT) */
108 	int inode;		/* inode that we are currently dealing with */
109 	int fd;			/* FD for this slave */
110 	int pid;		/* PID for this slave */
111 	int sent;		/* 1 == we've sent this slave requests */
112 	int firstrec;		/* record number of this block */
113 	char (*tblock)[TP_BSIZE]; /* buffer for data blocks */
114 	struct req *req;	/* buffer for requests */
115 } slaves[SLAVES+1];
116 struct slave *slp;
117 
118 char	(*nextblock)[TP_BSIZE];
119 
120 static time_t tstart_volume;	/* time of volume start */
121 static int tapea_volume;	/* value of spcl.c_tapea at volume start */
122 
123 int master;		/* pid of master, for sending error signals */
124 int tenths;		/* length of tape used per block written */
125 static int caught;	/* have we caught the signal to proceed? */
126 static int ready;	/* have we reached the lock point without having */
127 			/* received the SIGUSR2 signal from the prev slave? */
128 static jmp_buf jmpbuf;	/* where to jump to if we are ready when the */
129 			/* SIGUSR2 arrives from the previous slave */
130 
131 int
132 alloctape(void)
133 {
134 	int pgoff = getpagesize() - 1;
135 	char *buf;
136 	int i;
137 
138 	writesize = ntrec * TP_BSIZE;
139 	reqsiz = (ntrec + 1) * sizeof(struct req);
140 	/*
141 	 * CDC 92181's and 92185's make 0.8" gaps in 1600-bpi start/stop mode
142 	 * (see DEC TU80 User's Guide).  The shorter gaps of 6250-bpi require
143 	 * repositioning after stopping, i.e, streaming mode, where the gap is
144 	 * variable, 0.30" to 0.45".  The gap is maximal when the tape stops.
145 	 */
146 	if (blocksperfile == 0 && !unlimited)
147 		tenths = writesize / density +
148 		    (cartridge ? 16 : density == 625 ? 5 : 8);
149 	/*
150 	 * Allocate tape buffer contiguous with the array of instruction
151 	 * packets, so flushtape() can write them together with one write().
152 	 * Align tape buffer on page boundary to speed up tape write().
153 	 */
154 	for (i = 0; i <= SLAVES; i++) {
155 		buf = (char *)
156 		    xmalloc((unsigned)(reqsiz + writesize + pgoff + TP_BSIZE));
157 		slaves[i].tblock = (char (*)[TP_BSIZE])
158 		    (((long)&buf[ntrec + 1] + pgoff) &~ pgoff);
159 		slaves[i].req = (struct req *)slaves[i].tblock - ntrec - 1;
160 	}
161 	slp = &slaves[0];
162 	slp->count = 1;
163 	slp->tapea = 0;
164 	slp->firstrec = 0;
165 	nextblock = slp->tblock;
166 	return(1);
167 }
168 
169 void
170 writerec(char *dp, int isspcl)
171 {
172 
173 	slp->req[trecno].dblk = (daddr_t)0;
174 	slp->req[trecno].count = 1;
175 	*(union u_spcl *)(*(nextblock)++) = *(union u_spcl *)dp;
176 	if (isspcl)
177 		lastspclrec = iswap32(spcl.c_tapea);
178 	trecno++;
179 	spcl.c_tapea = iswap32(iswap32(spcl.c_tapea) +1);
180 	if (trecno >= ntrec)
181 		flushtape();
182 }
183 
184 void
185 dumpblock(daddr_t blkno, int size)
186 {
187 	int avail, tpblks, dblkno;
188 
189 	dblkno = fsatoda(ufsib, blkno);
190 	tpblks = size >> tp_bshift;
191 	while ((avail = MIN(tpblks, ntrec - trecno)) > 0) {
192 		slp->req[trecno].dblk = dblkno;
193 		slp->req[trecno].count = avail;
194 		trecno += avail;
195 		spcl.c_tapea = iswap32(iswap32(spcl.c_tapea) + avail);
196 		if (trecno >= ntrec)
197 			flushtape();
198 		dblkno += avail << (tp_bshift - dev_bshift);
199 		tpblks -= avail;
200 	}
201 }
202 
203 int	nogripe = 0;
204 
205 static void
206 tperror(int signo)
207 {
208 
209 	if (pipeout) {
210 		msg("write error on %s\n", tape);
211 		quit("Cannot recover\n");
212 		/* NOTREACHED */
213 	}
214 	msg("write error %ld blocks into volume %d\n", blocksthisvol, tapeno);
215 	broadcast("DUMP WRITE ERROR!\n");
216 	if (!query("Do you want to restart?"))
217 		dumpabort(0);
218 	msg("Closing this volume.  Prepare to restart with new media;\n");
219 	msg("this dump volume will be rewritten.\n");
220 	killall();
221 	nogripe = 1;
222 	close_rewind();
223 	Exit(X_REWRITE);
224 }
225 
226 static void
227 sigpipe(int signo)
228 {
229 
230 	quit("Broken pipe\n");
231 }
232 
233 /*
234  * do_stats --
235  *	Update xferrate stats
236  */
237 time_t
238 do_stats(void)
239 {
240 	time_t tnow, ttaken;
241 	int blocks;
242 
243 	(void)time(&tnow);
244 	ttaken = tnow - tstart_volume;
245 	blocks = iswap32(spcl.c_tapea) - tapea_volume;
246 	msg("Volume %d completed at: %s", tapeno, ctime(&tnow));
247 	if (ttaken > 0) {
248 		msg("Volume %d took %d:%02d:%02d\n", tapeno,
249 		    (int) (ttaken / 3600), (int) ((ttaken % 3600) / 60),
250 		    (int) (ttaken % 60));
251 		msg("Volume %d transfer rate: %d KB/s\n", tapeno,
252 		    (int) (blocks / ttaken));
253 		xferrate += blocks / ttaken;
254 	}
255 	return(tnow);
256 }
257 
258 /*
259  * statussig --
260  *	information message upon receipt of SIGINFO
261  *	(derived from optr.c::timeest())
262  */
263 void
264 statussig(int notused)
265 {
266 	time_t	tnow, deltat;
267 	char	msgbuf[128];
268 	int	errno_save;
269 
270 	if (blockswritten < 500)
271 		return;
272 	errno_save = errno;
273 	(void) time((time_t *) &tnow);
274 	if (tnow <= tstart_volume)
275 		return;
276 	deltat = tstart_writing - tnow +
277 	    (1.0 * (tnow - tstart_writing)) / blockswritten * tapesize;
278 	(void)snprintf(msgbuf, sizeof(msgbuf),
279 	    "%3.2f%% done at %ld KB/s, finished in %d:%02d\n",
280 	    (blockswritten * 100.0) / tapesize,
281 	    (long)((iswap32(spcl.c_tapea) - tapea_volume) /
282 	      (tnow - tstart_volume)),
283 	    (int)(deltat / 3600), (int)((deltat % 3600) / 60));
284 	write(STDERR_FILENO, msgbuf, strlen(msgbuf));
285 	errno = errno_save;
286 }
287 
288 static void
289 flushtape(void)
290 {
291 	int i, blks, got;
292 	long lastfirstrec;
293 
294 	int siz = (char *)nextblock - (char *)slp->req;
295 
296 	slp->req[trecno].count = 0;			/* Sentinel */
297 
298 	if (atomic_write(slp->fd, (char *)slp->req, siz) != siz)
299 		quit("error writing command pipe: %s\n", strerror(errno));
300 	slp->sent = 1; /* we sent a request, read the response later */
301 
302 	lastfirstrec = slp->firstrec;
303 
304 	if (++slp >= &slaves[SLAVES])
305 		slp = &slaves[0];
306 
307 	/* Read results back from next slave */
308 	if (slp->sent) {
309 		if (atomic_read(slp->fd, (char *)&got, sizeof got)
310 		    != sizeof got) {
311 			perror("  DUMP: error reading command pipe in master");
312 			dumpabort(0);
313 		}
314 		slp->sent = 0;
315 
316 		/* Check for end of tape */
317 		if (got < writesize) {
318 			msg("End of tape detected\n");
319 
320 			/*
321 			 * Drain the results, don't care what the values were.
322 			 * If we read them here then trewind won't...
323 			 */
324 			for (i = 0; i < SLAVES; i++) {
325 				if (slaves[i].sent) {
326 					if (atomic_read(slaves[i].fd,
327 					    (char *)&got, sizeof got)
328 					    != sizeof got) {
329 						perror("  DUMP: error reading command pipe in master");
330 						dumpabort(0);
331 					}
332 					slaves[i].sent = 0;
333 				}
334 			}
335 
336 			close_rewind();
337 			rollforward();
338 			return;
339 		}
340 	}
341 
342 	blks = 0;
343 	if (iswap32(spcl.c_type) != TS_END) {
344 		for (i = 0; i < iswap32(spcl.c_count); i++)
345 			if (spcl.c_addr[i] != 0)
346 				blks++;
347 	}
348 	slp->count = lastspclrec + blks + 1 - iswap32(spcl.c_tapea);
349 	slp->tapea = iswap32(spcl.c_tapea);
350 	slp->firstrec = lastfirstrec + ntrec;
351 	slp->inode = curino;
352 	nextblock = slp->tblock;
353 	trecno = 0;
354 	asize += tenths;
355 	blockswritten += ntrec;
356 	blocksthisvol += ntrec;
357 	if (!pipeout && !unlimited && (blocksperfile ?
358 	    (blocksthisvol >= blocksperfile) : (asize > tsize))) {
359 		close_rewind();
360 		startnewtape(0);
361 	}
362 	timeest();
363 }
364 
365 void
366 trewind(int eject)
367 {
368 	int f;
369 	int got;
370 
371 	for (f = 0; f < SLAVES; f++) {
372 		/*
373 		 * Drain the results, but unlike EOT we DO (or should) care
374 		 * what the return values were, since if we detect EOT after
375 		 * we think we've written the last blocks to the tape anyway,
376 		 * we have to replay those blocks with rollforward.
377 		 *
378 		 * fixme: punt for now.
379 		 */
380 		if (slaves[f].sent) {
381 			if (atomic_read(slaves[f].fd, (char *)&got, sizeof got)
382 			    != sizeof got) {
383 				perror("  DUMP: error reading command pipe in master");
384 				dumpabort(0);
385 			}
386 			slaves[f].sent = 0;
387 			if (got != writesize) {
388 				msg("EOT detected in last 2 tape records!\n");
389 				msg("Use a longer tape, decrease the size estimate\n");
390 				quit("or use no size estimate at all.\n");
391 			}
392 		}
393 		(void) close(slaves[f].fd);
394 	}
395 	while (wait((int *)NULL) >= 0)	/* wait for any signals from slaves */
396 		/* void */;
397 
398 	if (pipeout)
399 		return;
400 
401 	msg("Closing %s\n", tape);
402 
403 #ifdef RDUMP
404 	if (host) {
405 		rmtclose();
406 		while (rmtopen(tape, 0, 0) < 0)
407 			sleep(10);
408 		if (eflag && eject) {
409 			msg("Ejecting %s\n", tape);
410 			(void) rmtioctl(MTOFFL, 0);
411 		}
412 		rmtclose();
413 		return;
414 	}
415 #endif
416 	(void) close(tapefd);
417 	while ((f = open(tape, 0)) < 0)
418 		sleep (10);
419 	if (eflag && eject) {
420 		struct mtop offl;
421 
422 		msg("Ejecting %s\n", tape);
423 		offl.mt_op = MTOFFL;
424 		offl.mt_count = 0;
425 		(void) ioctl(f, MTIOCTOP, &offl);
426 	}
427 	(void) close(f);
428 }
429 
430 void
431 close_rewind(void)
432 {
433 	int i, f;
434 
435 	trewind(1);
436 	(void)do_stats();
437 	if (nexttape)
438 		return;
439 	if (!nogripe) {
440 		msg("Change Volumes: Mount volume #%d\n", tapeno+1);
441 		broadcast("CHANGE DUMP VOLUMES!\a\a\n");
442 	}
443 	if (lflag) {
444 		for (i = 0; i < lflag / 10; i++) { /* wait lflag seconds */
445 			if (host) {
446 				if (rmtopen(tape, 0, 0) >= 0) {
447 					rmtclose();
448 					return;
449 				}
450 			} else {
451 				if ((f = open(tape, 0)) >= 0) {
452 					close(f);
453 					return;
454 				}
455 			}
456 			sleep (10);
457 		}
458 	}
459 
460 	while (!query("Is the new volume mounted and ready to go?"))
461 		if (query("Do you want to abort?")) {
462 			dumpabort(0);
463 			/*NOTREACHED*/
464 		}
465 }
466 
467 void
468 rollforward(void)
469 {
470 	struct req *p, *q, *prev;
471 	struct slave *tslp;
472 	int i, size, savedtapea, got;
473 	union u_spcl *ntb, *otb;
474 	tslp = &slaves[SLAVES];
475 	ntb = (union u_spcl *)tslp->tblock[1];
476 
477 	/*
478 	 * Each of the N slaves should have requests that need to
479 	 * be replayed on the next tape.  Use the extra slave buffers
480 	 * (slaves[SLAVES]) to construct request lists to be sent to
481 	 * each slave in turn.
482 	 */
483 	for (i = 0; i < SLAVES; i++) {
484 		q = &tslp->req[1];
485 		otb = (union u_spcl *)slp->tblock;
486 
487 		/*
488 		 * For each request in the current slave, copy it to tslp.
489 		 */
490 
491 		prev = NULL;
492 		for (p = slp->req; p->count > 0; p += p->count) {
493 			*q = *p;
494 			if (p->dblk == 0)
495 				*ntb++ = *otb++; /* copy the datablock also */
496 			prev = q;
497 			q += q->count;
498 		}
499 		if (prev == NULL)
500 			quit("rollforward: protocol botch");
501 		if (prev->dblk != 0)
502 			prev->count -= 1;
503 		else
504 			ntb--;
505 		q -= 1;
506 		q->count = 0;
507 		q = &tslp->req[0];
508 		if (i == 0) {
509 			q->dblk = 0;
510 			q->count = 1;
511 			trecno = 0;
512 			nextblock = tslp->tblock;
513 			savedtapea = iswap32(spcl.c_tapea);
514 			spcl.c_tapea = iswap32(slp->tapea);
515 			startnewtape(0);
516 			spcl.c_tapea = iswap32(savedtapea);
517 			lastspclrec = savedtapea - 1;
518 		}
519 		size = (char *)ntb - (char *)q;
520 		if (atomic_write(slp->fd, (char *)q, size) != size) {
521 			perror("  DUMP: error writing command pipe");
522 			dumpabort(0);
523 		}
524 		slp->sent = 1;
525 		if (++slp >= &slaves[SLAVES])
526 			slp = &slaves[0];
527 
528 		q->count = 1;
529 
530 		if (prev->dblk != 0) {
531 			/*
532 			 * If the last one was a disk block, make the
533 			 * first of this one be the last bit of that disk
534 			 * block...
535 			 */
536 			q->dblk = prev->dblk +
537 				prev->count * (TP_BSIZE / DEV_BSIZE);
538 			ntb = (union u_spcl *)tslp->tblock;
539 		} else {
540 			/*
541 			 * It wasn't a disk block.  Copy the data to its
542 			 * new location in the buffer.
543 			 */
544 			q->dblk = 0;
545 			*((union u_spcl *)tslp->tblock) = *ntb;
546 			ntb = (union u_spcl *)tslp->tblock[1];
547 		}
548 	}
549 	slp->req[0] = *q;
550 	nextblock = slp->tblock;
551 	if (q->dblk == 0)
552 		nextblock++;
553 	trecno = 1;
554 
555 	/*
556 	 * Clear the first slaves' response.  One hopes that it
557 	 * worked ok, otherwise the tape is much too short!
558 	 */
559 	if (slp->sent) {
560 		if (atomic_read(slp->fd, (char *)&got, sizeof got)
561 		    != sizeof got) {
562 			perror("  DUMP: error reading command pipe in master");
563 			dumpabort(0);
564 		}
565 		slp->sent = 0;
566 
567 		if (got != writesize) {
568 			quit("EOT detected at start of the tape!\n");
569 		}
570 	}
571 }
572 
573 /*
574  * We implement taking and restoring checkpoints on the tape level.
575  * When each tape is opened, a new process is created by forking; this
576  * saves all of the necessary context in the parent.  The child
577  * continues the dump; the parent waits around, saving the context.
578  * If the child returns X_REWRITE, then it had problems writing that tape;
579  * this causes the parent to fork again, duplicating the context, and
580  * everything continues as if nothing had happened.
581  */
582 void
583 startnewtape(int top)
584 {
585 	int	parentpid;
586 	int	childpid;
587 	int	status;
588 	int	waitforpid;
589 	char	*p;
590 	sig_t	interrupt_save;
591 
592 	interrupt_save = signal(SIGINT, SIG_IGN);
593 	parentpid = getpid();
594 	tapea_volume = iswap32(spcl.c_tapea);
595 	(void)time(&tstart_volume);
596 
597 restore_check_point:
598 	(void)signal(SIGINT, interrupt_save);
599 	/*
600 	 *	All signals are inherited...
601 	 */
602 	childpid = fork();
603 	if (childpid < 0) {
604 		msg("Context save fork fails in parent %d\n", parentpid);
605 		Exit(X_ABORT);
606 	}
607 	if (childpid != 0) {
608 		/*
609 		 *	PARENT:
610 		 *	save the context by waiting
611 		 *	until the child doing all of the work returns.
612 		 *	don't catch the interrupt
613 		 */
614 		signal(SIGINT, SIG_IGN);
615 		signal(SIGINFO, SIG_IGN);	/* only want child's stats */
616 #ifdef TDEBUG
617 		msg("Tape: %d; parent process: %d child process %d\n",
618 			tapeno+1, parentpid, childpid);
619 #endif /* TDEBUG */
620 		while ((waitforpid = wait(&status)) != childpid)
621 			msg("Parent %d waiting for child %d has another child %d return\n",
622 				parentpid, childpid, waitforpid);
623 		if (status & 0xFF) {
624 			msg("Child %d returns LOB status %o\n",
625 				childpid, status&0xFF);
626 		}
627 		status = (status >> 8) & 0xFF;
628 #ifdef TDEBUG
629 		switch(status) {
630 			case X_FINOK:
631 				msg("Child %d finishes X_FINOK\n", childpid);
632 				break;
633 			case X_ABORT:
634 				msg("Child %d finishes X_ABORT\n", childpid);
635 				break;
636 			case X_REWRITE:
637 				msg("Child %d finishes X_REWRITE\n", childpid);
638 				break;
639 			default:
640 				msg("Child %d finishes unknown %d\n",
641 					childpid, status);
642 				break;
643 		}
644 #endif /* TDEBUG */
645 		switch(status) {
646 			case X_FINOK:
647 				Exit(X_FINOK);
648 			case X_ABORT:
649 				Exit(X_ABORT);
650 			case X_REWRITE:
651 				goto restore_check_point;
652 			default:
653 				msg("Bad return code from dump: %d\n", status);
654 				Exit(X_ABORT);
655 		}
656 		/*NOTREACHED*/
657 	} else {	/* we are the child; just continue */
658 		signal(SIGINFO, statussig);	/* now want child's stats */
659 #ifdef TDEBUG
660 		sleep(4);	/* allow time for parent's message to get out */
661 		msg("Child on Tape %d has parent %d, my pid = %d\n",
662 			tapeno+1, parentpid, getpid());
663 #endif /* TDEBUG */
664 		/*
665 		 * If we have a name like "/dev/rst0,/dev/rst1",
666 		 * use the name before the comma first, and save
667 		 * the remaining names for subsequent volumes.
668 		 */
669 		tapeno++;			/* current tape sequence */
670 		if (nexttape || strchr(tape, ',')) {
671 			if (nexttape && *nexttape)
672 				tape = nexttape;
673 			if ((p = strchr(tape, ',')) != NULL) {
674 				*p = '\0';
675 				nexttape = p + 1;
676 			} else
677 				nexttape = NULL;
678 			msg("Dumping volume %d on %s\n", tapeno, tape);
679 		}
680 #ifdef RDUMP
681 		while ((tapefd = (host ? rmtopen(tape, 2, 1) :
682 			pipeout ? 1 : open(tape, O_WRONLY|O_CREAT, 0666))) < 0)
683 #else
684 		while ((tapefd = (pipeout ? 1 :
685 				  open(tape, O_WRONLY|O_CREAT, 0666))) < 0)
686 #endif
687 		    {
688 			msg("Cannot open output \"%s\".\n", tape);
689 			if (!query("Do you want to retry the open?"))
690 				dumpabort(0);
691 		}
692 
693 		enslave();  /* Share open tape file descriptor with slaves */
694 
695 		asize = 0;
696 		blocksthisvol = 0;
697 		if (top)
698 			newtape++;		/* new tape signal */
699 		spcl.c_count = iswap32(slp->count);
700 		/*
701 		 * measure firstrec in TP_BSIZE units since restore doesn't
702 		 * know the correct ntrec value...
703 		 */
704 		spcl.c_firstrec = iswap32(slp->firstrec);
705 		spcl.c_volume = iswap32(iswap32(spcl.c_volume) + 1);
706 		spcl.c_type = iswap32(TS_TAPE);
707 		spcl.c_flags = iswap32(iswap32(spcl.c_flags) | DR_NEWHEADER);
708 		writeheader((ino_t)slp->inode);
709 		spcl.c_flags  = iswap32(iswap32(spcl.c_flags) & ~ DR_NEWHEADER);
710 		msg("Volume %d started at: %s", tapeno, ctime(&tstart_volume));
711 		if (tapeno > 1)
712 			msg("Volume %d begins with blocks from inode %d\n",
713 				tapeno, slp->inode);
714 	}
715 }
716 
717 void
718 dumpabort(int signo)
719 {
720 
721 	if (master != 0 && master != getpid())
722 		/* Signals master to call dumpabort */
723 		(void) kill(master, SIGTERM);
724 	else {
725 		killall();
726 		msg("The ENTIRE dump is aborted.\n");
727 	}
728 #ifdef RDUMP
729 	rmtclose();
730 #endif
731 	Exit(X_ABORT);
732 }
733 
734 void
735 Exit(int status)
736 {
737 
738 #ifdef TDEBUG
739 	msg("pid = %d exits with status %d\n", getpid(), status);
740 #endif /* TDEBUG */
741 	exit(status);
742 }
743 
744 /*
745  * proceed - handler for SIGUSR2, used to synchronize IO between the slaves.
746  */
747 static void
748 proceed(int signo)
749 {
750 
751 	if (ready)
752 		longjmp(jmpbuf, 1);
753 	caught++;
754 }
755 
756 void
757 enslave(void)
758 {
759 	int cmd[2];
760 	int i, j;
761 
762 	master = getpid();
763 
764 	signal(SIGTERM, dumpabort);  /* Slave sends SIGTERM on dumpabort() */
765 	signal(SIGPIPE, sigpipe);
766 	signal(SIGUSR1, tperror);    /* Slave sends SIGUSR1 on tape errors */
767 	signal(SIGUSR2, proceed);    /* Slave sends SIGUSR2 to next slave */
768 
769 	for (i = 0; i < SLAVES; i++) {
770 		if (i == slp - &slaves[0]) {
771 			caught = 1;
772 		} else {
773 			caught = 0;
774 		}
775 
776 		if (socketpair(AF_LOCAL, SOCK_STREAM, 0, cmd) < 0 ||
777 		    (slaves[i].pid = fork()) < 0)
778 			quit("too many slaves, %d (recompile smaller): %s\n",
779 			    i, strerror(errno));
780 
781 		slaves[i].fd = cmd[1];
782 		slaves[i].sent = 0;
783 		if (slaves[i].pid == 0) { 	    /* Slave starts up here */
784 			for (j = 0; j <= i; j++)
785 				(void) close(slaves[j].fd);
786 			signal(SIGINT, SIG_IGN);    /* Master handles this */
787 			signal(SIGINFO, SIG_IGN);
788 			doslave(cmd[0], i);
789 			Exit(X_FINOK);
790 		}
791 	}
792 
793 	for (i = 0; i < SLAVES; i++)
794 		(void) atomic_write(slaves[i].fd,
795 				(char *) &slaves[(i + 1) % SLAVES].pid,
796 				sizeof slaves[0].pid);
797 
798 	master = 0;
799 }
800 
801 void
802 killall(void)
803 {
804 	int i;
805 
806 	for (i = 0; i < SLAVES; i++)
807 		if (slaves[i].pid > 0) {
808 			(void) kill(slaves[i].pid, SIGKILL);
809 			slaves[i].sent = 0;
810 		}
811 }
812 
813 /*
814  * Synchronization - each process has a lockfile, and shares file
815  * descriptors to the following process's lockfile.  When our write
816  * completes, we release our lock on the following process's lock-
817  * file, allowing the following process to lock it and proceed. We
818  * get the lock back for the next cycle by swapping descriptors.
819  */
820 static void
821 doslave(int cmd, int slave_number)
822 {
823 	int nread, nextslave, size, wrote, eot_count, werror;
824 	sigset_t sigset;
825 
826 	/*
827 	 * Need our own seek pointer.
828 	 */
829 	(void) close(diskfd);
830 	if ((diskfd = open(disk, O_RDONLY)) < 0)
831 		quit("slave couldn't reopen disk: %s\n", strerror(errno));
832 
833 	/*
834 	 * Need the pid of the next slave in the loop...
835 	 */
836 	if ((nread = atomic_read(cmd, (char *)&nextslave, sizeof nextslave))
837 	    != sizeof nextslave) {
838 		quit("master/slave protocol botched - didn't get pid of next slave.\n");
839 	}
840 
841 	/*
842 	 * Get list of blocks to dump, read the blocks into tape buffer
843 	 */
844 	while ((nread = atomic_read(cmd, (char *)slp->req, reqsiz)) == reqsiz) {
845 		struct req *p = slp->req;
846 
847 		for (trecno = 0; trecno < ntrec;
848 		     trecno += p->count, p += p->count) {
849 			if (p->dblk) {
850 				bread(p->dblk, slp->tblock[trecno],
851 					p->count * TP_BSIZE);
852 			} else {
853 				if (p->count != 1 || atomic_read(cmd,
854 				    (char *)slp->tblock[trecno],
855 				    TP_BSIZE) != TP_BSIZE)
856 				       quit("master/slave protocol botched.\n");
857 			}
858 		}
859 		if (setjmp(jmpbuf) == 0) {
860 			ready = 1;
861 			if (!caught)
862 				(void) pause();
863 		}
864 		ready = 0;
865 		caught = 0;
866 
867 		/* Try to write the data... */
868 		eot_count = 0;
869 		size = 0;
870 		werror = 0;
871 
872 		while (eot_count < 10 && size < writesize) {
873 #ifdef RDUMP
874 			if (host)
875 				wrote = rmtwrite(slp->tblock[0]+size,
876 				    writesize-size);
877 			else
878 #endif
879 				wrote = write(tapefd, slp->tblock[0]+size,
880 				    writesize-size);
881 			werror = errno;
882 #ifdef WRITEDEBUG
883 			fprintf(stderr, "slave %d wrote %d werror %d\n",
884 			    slave_number, wrote, werror);
885 #endif
886 			if (wrote < 0)
887 				break;
888 			if (wrote == 0)
889 				eot_count++;
890 			size += wrote;
891 		}
892 
893 #ifdef WRITEDEBUG
894 		if (size != writesize)
895 			fprintf(stderr,
896 		    "slave %d only wrote %d out of %d bytes and gave up.\n",
897 			    slave_number, size, writesize);
898 #endif
899 
900 		/*
901 		 * Handle ENOSPC as an EOT condition.
902 		 */
903 		if (wrote < 0 && werror == ENOSPC) {
904 			wrote = 0;
905 			eot_count++;
906 		}
907 
908 		if (eot_count > 0)
909 			size = 0;
910 
911 		if (wrote < 0) {
912 			(void) kill(master, SIGUSR1);
913 			sigemptyset(&sigset);
914 			for (;;)
915 				sigsuspend(&sigset);
916 		} else {
917 			/*
918 			 * pass size of write back to master
919 			 * (for EOT handling)
920 			 */
921 			(void) atomic_write(cmd, (char *)&size, sizeof size);
922 		}
923 
924 		/*
925 		 * If partial write, don't want next slave to go.
926 		 * Also jolts him awake.
927 		 */
928 		(void) kill(nextslave, SIGUSR2);
929 	}
930 	printcachestats();
931 	if (nread != 0)
932 		quit("error reading command pipe: %s\n", strerror(errno));
933 }
934 
935 /*
936  * Since a read from a pipe may not return all we asked for,
937  * loop until the count is satisfied (or error).
938  */
939 static ssize_t
940 atomic_read(int fd, char *buf, int count)
941 {
942 	ssize_t got, need = count;
943 
944 	while ((got = read(fd, buf, need)) > 0 && (need -= got) > 0)
945 		buf += got;
946 	return (got < 0 ? got : count - need);
947 }
948 
949 /*
950  * Since a write may not write all we ask if we get a signal,
951  * loop until the count is satisfied (or error).
952  */
953 static ssize_t
954 atomic_write(int fd, char *buf, int count)
955 {
956 	ssize_t got, need = count;
957 
958 	while ((got = write(fd, buf, need)) > 0 && (need -= got) > 0)
959 		buf += got;
960 	return (got < 0 ? got : count - need);
961 }
962