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