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