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