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