]> git.wh0rd.org Git - dump.git/blob - dump/tape.c
545c78fd0c5778dbab784d5b8a7dfc6e89f95c86
[dump.git] / dump / tape.c
1 /*
2  *      Ported to Linux's Second Extended File System as part of the
3  *      dump and restore backup suit
4  *      Remy Card <card@Linux.EU.Org>, 1994-1997
5  *      Stelian Pop <pop@noos.fr>, 1999-2000
6  *      Stelian Pop <pop@noos.fr> - AlcĂ´ve <www.alcove.fr>, 2000
7  */
8
9 /*-
10  * Copyright (c) 1980, 1991, 1993
11  *      The Regents of the University of California.  All rights reserved.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *      This product includes software developed by the University of
24  *      California, Berkeley and its contributors.
25  * 4. Neither the name of the University nor the names of its contributors
26  *    may be used to endorse or promote products derived from this software
27  *    without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39  * SUCH DAMAGE.
40  */
41
42 #ifndef lint
43 static const char rcsid[] =
44         "$Id: tape.c,v 1.25 2000/12/04 15:43:16 stelian Exp $";
45 #endif /* not lint */
46
47 #ifdef __linux__
48 #include <sys/types.h>
49 #include <linux/types.h>
50 #endif
51 #include <sys/param.h>
52 #include <sys/socket.h>
53 #include <sys/time.h>
54 #include <sys/wait.h>
55 #ifdef __linux__
56 #include <linux/ext2_fs.h>
57 #include <bsdcompat.h>
58 #else   /* __linux__ */
59 #ifdef sunos
60 #include <sys/vnode.h>
61
62 #include <ufs/fs.h>
63 #include <ufs/inode.h>
64 #else
65 #include <ufs/ufs/dinode.h>
66 #include <ufs/ffs/fs.h>
67 #endif
68 #endif  /* __linux__ */
69
70 #include <protocols/dumprestore.h>
71
72 #include <errno.h>
73 #include <fcntl.h>
74 #include <setjmp.h>
75 #include <signal.h>
76 #include <stdio.h>
77 #include <compaterr.h>
78 #ifdef __STDC__
79 #include <stdlib.h>
80 #include <string.h>
81 #include <unistd.h>
82 #else
83 int     write(), read();
84 #endif
85
86 #ifdef __linux__
87 #include <ext2fs/ext2fs.h>
88 #endif
89
90 #include "dump.h"
91
92 int     writesize;              /* size of malloc()ed buffer for tape */
93 long    lastspclrec = -1;       /* tape block number of last written header */
94 int     trecno = 0;             /* next record to write in current block */
95 extern  long blocksperfile;     /* number of blocks per output file */
96 long    blocksthisvol;          /* number of blocks on current output file */
97 extern  int ntrec;              /* blocking factor on tape */
98 extern  int cartridge;
99 extern  char *host;
100 char    *nexttape;
101 extern  pid_t rshpid;
102 int     eot_code = 1;
103
104 static  ssize_t atomic_read __P((int, void *, size_t));
105 static  ssize_t atomic_write __P((int, const void *, size_t));
106 static  void doslave __P((int, int));
107 static  void enslave __P((void));
108 static  void flushtape __P((void));
109 static  void killall __P((void));
110 static  void rollforward __P((void));
111 static  int system_command __P((const char *, const char *, int));
112
113 /*
114  * Concurrent dump mods (Caltech) - disk block reading and tape writing
115  * are exported to several slave processes.  While one slave writes the
116  * tape, the others read disk blocks; they pass control of the tape in
117  * a ring via signals. The parent process traverses the filesystem and
118  * sends writeheader()'s and lists of daddr's to the slaves via pipes.
119  * The following structure defines the instruction packets sent to slaves.
120  */
121 struct req {
122         daddr_t dblk;
123         int count;
124 };
125 int reqsiz;
126
127 #define SLAVES 3                /* 1 slave writing, 1 reading, 1 for slack */
128 struct slave {
129         int tapea;              /* header number at start of this chunk */
130         int count;              /* count to next header (used for TS_TAPE */
131                                 /* after EOT) */
132         int inode;              /* inode that we are currently dealing with */
133         int fd;                 /* FD for this slave */
134         int pid;                /* PID for this slave */
135         int sent;               /* 1 == we've sent this slave requests */
136         int firstrec;           /* record number of this block */
137         char (*tblock)[TP_BSIZE]; /* buffer for data blocks */
138         struct req *req;        /* buffer for requests */
139 } slaves[SLAVES+1];
140 struct slave *slp;
141
142 char    (*nextblock)[TP_BSIZE];
143
144 static time_t tstart_volume;    /* time of volume start */ 
145 static int tapea_volume;        /* value of spcl.c_tapea at volume start */
146
147 int master;             /* pid of master, for sending error signals */
148 int tenths;             /* length of tape used per block written */
149 static int caught;      /* have we caught the signal to proceed? */
150 static int ready;       /* have we reached the lock point without having */
151                         /* received the SIGUSR2 signal from the prev slave? */
152 static sigjmp_buf jmpbuf;       /* where to jump to if we are ready when the */
153                         /* SIGUSR2 arrives from the previous slave */
154
155 int
156 alloctape(void)
157 {
158         int pgoff = getpagesize() - 1;
159         char *buf;
160         int i;
161
162         writesize = ntrec * TP_BSIZE;
163         reqsiz = (ntrec + 1) * sizeof(struct req);
164         /*
165          * CDC 92181's and 92185's make 0.8" gaps in 1600-bpi start/stop mode
166          * (see DEC TU80 User's Guide).  The shorter gaps of 6250-bpi require
167          * repositioning after stopping, i.e, streaming mode, where the gap is
168          * variable, 0.30" to 0.45".  The gap is maximal when the tape stops.
169          */
170         if (blocksperfile == 0 && !unlimited)
171                 tenths = writesize / density +
172                     (cartridge ? 16 : density == 625 ? 5 : 8);
173         /*
174          * Allocate tape buffer contiguous with the array of instruction
175          * packets, so flushtape() can write them together with one write().
176          * Align tape buffer on page boundary to speed up tape write().
177          */
178         for (i = 0; i <= SLAVES; i++) {
179                 buf = (char *)
180                     malloc((unsigned)(reqsiz + writesize + pgoff + TP_BSIZE));
181                 if (buf == NULL)
182                         return(0);
183                 slaves[i].tblock = (char (*)[TP_BSIZE])
184 #ifdef  __linux__
185                     (((long)&buf[reqsiz] + pgoff) &~ pgoff);
186 #else
187                     (((long)&buf[ntrec + 1] + pgoff) &~ pgoff);
188 #endif
189                 slaves[i].req = (struct req *)slaves[i].tblock - ntrec - 1;
190         }
191         slp = &slaves[0];
192         slp->count = 1;
193         slp->tapea = 0;
194         slp->firstrec = 0;
195         nextblock = slp->tblock;
196         return(1);
197 }
198
199 void
200 writerec(const void *dp, int isspcl)
201 {
202
203         slp->req[trecno].dblk = (daddr_t)0;
204         slp->req[trecno].count = 1;
205         /* XXX post increment triggers an egcs-1.1.2-12 bug on alpha/sparc */
206         *(union u_spcl *)(*(nextblock)) = *(union u_spcl *)dp;
207         nextblock++;
208         if (isspcl)
209                 lastspclrec = spcl.c_tapea;
210         trecno++;
211         spcl.c_tapea++;
212         if (trecno >= ntrec)
213                 flushtape();
214 }
215
216 void
217 dumpblock(daddr_t blkno, int size)
218 {
219         int avail, tpblks, dblkno;
220
221         dblkno = fsbtodb(sblock, blkno);
222         tpblks = size >> tp_bshift;
223         while ((avail = MIN(tpblks, ntrec - trecno)) > 0) {
224                 slp->req[trecno].dblk = dblkno;
225                 slp->req[trecno].count = avail;
226                 trecno += avail;
227                 spcl.c_tapea += avail;
228                 if (trecno >= ntrec)
229                         flushtape();
230                 dblkno += avail << (tp_bshift - dev_bshift);
231                 tpblks -= avail;
232         }
233 }
234
235 int     nogripe = 0;
236
237 static void
238 tperror(int signo)
239 {
240
241         if (pipeout) {
242                 msg("write error on %s\n", tape);
243                 quit("Cannot recover\n");
244                 /* NOTREACHED */
245         }
246         msg("write error %d blocks into volume %d\n", blocksthisvol, tapeno);
247         broadcast("DUMP WRITE ERROR!\n");
248         if (!query("Do you want to restart?"))
249                 dumpabort(0);
250         msg("Closing this volume.  Prepare to restart with new media;\n");
251         msg("this dump volume will be rewritten.\n");
252         killall();
253         nogripe = 1;
254         close_rewind();
255         Exit(X_REWRITE);
256 }
257
258 static void
259 sigpipe(int signo)
260 {
261
262         quit("Broken pipe\n");
263 }
264
265 /*
266  * do_stats --
267  *     Update xferrate stats
268  */
269 time_t
270 do_stats(void)
271 {
272         time_t tnow, ttaken;
273         int blocks;
274
275 #ifdef __linux__
276         (void)time4(&tnow);
277 #else
278         (void)time(&tnow);
279 #endif
280         ttaken = tnow - tstart_volume;
281         blocks = spcl.c_tapea - tapea_volume;
282         msg("Volume %d completed at: %s", tapeno, 
283 #ifdef __linux__
284                                           ctime4(&tnow));
285 #else
286                                           ctime(&tnow));
287 #endif
288         if (ttaken > 0) {
289                 msg("Volume %d took %d:%02d:%02d\n", tapeno,
290                         ttaken / 3600, (ttaken % 3600) / 60, ttaken % 60);
291                 msg("Volume %d transfer rate: %ld KB/s\n", tapeno,
292                         blocks / ttaken);
293                 xferrate += blocks / ttaken;
294         }
295         return(tnow);
296 }
297
298 #if defined(SIGINFO)
299 /*
300  * statussig --
301  *     information message upon receipt of SIGINFO
302  *     (derived from optr.c::timeest())
303  */
304 void
305 statussig(int notused)
306 {
307         time_t  tnow, deltat;
308         char    msgbuf[128];
309         int save_errno = errno;
310
311         if (blockswritten < 500)
312                 return;
313 #ifdef __linux__
314         (void) time4(&tnow);
315 #else
316         (void) time((time_t *) &tnow);
317 #endif
318         if (blockswritten > tapesize)
319                 tapesize = blockswritten;
320         deltat = tstart_writing - tnow + (1.0 * (tnow - tstart_writing))
321                 / blockswritten * tapesize;
322         (void)snprintf(msgbuf, sizeof(msgbuf),
323                 "%3.2f%% done at %ld KB/s, finished in %d:%02d\n",
324                 (blockswritten * 100.0) / tapesize,
325                 (spcl.c_tapea - tapea_volume) / (tnow - tstart_volume),
326                 (int)(deltat / 3600), (int)((deltat % 3600) / 60));
327         write(STDERR_FILENO, msgbuf, strlen(msgbuf));
328         errno = save_errno;
329 }
330 #endif
331
332 static void
333 flushtape(void)
334 {
335         int i, blks, got;
336         long lastfirstrec;
337
338         int siz = (char *)nextblock - (char *)slp->req;
339
340         slp->req[trecno].count = 0;                     /* Sentinel */
341
342         if (atomic_write( slp->fd, (char *)slp->req, siz) != siz)
343                 quit("error writing command pipe: %s\n", strerror(errno));
344         slp->sent = 1; /* we sent a request, read the response later */
345
346         lastfirstrec = slp->firstrec;
347
348         if (++slp >= &slaves[SLAVES])
349                 slp = &slaves[0];
350
351         /* Read results back from next slave */
352         if (slp->sent) {
353                 if (atomic_read( slp->fd, (char *)&got, sizeof got)
354                     != sizeof got) {
355                         perror("  DUMP: error reading command pipe in master");
356                         dumpabort(0);
357                 }
358                 slp->sent = 0;
359
360                 /* Check for end of tape */
361                 if (got < writesize) {
362                         msg("End of tape detected\n");
363
364                         /*
365                          * Drain the results, don't care what the values were.
366                          * If we read them here then trewind won't...
367                          */
368                         for (i = 0; i < SLAVES; i++) {
369                                 if (slaves[i].sent) {
370                                         if (atomic_read( slaves[i].fd,
371                                             (char *)&got, sizeof got)
372                                             != sizeof got) {
373                                                 perror("  DUMP: error reading command pipe in master");
374                                                 dumpabort(0);
375                                         }
376                                         slaves[i].sent = 0;
377                                 }
378                         }
379
380                         close_rewind();
381                         rollforward();
382                         return;
383                 }
384         }
385
386         blks = 0;
387         if (spcl.c_type != TS_END) {
388                 for (i = 0; i < spcl.c_count; i++)
389                         if (spcl.c_addr[i] != 0)
390                                 blks++;
391         }
392         slp->count = lastspclrec + blks + 1 - spcl.c_tapea;
393         slp->tapea = spcl.c_tapea;
394         slp->firstrec = lastfirstrec + ntrec;
395         slp->inode = curino;
396         nextblock = slp->tblock;
397         trecno = 0;
398         asize += tenths;
399         blockswritten += ntrec;
400         blocksthisvol += ntrec;
401         if (!pipeout && !unlimited && (blocksperfile ?
402             (blocksthisvol >= blocksperfile) : (asize > tsize))) {
403                 close_rewind();
404                 startnewtape(0);
405         }
406         timeest();
407 }
408
409 /*
410  * Executes the command in a shell.
411  * Returns -1 if an error occured, the exit status of
412  * the command on success.
413  */
414 int system_command(const char *command, const char *device, int volnum) {
415         int pid, status;
416         char commandstr[4096];
417
418         pid = fork();
419         if (pid == -1) {
420                 perror("  DUMP: unable to fork");
421                 return -1;
422         }
423         if (pid == 0) {
424                 setuid(getuid());
425                 setgid(getgid());
426 #if OLD_STYLE_FSCRIPT
427                 snprintf(commandstr, sizeof(commandstr), "%s", command);
428 #else
429                 snprintf(commandstr, sizeof(commandstr), "%s %s %d", command, device, volnum);
430 #endif
431                 commandstr[sizeof(commandstr) - 1] = '\0';
432                 execl("/bin/sh", "sh", "-c", commandstr, NULL);
433                 perror("  DUMP: unable to execute shell");
434                 exit(-1);
435         }
436         do {
437                 if (waitpid(pid, &status, 0) == -1) {
438                         if (errno != EINTR) {
439                                 perror("  DUMP: waitpid error");
440                                 return -1;
441                         }
442                 } else {
443                         if (WIFEXITED(status))
444                                 return WEXITSTATUS(status);
445                         else
446                                 return -1;
447                 }
448         } while(1);
449 }
450
451 time_t
452 trewind(void)
453 {
454         int f;
455         int got;
456
457         for (f = 0; f < SLAVES; f++) {
458                 /*
459                  * Drain the results, but unlike EOT we DO (or should) care
460                  * what the return values were, since if we detect EOT after
461                  * we think we've written the last blocks to the tape anyway,
462                  * we have to replay those blocks with rollforward.
463                  *
464                  * fixme: punt for now.
465                  */
466                 if (slaves[f].sent) {
467                         if (atomic_read( slaves[f].fd, (char *)&got, sizeof got)
468                             != sizeof got) {
469                                 perror("  DUMP: error reading command pipe in master");
470                                 dumpabort(0);
471                         }
472                         slaves[f].sent = 0;
473                         if (got != writesize) {
474                                 msg("EOT detected in last 2 tape records!\n");
475                                 msg("Use a longer tape, decrease the size estimate\n");
476                                 quit("or use no size estimate at all.\n");
477                         }
478                 }
479                 (void) close(slaves[f].fd);
480         }
481         while (wait((int *)NULL) >= 0)  /* wait for any signals from slaves */
482                 /* void */;
483
484         if (!pipeout) {
485
486                 msg("Closing %s\n", tape);
487
488 #ifdef RDUMP
489                 if (host) {
490                         rmtclose();
491                         while (rmtopen(tape, 0) < 0)
492                                 sleep(10);
493                         rmtclose();
494                 }
495                 else 
496 #endif
497                 {
498                         (void) close(tapefd);
499                         while ((f = open(tape, 0)) < 0)
500                                 sleep (10);
501                         (void) close(f);
502                 }
503                 eot_code = 1;
504                 if (eot_script && spcl.c_type != TS_END) {
505                         msg("Launching %s\n", eot_script);
506                         eot_code = system_command(eot_script, tape, tapeno);
507                 }
508                 if (eot_code != 0 && eot_code != 1) {
509                         msg("Dump aborted by the end of tape script\n");
510                         dumpabort(0);
511                 }
512         }
513         return do_stats();
514 }
515
516                 
517 void
518 close_rewind(void)
519 {
520         (void)trewind();
521         if (nexttape || Mflag || (eot_code == 0) )
522                 return;
523         if (!nogripe) {
524                 msg("Change Volumes: Mount volume #%d\n", tapeno+1);
525                 broadcast("CHANGE DUMP VOLUMES!\7\7\n");
526         }
527         while (!query("Is the new volume mounted and ready to go?"))
528                 if (query("Do you want to abort?")) {
529                         dumpabort(0);
530                         /*NOTREACHED*/
531                 }
532 }
533
534 void
535 rollforward(void)
536 {
537         register struct req *p, *q, *prev;
538         register struct slave *tslp;
539         int i, size, savedtapea, got;
540         union u_spcl *ntb, *otb;
541 #ifdef __linux__
542         int blks;
543         long lastfirstrec;
544 #endif
545         tslp = &slaves[SLAVES];
546         ntb = (union u_spcl *)tslp->tblock[1];
547
548         /*
549          * Each of the N slaves should have requests that need to
550          * be replayed on the next tape.  Use the extra slave buffers
551          * (slaves[SLAVES]) to construct request lists to be sent to
552          * each slave in turn.
553          */
554         for (i = 0; i < SLAVES; i++) {
555                 q = &tslp->req[1];
556                 otb = (union u_spcl *)slp->tblock;
557
558                 /*
559                  * For each request in the current slave, copy it to tslp.
560                  */
561
562                 prev = NULL;
563                 for (p = slp->req; p->count > 0; p += p->count) {
564                         *q = *p;
565                         if (p->dblk == 0)
566                                 *ntb++ = *otb++; /* copy the datablock also */
567                         prev = q;
568                         q += q->count;
569                 }
570                 if (prev == NULL)
571                         quit("rollforward: protocol botch");
572                 if (prev->dblk != 0)
573                         prev->count -= 1;
574                 else
575                         ntb--;
576                 q -= 1;
577                 q->count = 0;
578                 q = &tslp->req[0];
579                 if (i == 0) {
580                         q->dblk = 0;
581                         q->count = 1;
582                         trecno = 0;
583                         nextblock = tslp->tblock;
584                         savedtapea = spcl.c_tapea;
585                         spcl.c_tapea = slp->tapea;
586                         startnewtape(0);
587                         spcl.c_tapea = savedtapea;
588                         lastspclrec = savedtapea - 1;
589                 }
590                 size = (char *)ntb - (char *)q;
591                 if (atomic_write( slp->fd, (char *)q, size) != size) {
592                         perror("  DUMP: error writing command pipe");
593                         dumpabort(0);
594                 }
595                 slp->sent = 1;
596 #ifdef __linux__
597                 lastfirstrec = slp->firstrec;
598 #endif
599                 if (++slp >= &slaves[SLAVES])
600                         slp = &slaves[0];
601
602                 q->count = 1;
603
604                 if (prev->dblk != 0) {
605                         /*
606                          * If the last one was a disk block, make the
607                          * first of this one be the last bit of that disk
608                          * block...
609                          */
610                         q->dblk = prev->dblk +
611                                 prev->count * (TP_BSIZE / DEV_BSIZE);
612                         ntb = (union u_spcl *)tslp->tblock;
613                 } else {
614                         /*
615                          * It wasn't a disk block.  Copy the data to its
616                          * new location in the buffer.
617                          */
618                         q->dblk = 0;
619                         *((union u_spcl *)tslp->tblock) = *ntb;
620                         ntb = (union u_spcl *)tslp->tblock[1];
621                 }
622         }
623         slp->req[0] = *q;
624         nextblock = slp->tblock;
625         if (q->dblk == 0) {
626 #ifdef __linux__
627         /* XXX post increment triggers an egcs-1.1.2-12 bug on alpha/sparc */
628                 *(union u_spcl *)(*nextblock) = *(union u_spcl *)tslp->tblock;
629 #endif
630                 nextblock++;
631         }
632         trecno = 1;
633
634         /*
635          * Clear the first slaves' response.  One hopes that it
636          * worked ok, otherwise the tape is much too short!
637          */
638         if (slp->sent) {
639                 if (atomic_read( slp->fd, (char *)&got, sizeof got)
640                     != sizeof got) {
641                         perror("  DUMP: error reading command pipe in master");
642                         dumpabort(0);
643                 }
644                 slp->sent = 0;
645
646                 if (got != writesize) {
647                         quit("EOT detected at start of the tape!\n");
648                 }
649         }
650
651 #ifdef __linux__
652         blks = 0;
653         if (spcl.c_type != TS_END) {
654                 for (i = 0; i < spcl.c_count; i++)
655                         if (spcl.c_addr[i] != 0)
656                                 blks++;
657         }
658
659         slp->firstrec = lastfirstrec + ntrec;
660         slp->count = lastspclrec + blks + 1 - spcl.c_tapea;
661         slp->inode = curino;
662         asize += tenths;
663         blockswritten += ntrec;
664         blocksthisvol += ntrec;
665 #endif
666 }
667
668 /*
669  * We implement taking and restoring checkpoints on the tape level.
670  * When each tape is opened, a new process is created by forking; this
671  * saves all of the necessary context in the parent.  The child
672  * continues the dump; the parent waits around, saving the context.
673  * If the child returns X_REWRITE, then it had problems writing that tape;
674  * this causes the parent to fork again, duplicating the context, and
675  * everything continues as if nothing had happened.
676  */
677 void
678 startnewtape(int top)
679 {
680         int     parentpid;
681         int     childpid;
682         int     status;
683         int     waitpid;
684         char    *p;
685
686 #ifdef  __linux__
687         sigset_t sigs;
688         sigemptyset(&sigs);
689         sigaddset(&sigs, SIGINT);
690         sigprocmask(SIG_BLOCK, &sigs, NULL);
691 #else   /* __linux__ */
692 #ifdef sunos
693         void    (*interrupt_save)();
694 #else
695         sig_t   interrupt_save;
696 #endif
697         interrupt_save = signal(SIGINT, SIG_IGN);
698 #endif  /* __linux__ */
699
700         parentpid = getpid();
701         tapea_volume = spcl.c_tapea;
702 #ifdef __linux__
703         (void)time4(&tstart_volume);
704 #else
705         (void)time((&tstart_volume);
706 #endif
707
708 restore_check_point:
709 #ifdef  __linux__
710         sigprocmask(SIG_UNBLOCK, &sigs, NULL);
711 #else
712         (void)signal(SIGINT, interrupt_save);
713 #endif
714         /*
715          *      All signals are inherited...
716          */
717         childpid = fork();
718         if (childpid < 0) {
719                 msg("Context save fork fails in parent %d\n", parentpid);
720                 Exit(X_ABORT);
721         }
722         if (childpid != 0) {
723                 /*
724                  *      PARENT:
725                  *      save the context by waiting
726                  *      until the child doing all of the work returns.
727                  *      don't catch the interrupt
728                  */
729 #ifdef  __linux__
730                 sigprocmask(SIG_BLOCK, &sigs, NULL);
731 #else
732                 signal(SIGINT, SIG_IGN);
733 #endif
734 #ifdef TDEBUG
735                 msg("Tape: %d; parent process: %d child process %d\n",
736                         tapeno+1, parentpid, childpid);
737 #endif /* TDEBUG */
738                 while ((waitpid = wait(&status)) != childpid)
739                         if (waitpid != rshpid)
740                                 msg("Parent %d waiting for child %d has another child %d return\n",
741                                 parentpid, childpid, waitpid);
742                 if (status & 0xFF) {
743                         msg("Child %d returns LOB status %o\n",
744                                 childpid, status&0xFF);
745                 }
746                 status = (status >> 8) & 0xFF;
747 #ifdef TDEBUG
748                 switch(status) {
749                         case X_FINOK:
750                                 msg("Child %d finishes X_FINOK\n", childpid);
751                                 break;
752                         case X_ABORT:
753                                 msg("Child %d finishes X_ABORT\n", childpid);
754                                 break;
755                         case X_REWRITE:
756                                 msg("Child %d finishes X_REWRITE\n", childpid);
757                                 break;
758                         default:
759                                 msg("Child %d finishes unknown %d\n",
760                                         childpid, status);
761                                 break;
762                 }
763 #endif /* TDEBUG */
764                 switch(status) {
765                         case X_FINOK:
766                                 Exit(X_FINOK);
767                         case X_ABORT:
768                                 Exit(X_ABORT);
769                         case X_REWRITE:
770                                 goto restore_check_point;
771                         default:
772                                 msg("Bad return code from dump: %d\n", status);
773                                 Exit(X_ABORT);
774                 }
775                 /*NOTREACHED*/
776         } else {        /* we are the child; just continue */
777 #ifdef TDEBUG
778                 sleep(4);       /* allow time for parent's message to get out */
779                 msg("Child on Tape %d has parent %d, my pid = %d\n",
780                         tapeno+1, parentpid, getpid());
781 #endif /* TDEBUG */
782                 /*
783                  * If we have a name like "/dev/rmt0,/dev/rmt1",
784                  * use the name before the comma first, and save
785                  * the remaining names for subsequent volumes.
786                  */
787                 tapeno++;               /* current tape sequence */
788                 if (Mflag) {
789                         snprintf(tape, MAXPATHLEN, "%s%03d", tapeprefix, tapeno);
790                         tape[MAXPATHLEN - 1] = '\0';
791                         msg("Dumping volume %d on %s\n", tapeno, tape);
792                 }
793                 else if (nexttape || strchr(tapeprefix, ',')) {
794                         if (nexttape && *nexttape)
795                                 tapeprefix = nexttape;
796                         if ((p = strchr(tapeprefix, ',')) != NULL) {
797                                 *p = '\0';
798                                 nexttape = p + 1;
799                         } else
800                                 nexttape = NULL;
801                         strncpy(tape, tapeprefix, MAXPATHLEN);
802                         tape[MAXPATHLEN - 1] = '\0';
803                         msg("Dumping volume %d on %s\n", tapeno, tape);
804                 }
805 #ifdef RDUMP
806                 while ((tapefd = (host ? rmtopen(tape, 2) : pipeout ? 
807                         fileno(stdout) : 
808                         open(tape, O_WRONLY|O_CREAT, 0666))) < 0)
809 #else
810                 while ((tapefd = (pipeout ? fileno(stdout) :
811                                   open(tape, O_WRONLY|O_CREAT, 0666))) < 0)
812 #endif
813                     {
814                         msg("Cannot open output \"%s\".\n", tape);
815                         if (!query("Do you want to retry the open?"))
816                                 dumpabort(0);
817                 }
818
819                 enslave();  /* Share open tape file descriptor with slaves */
820
821                 asize = 0;
822                 blocksthisvol = 0;
823                 if (top)
824                         newtape++;              /* new tape signal */
825                 spcl.c_count = slp->count;
826                 /*
827                  * measure firstrec in TP_BSIZE units since restore doesn't
828                  * know the correct ntrec value...
829                  */
830                 spcl.c_firstrec = slp->firstrec;
831                 spcl.c_volume++;
832                 spcl.c_type = TS_TAPE;
833                 spcl.c_flags |= DR_NEWHEADER;
834                 writeheader((ino_t)slp->inode);
835                 spcl.c_flags &=~ DR_NEWHEADER;
836                 msg("Volume %d started at: %s", tapeno, 
837 #ifdef __linux__
838                                                 ctime4(&tstart_volume));
839 #else
840                                                 ctime(&tstart_volume));
841 #endif
842                 if (tapeno > 1)
843                         msg("Volume %d begins with blocks from inode %d\n",
844                                 tapeno, slp->inode);
845         }
846 }
847
848 void
849 dumpabort(int signo)
850 {
851
852         if (master != 0 && master != getpid())
853                 /* Signals master to call dumpabort */
854                 (void) kill(master, SIGTERM);
855         else {
856                 killall();
857                 msg("The ENTIRE dump is aborted.\n");
858         }
859 #ifdef RDUMP
860         rmtclose();
861 #endif
862         Exit(X_ABORT);
863 }
864
865 void
866 Exit(int status)
867 {
868
869 #ifdef TDEBUG
870         msg("pid = %d exits with status %d\n", getpid(), status);
871 #endif /* TDEBUG */
872         exit(status);
873 }
874
875 /*
876  * proceed - handler for SIGUSR2, used to synchronize IO between the slaves.
877  */
878 static void
879 proceed(int signo)
880 {
881         if (ready)
882                 siglongjmp(jmpbuf, 1);
883         caught++;
884 }
885
886 void
887 enslave(void)
888 {
889         int cmd[2];
890 #ifdef  LINUX_FORK_BUG
891         int i, j;
892 #else
893         register int i, j;
894 #endif
895
896         master = getpid();
897
898     {   struct sigaction sa;
899         memset(&sa, 0, sizeof sa);
900         sigemptyset(&sa.sa_mask);
901         sa.sa_handler = dumpabort;
902         sigaction(SIGTERM, &sa, NULL); /* Slave sends SIGTERM on dumpabort() */
903         sa.sa_handler = sigpipe;
904         sigaction(SIGPIPE, &sa, NULL);
905         sa.sa_handler = tperror;
906         sigaction(SIGUSR1, &sa, NULL); /* Slave sends SIGUSR1 on tape errors */
907         sa.sa_handler = proceed;
908         sa.sa_flags = SA_RESTART;
909         sigaction(SIGUSR2, &sa, NULL); /* Slave sends SIGUSR2 to next slave */
910    }
911
912         for (i = 0; i < SLAVES; i++) {
913                 if (i == slp - &slaves[0]) {
914                         caught = 1;
915                 } else {
916                         caught = 0;
917                 }
918
919                 if (socketpair(AF_UNIX, SOCK_STREAM, 0, cmd) < 0 ||
920                     (slaves[i].pid = fork()) < 0)
921                         quit("too many slaves, %d (recompile smaller): %s\n",
922                             i, strerror(errno));
923
924                 slaves[i].fd = cmd[1];
925                 slaves[i].sent = 0;
926                 if (slaves[i].pid == 0) {           /* Slave starts up here */
927                         sigset_t sigs;
928                         for (j = 0; j <= i; j++)
929                                 (void) close(slaves[j].fd);
930                         sigemptyset(&sigs);
931                         sigaddset(&sigs, SIGINT);  /* Master handles this */
932 #if defined(SIGINFO)
933                         sigaddset(&sigs, SIGINFO);
934 #endif
935                         sigprocmask(SIG_BLOCK, &sigs, NULL);
936
937 #ifdef  LINUX_FORK_BUG
938                         if (atomic_write( cmd[0], (char *) &i, sizeof i)
939                             != sizeof i)
940                                 quit("master/slave protocol botched 3\n");
941 #endif
942                         doslave(cmd[0], i);
943                         Exit(X_FINOK);
944                 }
945         }
946
947 #ifdef  LINUX_FORK_BUG
948         /*
949          * Wait for all slaves to _actually_ start to circumvent a bug in
950          * Linux kernels >= 2.1.3 where a signal sent to a child that hasn't
951          * returned from fork() causes a SEGV in the child process
952          */
953         for (i = 0; i < SLAVES; i++)
954                 if (atomic_read( slaves[i].fd, (char *) &j, sizeof j) != sizeof j)
955                         quit("master/slave protocol botched 4\n");
956 #endif
957
958         for (i = 0; i < SLAVES; i++)
959                 (void) atomic_write( slaves[i].fd, 
960                               (char *) &slaves[(i + 1) % SLAVES].pid, 
961                               sizeof slaves[0].pid);
962                 
963         master = 0; 
964 }
965
966 void
967 killall(void)
968 {
969         register int i;
970
971         for (i = 0; i < SLAVES; i++)
972                 if (slaves[i].pid > 0) {
973                         (void) kill(slaves[i].pid, SIGKILL);
974                         slaves[i].sent = 0;
975                 }
976 }
977
978 /*
979  * Synchronization - each process has a lockfile, and shares file
980  * descriptors to the following process's lockfile.  When our write
981  * completes, we release our lock on the following process's lock-
982  * file, allowing the following process to lock it and proceed. We
983  * get the lock back for the next cycle by swapping descriptors.
984  */
985 static void
986 doslave(int cmd, int slave_number)
987 {
988         register int nread;
989         int nextslave, size, eot_count;
990         volatile int wrote = 0;
991         sigset_t sigset;
992 #ifdef  __linux__
993         errcode_t retval;
994 #endif
995
996         /*
997          * Need our own seek pointer.
998          */
999         (void) close(diskfd);
1000         if ((diskfd = open(disk, O_RDONLY)) < 0)
1001                 quit("slave couldn't reopen disk: %s\n", strerror(errno));
1002 #ifdef  __linux__
1003         ext2fs_close(fs);
1004         retval = dump_fs_open(disk, &fs);
1005         if (retval)
1006                 quit("slave couldn't reopen disk: %s\n", error_message(retval));
1007 #endif  /* __linux__ */
1008
1009         /*
1010          * Need the pid of the next slave in the loop...
1011          */
1012         if ((nread = atomic_read( cmd, (char *)&nextslave, sizeof nextslave))
1013             != sizeof nextslave) {
1014                 quit("master/slave protocol botched - didn't get pid of next slave.\n");
1015         }
1016
1017         /*
1018          * Get list of blocks to dump, read the blocks into tape buffer
1019          */
1020         while ((nread = atomic_read( cmd, (char *)slp->req, reqsiz)) == reqsiz) {
1021                 register struct req *p = slp->req;
1022
1023                 for (trecno = 0; trecno < ntrec;
1024                      trecno += p->count, p += p->count) {
1025                         if (p->dblk) {
1026                                 bread(p->dblk, slp->tblock[trecno],
1027                                         p->count * TP_BSIZE);
1028                         } else {
1029                                 if (p->count != 1 || atomic_read( cmd,
1030                                     (char *)slp->tblock[trecno],
1031                                     TP_BSIZE) != TP_BSIZE)
1032                                        quit("master/slave protocol botched.\n");
1033                         }
1034                 }
1035                 if (sigsetjmp(jmpbuf, 1) == 0) {
1036                         ready = 1;
1037                         if (!caught)
1038                                 (void) pause();
1039                 }
1040                 ready = 0;
1041                 caught = 0;
1042
1043                 /* Try to write the data... */
1044                 wrote = 0;
1045                 eot_count = 0;
1046                 size = 0;
1047
1048                 while (eot_count < 10 && size < writesize) {
1049 #ifdef RDUMP
1050                         if (host)
1051                                 wrote = rmtwrite(slp->tblock[0]+size,
1052                                     writesize-size);
1053                         else
1054 #endif
1055                                 wrote = write(tapefd, slp->tblock[0]+size,
1056                                     writesize-size);
1057 #ifdef WRITEDEBUG
1058                         printf("slave %d wrote %d\n", slave_number, wrote);
1059 #endif
1060                         if (wrote < 0)
1061                                 break;
1062                         if (wrote == 0)
1063                                 eot_count++;
1064                         size += wrote;
1065                 }
1066
1067 #ifdef WRITEDEBUG
1068                 if (size != writesize)
1069                  printf("slave %d only wrote %d out of %d bytes and gave up.\n",
1070                      slave_number, size, writesize);
1071 #endif
1072
1073                 /*
1074                  * Handle ENOSPC as an EOT condition.
1075                  */
1076                 if (wrote < 0 && errno == ENOSPC) {
1077                         wrote = 0;
1078                         eot_count++;
1079                 }
1080
1081                 if (eot_count > 0)
1082                         size = 0;
1083
1084                 if (wrote < 0) {
1085                         (void) kill(master, SIGUSR1);
1086                         sigemptyset(&sigset);
1087                         sigaddset(&sigset, SIGINT);
1088                         for (;;)
1089                                 sigsuspend(&sigset);
1090                 } else {
1091                         /*
1092                          * pass size of write back to master
1093                          * (for EOT handling)
1094                          */
1095                         (void) atomic_write( cmd, (char *)&size, sizeof size);
1096                 }
1097
1098                 /*
1099                  * If partial write, don't want next slave to go.
1100                  * Also jolts him awake.
1101                  */
1102                 (void) kill(nextslave, SIGUSR2);
1103         }
1104         if (nread != 0)
1105                 quit("error reading command pipe: %s\n", strerror(errno));
1106 }
1107
1108 /*
1109  * Since a read from a pipe may not return all we asked for,
1110  * or a write may not write all we ask if we get a signal,
1111  * loop until the count is satisfied (or error).
1112  */
1113 static ssize_t
1114 atomic_read(int fd, void *buf, size_t count)
1115 {
1116         int got, need = count;
1117
1118         do {
1119                 while ((got = read(fd, buf, need)) > 0 && (need -= got) > 0)
1120                         (char *)buf += got;
1121         } while (got == -1 && errno == EINTR);
1122         return (got < 0 ? got : count - need);
1123 }
1124
1125 /*
1126  * Since a read from a pipe may not return all we asked for,
1127  * or a write may not write all we ask if we get a signal,
1128  * loop until the count is satisfied (or error).
1129  */
1130 static ssize_t
1131 atomic_write(int fd, const void *buf, size_t count)
1132 {
1133         int got, need = count;
1134
1135         do {
1136                 while ((got = write(fd, buf, need)) > 0 && (need -= got) > 0)
1137                         (char *)buf += got;
1138         } while (got == -1 && errno == EINTR);
1139         return (got < 0 ? got : count - need);
1140 }