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