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