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