]> git.wh0rd.org Git - dump.git/blob - dump/tape.c
Made -Q option work on regular files.
[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 <stelian@popies.net>, 1999-2000
6  *      Stelian Pop <stelian@popies.net> - AlcĂ´ve <www.alcove.com>, 2000-2002
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.60 2002/01/22 11:12:28 stelian Exp $";
45 #endif /* not lint */
46
47 #include <config.h>
48 #include <compatlfs.h>
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <setjmp.h>
52 #include <signal.h>
53 #include <stdio.h>
54 #include <compaterr.h>
55 #include <system.h>
56 #ifdef __STDC__
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60 #else
61 int    write(), read();
62 #endif
63
64 #ifdef __linux__
65 #include <sys/types.h>
66 #include <sys/time.h>
67 #include <time.h>
68 #endif
69 #include <sys/param.h>
70 #include <sys/socket.h>
71 #include <sys/wait.h>
72 #include <sys/mtio.h>
73 #ifdef __linux__
74 #include <linux/fs.h>
75 #undef atomic_read      /* this get wrongly defined in kernel */
76                         /* headers and we don't want it */
77 #ifdef HAVE_EXT2FS_EXT2_FS_H
78 #include <ext2fs/ext2_fs.h>
79 #else
80 #include <linux/ext2_fs.h>
81 #endif
82 #include <ext2fs/ext2fs.h>
83 #include <bsdcompat.h>
84 #elif defined sunos
85 #include <sys/vnode.h>
86
87 #include <ufs/fs.h>
88 #include <ufs/inode.h>
89 #else
90 #include <ufs/ufs/dinode.h>
91 #include <ufs/ffs/fs.h>
92 #endif  /* __linux__ */
93
94 #include <protocols/dumprestore.h>
95
96 #ifdef HAVE_ZLIB
97 #include <zlib.h>
98 #endif /* HAVE_ZLIB */
99
100 #ifdef HAVE_BZLIB
101 #include <bzlib.h>
102 #endif /* HAVE_BZLIB */
103
104 #include "dump.h"
105
106 int     writesize;              /* size of malloc()ed buffer for tape */
107 long    lastspclrec = -1;       /* tape block number of last written header */
108 int     trecno = 0;             /* next record to write in current block */
109 extern  long blocksperfile;     /* number of blocks per output file */
110 long    blocksthisvol;          /* number of blocks on current output file */
111 extern  int ntrec;              /* blocking factor on tape */
112 extern  int cartridge;
113 extern  char *host;
114 char    *nexttape;
115 extern  pid_t rshpid;
116 int     eot_code = 1;
117 long long tapea_bytes = 0;      /* bytes_written at start of current volume */
118 static int magtapeout;          /* output is really a tape */
119
120 static  ssize_t atomic_read __P((int, void *, size_t));
121 static  ssize_t atomic_write __P((int, const void *, size_t));
122 static  void doslave __P((int, int, int));
123 static  void enslave __P((void));
124 static  void flushtape __P((void));
125 static  void killall __P((void));
126 static  void rollforward __P((void));
127 #ifdef USE_QFA
128 static int GetTapePos __P((long *));
129 static void MkTapeString __P((struct s_spcl *, long));
130 #endif
131
132 /*
133  * Concurrent dump mods (Caltech) - disk block reading and tape writing
134  * are exported to several slave processes.  While one slave writes the
135  * tape, the others read disk blocks; they pass control of the tape in
136  * a ring via signals. The parent process traverses the filesystem and
137  * sends writeheader()'s and lists of daddr's to the slaves via pipes.
138  * The following structure defines the instruction packets sent to slaves.
139  */
140 struct req {
141         daddr_t dblk;
142         int count;
143 };
144 int reqsiz;
145
146 struct slave_results {
147         ssize_t unclen;         /* uncompressed length */
148         ssize_t clen;           /* compressed length */
149 };
150
151 #define SLAVES 3                /* 1 slave writing, 1 reading, 1 for slack */
152 struct slave {
153         int tapea;              /* header number at start of this chunk */
154         int count;              /* count to next header (used for TS_TAPE */
155                                 /* after EOT) */
156         int inode;              /* inode that we are currently dealing with */
157         int fd;                 /* FD for this slave */
158         int pid;                /* PID for this slave */
159         int sent;               /* 1 == we've sent this slave requests */
160         int firstrec;           /* record number of this block */
161         char (*tblock)[TP_BSIZE]; /* buffer for data blocks */
162         struct req *req;        /* buffer for requests */
163 } slaves[SLAVES+1];
164 struct slave *slp;
165
166 char    (*nextblock)[TP_BSIZE];
167
168 static time_t tstart_volume;    /* time of volume start */ 
169 static int tapea_volume;        /* value of spcl.c_tapea at volume start */
170
171 int master;             /* pid of master, for sending error signals */
172 int tenths;             /* length of tape overhead per block written */
173 static int caught;      /* have we caught the signal to proceed? */
174 static int ready;       /* have we reached the lock point without having */
175                         /* received the SIGUSR2 signal from the prev slave? */
176 static sigjmp_buf jmpbuf;       /* where to jump to if we are ready when the */
177                         /* SIGUSR2 arrives from the previous slave */
178 #ifdef USE_QFA
179 static int gtperr = 0;
180 #endif
181
182 int
183 alloctape(void)
184 {
185         int pgoff = getpagesize() - 1;
186         char *buf;
187         int i;
188
189         writesize = ntrec * TP_BSIZE;
190         reqsiz = (ntrec + 1) * sizeof(struct req);
191         /*
192          * CDC 92181's and 92185's make 0.8" gaps in 1600-bpi start/stop mode
193          * (see DEC TU80 User's Guide).  The shorter gaps of 6250-bpi require
194          * repositioning after stopping, i.e, streaming mode, where the gap is
195          * variable, 0.30" to 0.45".  The gap is maximal when the tape stops.
196          */
197         if (blocksperfile == 0 && !unlimited)
198                 tenths = (cartridge ? 16 : density == 625 ? 5 : 8);
199         else {
200                 tenths = 0;
201                 density = 1;
202         }
203         /*
204          * Allocate tape buffer contiguous with the array of instruction
205          * packets, so flushtape() can write them together with one write().
206          * Align tape buffer on page boundary to speed up tape write().
207          */
208         for (i = 0; i <= SLAVES; i++) {
209                 buf = (char *)
210                     malloc((unsigned)(reqsiz + writesize + pgoff + TP_BSIZE));
211                 if (buf == NULL)
212                         return(0);
213                 slaves[i].tblock = (char (*)[TP_BSIZE])
214 #ifdef  __linux__
215                     (((long)&buf[reqsiz] + pgoff) &~ pgoff);
216 #else
217                     (((long)&buf[ntrec + 1] + pgoff) &~ pgoff);
218 #endif
219                 slaves[i].req = (struct req *)slaves[i].tblock - ntrec - 1;
220         }
221         slp = &slaves[0];
222         slp->count = 1;
223         slp->tapea = 0;
224         slp->firstrec = 0;
225         nextblock = slp->tblock;
226         return(1);
227 }
228
229 void
230 writerec(const void *dp, int isspcl)
231 {
232
233         slp->req[trecno].dblk = (daddr_t)0;
234         slp->req[trecno].count = 1;
235         /* XXX post increment triggers an egcs-1.1.2-12 bug on alpha/sparc */
236         *(union u_spcl *)(*(nextblock)) = *(union u_spcl *)dp;
237         nextblock++;
238         if (isspcl)
239                 lastspclrec = spcl.c_tapea;
240         trecno++;
241         spcl.c_tapea++;
242         if (trecno >= ntrec)
243                 flushtape();
244 }
245
246 void
247 dumpblock(daddr_t blkno, int size)
248 {
249         int avail, tpblks, dblkno;
250
251         dblkno = fsbtodb(sblock, blkno);
252         tpblks = size >> tp_bshift;
253         while ((avail = MIN(tpblks, ntrec - trecno)) > 0) {
254                 slp->req[trecno].dblk = dblkno;
255                 slp->req[trecno].count = avail;
256                 trecno += avail;
257                 spcl.c_tapea += avail;
258                 if (trecno >= ntrec)
259                         flushtape();
260                 dblkno += avail << (tp_bshift - dev_bshift);
261                 tpblks -= avail;
262         }
263 }
264
265 int     nogripe = 0;
266
267 static void
268 tperror(int errnum)
269 {
270
271         if (pipeout) {
272                 msg("write error on %s: %s\n", tape, strerror(errnum));
273                 quit("Cannot recover\n");
274                 /* NOTREACHED */
275         }
276         msg("write error %d blocks into volume %d: %s\n", 
277             blocksthisvol, tapeno, strerror(errnum));
278         broadcast("DUMP WRITE ERROR!\n");
279         if (query("Do you want to rewrite this volume?")) {
280                 msg("Closing this volume.  Prepare to restart with new media;\n");
281                 msg("this dump volume will be rewritten.\n");
282                 killall();
283                 nogripe = 1;
284                 close_rewind();
285                 Exit(X_REWRITE);
286         }
287         if (query("Do you want to start the next tape?"))
288                 return;
289         dumpabort(0);
290 }
291
292 static void
293 sigpipe(int signo)
294 {
295
296         quit("Broken pipe\n");
297 }
298
299 /*
300  * do_stats --
301  *     Update xferrate stats
302  */
303 time_t
304 do_stats(void)
305 {
306         time_t tnow, ttaken;
307         int blocks;
308
309         tnow = time(NULL);
310         ttaken = tnow - tstart_volume;
311         blocks = spcl.c_tapea - tapea_volume;
312         msg("Volume %d completed at: %s", tapeno, ctime(&tnow));
313         if (! compressed)
314                 msg("Volume %d %ld tape blocks (%.2fMB)\n", tapeno, 
315                         blocks, ((double)blocks * TP_BSIZE / 1048576));
316         if (ttaken > 0) {
317                 long volkb = (bytes_written - tapea_bytes) / 1024;
318                 long txfrate = volkb / ttaken;
319                 msg("Volume %d took %d:%02d:%02d\n", tapeno,
320                         ttaken / 3600, (ttaken % 3600) / 60, ttaken % 60);
321                 msg("Volume %d transfer rate: %ld kB/s\n", tapeno,
322                         txfrate);
323                 xferrate += txfrate;
324                 if (compressed) {
325                         double rate = .0005 + (double) blocks / (double) volkb;
326                         msg("Volume %d %ldkB uncompressed, %ldkB compressed,"
327                                 " %1.3f:1\n",
328                                 tapeno, blocks, volkb, rate);
329                 }
330         }
331         return(tnow);
332 }
333
334 char *
335 mktimeest(time_t tnow)
336 {
337         static char msgbuf[128];
338         time_t deltat;
339
340         msgbuf[0] = '\0';
341
342         if (blockswritten < 500)
343                 return NULL;
344         if (blockswritten > tapesize)
345                 tapesize = blockswritten;
346         deltat = tstart_writing - tnow + (1.0 * (tnow - tstart_writing))
347                 / blockswritten * tapesize;
348         if (tnow > tstart_volume)
349                 (void)snprintf(msgbuf, sizeof(msgbuf),
350                         "%3.2f%% done at %ld kB/s, finished in %d:%02d\n",
351                         (blockswritten * 100.0) / tapesize,
352                         (spcl.c_tapea - tapea_volume) / (tnow - tstart_volume),
353                         (int)(deltat / 3600), (int)((deltat % 3600) / 60));
354         else
355                 (void)snprintf(msgbuf, sizeof(msgbuf),
356                         "%3.2f%% done, finished in %d:%02d\n",
357                         (blockswritten * 100.0) / tapesize,
358                         (int)(deltat / 3600), (int)((deltat % 3600) / 60));
359
360         return msgbuf;
361 }
362
363 #if defined(SIGINFO)
364 /*
365  * statussig --
366  *     information message upon receipt of SIGINFO
367  */
368 void
369 statussig(int notused)
370 {
371         int save_errno = errno;
372         char *buf;
373
374         buf = mktimeest(time(NULL));
375         if (buf)
376                 write(STDERR_FILENO, buf, strlen(buf));
377         errno = save_errno;
378 }
379 #endif
380
381 static void
382 flushtape(void)
383 {
384         int i, blks, got;
385         long lastfirstrec;
386         struct slave_results returned;
387
388         int siz = (char *)nextblock - (char *)slp->req;
389
390         slp->req[trecno].count = 0;                     /* Sentinel */
391
392         if (atomic_write( slp->fd, (char *)slp->req, siz) != siz)
393                 quit("error writing command pipe: %s\n", strerror(errno));
394         slp->sent = 1; /* we sent a request, read the response later */
395
396         lastfirstrec = slp->firstrec;
397
398         if (++slp >= &slaves[SLAVES])
399                 slp = &slaves[0];
400
401         /* Read results back from next slave */
402         if (slp->sent) {
403                 if (atomic_read( slp->fd, (char *)&returned, sizeof returned)
404                     != sizeof returned) {
405                         perror("  DUMP: error reading command pipe in master");
406                         dumpabort(0);
407                 }
408                 got = returned.unclen;
409                 bytes_written += returned.clen;
410                 if (returned.unclen == returned.clen)
411                         uncomprblks++;
412                 slp->sent = 0;
413
414                 /* Check for errors or end of tape */
415                 if (got <= 0) {
416                         /* Check for errors */
417                         if (got < 0)
418                                 tperror(-got);
419                         else
420                                 msg("End of tape detected\n");
421
422                         /*
423                          * Drain the results, don't care what the values were.
424                          * If we read them here then trewind won't...
425                          */
426                         for (i = 0; i < SLAVES; i++) {
427                                 if (slaves[i].sent) {
428                                         if (atomic_read( slaves[i].fd,
429                                             (char *)&returned, sizeof returned)
430                                             != sizeof returned) {
431                                                 perror("  DUMP: error reading command pipe in master");
432                                                 dumpabort(0);
433                                         }
434                                         slaves[i].sent = 0;
435                                 }
436                         }
437
438                         close_rewind();
439                         rollforward();
440                         return;
441                 }
442         }
443
444         blks = 0;
445         if (spcl.c_type != TS_END) {
446                 for (i = 0; i < spcl.c_count; i++)
447                         if (spcl.c_addr[i] != 0)
448                                 blks++;
449         }
450         slp->count = lastspclrec + blks + 1 - spcl.c_tapea;
451         slp->tapea = spcl.c_tapea;
452         slp->firstrec = lastfirstrec + ntrec;
453         slp->inode = curino;
454         nextblock = slp->tblock;
455         trecno = 0;
456         asize += tenths + returned.clen / density;
457         blockswritten += ntrec;
458         blocksthisvol += ntrec;
459         if (!pipeout && !unlimited) {
460                 if (blocksperfile) {
461                         if ( compressed ? (bytes_written - tapea_bytes + SLAVES * (writesize + sizeof(struct tapebuf))) >= blocksperfile * 1024
462                                         : blocksthisvol >= blocksperfile ) {
463                                 close_rewind();
464                                 startnewtape(0);
465                         }
466                 }
467                 else if (asize > tsize) {
468                         close_rewind();
469                         startnewtape(0);
470                 }
471         }
472         timeest();
473 }
474
475 time_t
476 trewind(void)
477 {
478         int f;
479         int got;
480         struct slave_results returned;
481
482         for (f = 0; f < SLAVES; f++) {
483                 /*
484                  * Drain the results, but unlike EOT we DO (or should) care
485                  * what the return values were, since if we detect EOT after
486                  * we think we've written the last blocks to the tape anyway,
487                  * we have to replay those blocks with rollforward.
488                  *
489                  * fixme: punt for now.
490                  */
491                 if (slaves[f].sent) {
492                         if (atomic_read( slaves[f].fd, (char *)&returned, sizeof returned)
493                             != sizeof returned) {
494                                 perror("  DUMP: error reading command pipe in master");
495                                 dumpabort(0);
496                         }
497                         got = returned.unclen;
498                         bytes_written += returned.clen;
499                         if (returned.unclen == returned.clen)
500                                 uncomprblks++;
501                         slaves[f].sent = 0;
502
503                         if (got < 0)
504                                 tperror(-got);
505
506                         if (got == 0) {
507                                 msg("EOT detected in last 2 tape records!\n");
508                                 msg("Use a longer tape, decrease the size estimate\n");
509                                 quit("or use no size estimate at all.\n");
510                         }
511                 }
512                 (void) close(slaves[f].fd);
513         }
514         while (wait((int *)NULL) >= 0)  /* wait for any signals from slaves */
515                 /* void */;
516
517         if (!pipeout) {
518
519                 msg("Closing %s\n", tape);
520
521 #ifdef RDUMP
522                 if (host) {
523                         rmtclose();
524                         while (rmtopen(tape, 0) < 0)
525                                 sleep(10);
526                         rmtclose();
527                 }
528                 else 
529 #endif
530                 {
531                         (void) close(tapefd);
532                         if (!fifoout) {
533                                 while ((f = OPEN(tape, 0)) < 0)
534                                         sleep (10);
535                                 (void) close(f);
536                         }
537                 }
538                 eot_code = 1;
539                 if (eot_script && spcl.c_type != TS_END) {
540                         msg("Launching %s\n", eot_script);
541                         eot_code = system_command(eot_script, tape, tapeno);
542                 }
543                 if (eot_code != 0 && eot_code != 1) {
544                         msg("Dump aborted by the end of tape script\n");
545                         dumpabort(0);
546                 }
547         }
548         return do_stats();
549 }
550
551                 
552 void
553 close_rewind(void)
554 {
555         (void)trewind();
556         if (nexttape || Mflag || (eot_code == 0) )
557                 return;
558         if (!nogripe) {
559                 msg("Change Volumes: Mount volume #%d\n", tapeno+1);
560                 broadcast("CHANGE DUMP VOLUMES!\7\7\n");
561         }
562         while (!query("Is the new volume mounted and ready to go?"))
563                 if (query("Do you want to abort?")) {
564                         dumpabort(0);
565                         /*NOTREACHED*/
566                 }
567 }
568
569 void
570 rollforward(void)
571 {
572         register struct req *p, *q = NULL, *prev;
573         register struct slave *tslp;
574         int i, size, savedtapea, got;
575         union u_spcl *ntb, *otb;
576         struct slave_results returned;
577 #ifdef __linux__
578         int blks;
579         long lastfirstrec;
580 #endif
581         tslp = &slaves[SLAVES];
582         ntb = (union u_spcl *)tslp->tblock[1];
583
584         /*
585          * Each of the N slaves should have requests that need to
586          * be replayed on the next tape.  Use the extra slave buffers
587          * (slaves[SLAVES]) to construct request lists to be sent to
588          * each slave in turn.
589          */
590         for (i = 0; i < SLAVES; i++) {
591                 q = &tslp->req[1];
592                 otb = (union u_spcl *)slp->tblock;
593
594                 /*
595                  * For each request in the current slave, copy it to tslp.
596                  */
597
598                 prev = NULL;
599                 for (p = slp->req; p->count > 0; p += p->count) {
600                         *q = *p;
601                         if (p->dblk == 0)
602                                 *ntb++ = *otb++; /* copy the datablock also */
603                         prev = q;
604                         q += q->count;
605                 }
606                 if (prev == NULL)
607                         quit("rollforward: protocol botch");
608                 if (prev->dblk != 0)
609                         prev->count -= 1;
610                 else
611                         ntb--;
612                 q -= 1;
613                 q->count = 0;
614                 q = &tslp->req[0];
615                 if (i == 0) {
616                         q->dblk = 0;
617                         q->count = 1;
618                         trecno = 0;
619                         nextblock = tslp->tblock;
620                         savedtapea = spcl.c_tapea;
621                         spcl.c_tapea = slp->tapea;
622                         startnewtape(0);
623                         spcl.c_tapea = savedtapea;
624                         lastspclrec = savedtapea - 1;
625                 }
626                 size = (char *)ntb - (char *)q;
627                 if (atomic_write( slp->fd, (char *)q, size) != size) {
628                         perror("  DUMP: error writing command pipe");
629                         dumpabort(0);
630                 }
631                 slp->sent = 1;
632 #ifdef __linux__
633                 lastfirstrec = slp->firstrec;
634 #endif
635                 if (++slp >= &slaves[SLAVES])
636                         slp = &slaves[0];
637
638                 q->count = 1;
639
640                 if (prev->dblk != 0) {
641                         /*
642                          * If the last one was a disk block, make the
643                          * first of this one be the last bit of that disk
644                          * block...
645                          */
646                         q->dblk = prev->dblk +
647                                 prev->count * (TP_BSIZE / DEV_BSIZE);
648                         ntb = (union u_spcl *)tslp->tblock;
649                 } else {
650                         /*
651                          * It wasn't a disk block.  Copy the data to its
652                          * new location in the buffer.
653                          */
654                         q->dblk = 0;
655                         *((union u_spcl *)tslp->tblock) = *ntb;
656                         ntb = (union u_spcl *)tslp->tblock[1];
657                 }
658         }
659         slp->req[0] = *q;
660         nextblock = slp->tblock;
661         if (q->dblk == 0) {
662 #ifdef __linux__
663         /* XXX post increment triggers an egcs-1.1.2-12 bug on alpha/sparc */
664                 *(union u_spcl *)(*nextblock) = *(union u_spcl *)tslp->tblock;
665 #endif
666                 nextblock++;
667         }
668         trecno = 1;
669
670         /*
671          * Clear the first slaves' response.  One hopes that it
672          * worked ok, otherwise the tape is much too short!
673          */
674         if (slp->sent) {
675                 if (atomic_read( slp->fd, (char *)&returned, sizeof returned)
676                     != sizeof returned) {
677                         perror("  DUMP: error reading command pipe in master");
678                         dumpabort(0);
679                 }
680                 got = returned.unclen;
681                 bytes_written += returned.clen;
682                 if (returned.clen == returned.unclen)
683                         uncomprblks++;
684                 slp->sent = 0;
685
686                 if (got < 0)
687                         tperror(-got);
688
689                 if (got == 0) {
690                         quit("EOT detected at start of the tape!\n");
691                 }
692         }
693
694 #ifdef __linux__
695         blks = 0;
696         if (spcl.c_type != TS_END) {
697                 for (i = 0; i < spcl.c_count; i++)
698                         if (spcl.c_addr[i] != 0)
699                                 blks++;
700         }
701
702         slp->firstrec = lastfirstrec + ntrec;
703         slp->count = lastspclrec + blks + 1 - spcl.c_tapea;
704         slp->inode = curino;
705         asize += tenths + returned.clen / density;
706         blockswritten += ntrec;
707         blocksthisvol += ntrec;
708 #endif
709 }
710
711 /*
712  * We implement taking and restoring checkpoints on the tape level.
713  * When each tape is opened, a new process is created by forking; this
714  * saves all of the necessary context in the parent.  The child
715  * continues the dump; the parent waits around, saving the context.
716  * If the child returns X_REWRITE, then it had problems writing that tape;
717  * this causes the parent to fork again, duplicating the context, and
718  * everything continues as if nothing had happened.
719  */
720 void
721 startnewtape(int top)
722 {
723         int     parentpid;
724         int     childpid;
725         int     status;
726         int     waitpid;
727         char    *p;
728
729 #ifdef  __linux__
730         sigset_t sigs;
731         sigemptyset(&sigs);
732         sigaddset(&sigs, SIGINT);
733         sigprocmask(SIG_BLOCK, &sigs, NULL);
734 #else   /* __linux__ */
735 #ifdef sunos
736         void    (*interrupt_save)();
737 #else
738         sig_t   interrupt_save;
739 #endif
740         interrupt_save = signal(SIGINT, SIG_IGN);
741 #endif  /* __linux__ */
742
743         parentpid = getpid();
744         tapea_volume = spcl.c_tapea;
745         tapea_bytes = bytes_written;
746         tstart_volume = time(NULL);
747
748 restore_check_point:
749 #ifdef  __linux__
750         sigprocmask(SIG_UNBLOCK, &sigs, NULL);
751 #else
752         (void)signal(SIGINT, interrupt_save);
753 #endif
754         /*
755          *      All signals are inherited...
756          */
757         childpid = fork();
758         if (childpid < 0) {
759                 msg("Context save fork fails in parent %d\n", parentpid);
760                 Exit(X_ABORT);
761         }
762         if (childpid != 0) {
763                 /*
764                  *      PARENT:
765                  *      save the context by waiting
766                  *      until the child doing all of the work returns.
767                  *      don't catch the interrupt
768                  */
769 #ifdef  __linux__
770                 sigprocmask(SIG_BLOCK, &sigs, NULL);
771 #else
772                 signal(SIGINT, SIG_IGN);
773 #endif
774 #ifdef TDEBUG
775                 msg("Tape: %d; parent process: %d child process %d\n",
776                         tapeno+1, parentpid, childpid);
777 #endif /* TDEBUG */
778                 while ((waitpid = wait(&status)) != childpid)
779                         if (waitpid != rshpid)
780                                 msg("Parent %d waiting for child %d has another child %d return\n",
781                                 parentpid, childpid, waitpid);
782                 if (status & 0xFF) {
783                         msg("Child %d returns LOB status %o\n",
784                                 childpid, status&0xFF);
785                 }
786                 status = (status >> 8) & 0xFF;
787 #ifdef TDEBUG
788                 switch(status) {
789                         case X_FINOK:
790                                 msg("Child %d finishes X_FINOK\n", childpid);
791                                 break;
792                         case X_ABORT:
793                                 msg("Child %d finishes X_ABORT\n", childpid);
794                                 break;
795                         case X_REWRITE:
796                                 msg("Child %d finishes X_REWRITE\n", childpid);
797                                 break;
798                         default:
799                                 msg("Child %d finishes unknown %d\n",
800                                         childpid, status);
801                                 break;
802                 }
803 #endif /* TDEBUG */
804                 switch(status) {
805                         case X_FINOK:
806                                 Exit(X_FINOK);
807                         case X_ABORT:
808                                 Exit(X_ABORT);
809                         case X_REWRITE:
810                                 goto restore_check_point;
811                         default:
812                                 msg("Bad return code from dump: %d\n", status);
813                                 Exit(X_ABORT);
814                 }
815                 /*NOTREACHED*/
816         } else {        /* we are the child; just continue */
817 #ifdef TDEBUG
818                 sleep(4);       /* allow time for parent's message to get out */
819                 msg("Child on Tape %d has parent %d, my pid = %d\n",
820                         tapeno+1, parentpid, getpid());
821 #endif /* TDEBUG */
822                 /*
823                  * If we have a name like "/dev/rmt0,/dev/rmt1",
824                  * use the name before the comma first, and save
825                  * the remaining names for subsequent volumes.
826                  */
827                 tapeno++;               /* current tape sequence */
828                 if (Mflag) {
829                         snprintf(tape, MAXPATHLEN, "%s%03d", tapeprefix, tapeno);
830                         tape[MAXPATHLEN - 1] = '\0';
831                         msg("Dumping volume %d on %s\n", tapeno, tape);
832                 }
833                 else if (nexttape || strchr(tapeprefix, ',')) {
834                         if (nexttape && *nexttape)
835                                 tapeprefix = nexttape;
836                         if ((p = strchr(tapeprefix, ',')) != NULL) {
837                                 *p = '\0';
838                                 nexttape = p + 1;
839                         } else
840                                 nexttape = NULL;
841                         strncpy(tape, tapeprefix, MAXPATHLEN);
842                         tape[MAXPATHLEN - 1] = '\0';
843                         msg("Dumping volume %d on %s\n", tapeno, tape);
844                 }
845 #ifdef RDUMP
846                 while ((tapefd = (host ? rmtopen(tape, 2) : pipeout ? 
847                         fileno(stdout) : 
848                         OPEN(tape, O_WRONLY|O_CREAT, 0666))) < 0)
849 #else
850                 while ((tapefd = (pipeout ? fileno(stdout) :
851                                   OPEN(tape, O_RDWR|O_CREAT, 0666))) < 0)
852 #endif
853                     {
854                         msg("Cannot open output \"%s\".\n", tape);
855                         if (!query("Do you want to retry the open?"))
856                                 dumpabort(0);
857                 }
858 #ifdef RDUMP
859                 if (!host)
860 #endif
861                         {
862                                 struct mtget mt_stat;
863                                 magtapeout = ioctl(tapefd, MTIOCGET, (char *)&mt_stat) == 0;
864                                 /*
865                                 msg("Output is to %s\n", 
866                                         magtapeout ? "tape" : "file/pipe");
867                                 */
868                         }
869
870                 enslave();  /* Share open tape file descriptor with slaves */
871
872                 asize = 0;
873                 blocksthisvol = 0;
874                 if (top)
875                         newtape++;              /* new tape signal */
876                 spcl.c_count = slp->count;
877                 /*
878                  * measure firstrec in TP_BSIZE units since restore doesn't
879                  * know the correct ntrec value...
880                  */
881                 spcl.c_firstrec = slp->firstrec;
882                 spcl.c_volume++;
883                 spcl.c_type = TS_TAPE;
884                 spcl.c_flags |= DR_NEWHEADER;
885                 spcl.c_ntrec = ntrec;
886                 if (compressed)
887                         spcl.c_flags |= DR_COMPRESSED;
888                 writeheader((dump_ino_t)slp->inode);
889                 spcl.c_flags &=~ DR_NEWHEADER;
890                 msg("Volume %d started with block %ld at: %s", tapeno, 
891                     spcl.c_tapea, ctime(&tstart_volume));
892                 if (tapeno > 1)
893                         msg("Volume %d begins with blocks from inode %d\n",
894                                 tapeno, slp->inode);
895         }
896 }
897
898 void
899 dumpabort(int signo)
900 {
901
902         if (master != 0 && master != getpid())
903                 /* Signals master to call dumpabort */
904                 (void) kill(master, SIGTERM);
905         else {
906                 killall();
907                 msg("The ENTIRE dump is aborted.\n");
908         }
909 #ifdef RDUMP
910         rmtclose();
911 #endif
912         Exit(X_ABORT);
913 }
914
915 void
916 Exit(int status)
917 {
918
919 #ifdef TDEBUG
920         msg("pid = %d exits with status %d\n", getpid(), status);
921 #endif /* TDEBUG */
922         exit(status);
923 }
924
925 /*
926  * proceed - handler for SIGUSR2, used to synchronize IO between the slaves.
927  */
928 static void
929 proceed(int signo)
930 {
931         if (ready)
932                 siglongjmp(jmpbuf, 1);
933         caught++;
934 }
935
936 void
937 enslave(void)
938 {
939         int cmd[2];
940 #ifdef  LINUX_FORK_BUG
941         int i, j;
942 #else
943         register int i, j;
944 #endif
945
946         master = getpid();
947
948     {   struct sigaction sa;
949         memset(&sa, 0, sizeof sa);
950         sigemptyset(&sa.sa_mask);
951         sa.sa_handler = dumpabort;
952         sigaction(SIGTERM, &sa, NULL); /* Slave sends SIGTERM on dumpabort() */
953         sa.sa_handler = sigpipe;
954         sigaction(SIGPIPE, &sa, NULL);
955         sa.sa_handler = proceed;
956         sa.sa_flags = SA_RESTART;
957         sigaction(SIGUSR2, &sa, NULL); /* Slave sends SIGUSR2 to next slave */
958    }
959
960         for (i = 0; i < SLAVES; i++) {
961                 if (i == slp - &slaves[0]) {
962                         caught = 1;
963                 } else {
964                         caught = 0;
965                 }
966
967                 if (socketpair(AF_UNIX, SOCK_STREAM, 0, cmd) < 0 ||
968                     (slaves[i].pid = fork()) < 0)
969                         quit("too many slaves, %d (recompile smaller): %s\n",
970                             i, strerror(errno));
971
972                 slaves[i].fd = cmd[1];
973                 slaves[i].sent = 0;
974                 if (slaves[i].pid == 0) {           /* Slave starts up here */
975                         sigset_t sigs;
976                         for (j = 0; j <= i; j++)
977                                 (void) close(slaves[j].fd);
978                         sigemptyset(&sigs);
979                         sigaddset(&sigs, SIGINT);  /* Master handles this */
980 #if defined(SIGINFO)
981                         sigaddset(&sigs, SIGINFO);
982 #endif
983                         sigprocmask(SIG_BLOCK, &sigs, NULL);
984
985 #ifdef  LINUX_FORK_BUG
986                         if (atomic_write( cmd[0], (char *) &i, sizeof i)
987                             != sizeof i)
988                                 quit("master/slave protocol botched 3\n");
989 #endif
990                         doslave(cmd[0], i, (slaves[i].pid == slp->pid));
991                         Exit(X_FINOK);
992                 }
993                 else
994                         close(cmd[0]);
995         }
996
997 #ifdef  LINUX_FORK_BUG
998         /*
999          * Wait for all slaves to _actually_ start to circumvent a bug in
1000          * Linux kernels >= 2.1.3 where a signal sent to a child that hasn't
1001          * returned from fork() causes a SEGV in the child process
1002          */
1003         for (i = 0; i < SLAVES; i++)
1004                 if (atomic_read( slaves[i].fd, (char *) &j, sizeof j) != sizeof j)
1005                         quit("master/slave protocol botched 4\n");
1006 #endif
1007
1008         for (i = 0; i < SLAVES; i++)
1009                 (void) atomic_write( slaves[i].fd, 
1010                               (char *) &slaves[(i + 1) % SLAVES].pid, 
1011                               sizeof slaves[0].pid);
1012                 
1013         master = 0; 
1014 }
1015
1016 void
1017 killall(void)
1018 {
1019         register int i;
1020
1021         for (i = 0; i < SLAVES; i++)
1022                 if (slaves[i].pid > 0) {
1023                         (void) kill(slaves[i].pid, SIGKILL);
1024                         slaves[i].sent = 0;
1025                 }
1026 }
1027
1028 /*
1029  * Synchronization - each process waits for a SIGUSR2 from the
1030  * previous process before writing to the tape, and sends SIGUSR2
1031  * to the next process when the tape write completes. On tape errors
1032  * a SIGUSR1 is sent to the master which then terminates all of the
1033  * slaves.
1034  */
1035 static void
1036 doslave(int cmd, int slave_number, int first)
1037 {
1038         register int nread;
1039         int nextslave, size, eot_count, bufsize;
1040         volatile int wrote = 0;
1041         char *buffer;
1042 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB)
1043         struct tapebuf *comp_buf = NULL;
1044         int compresult, do_compress = !first;
1045         unsigned long worklen;
1046 #ifdef HAVE_BZLIB
1047         unsigned int worklen2;
1048 #endif
1049 #endif /* HAVE_ZLIB || HAVE_BZLIB */
1050         struct slave_results returns;
1051 #ifdef  __linux__
1052         errcode_t retval;
1053 #endif
1054 #ifdef USE_QFA
1055         long curtapepos;
1056         union u_spcl *uspclptr;
1057         struct s_spcl *spclptr;
1058 #endif /* USE_QFA */
1059         sigset_t set;
1060
1061         sigemptyset(&set);
1062         sigaddset(&set, SIGUSR2);
1063         sigprocmask(SIG_BLOCK, &set, NULL);
1064         sigemptyset(&set);
1065
1066         /*
1067          * Need our own seek pointer.
1068          */
1069         (void) close(diskfd);
1070         if ((diskfd = OPEN(disk, O_RDONLY)) < 0)
1071                 quit("slave couldn't reopen disk: %s\n", strerror(errno));
1072 #ifdef  __linux__
1073 #ifdef BLKFLSBUF
1074         (void)ioctl(diskfd, BLKFLSBUF);
1075 #endif
1076         ext2fs_close(fs);
1077         retval = dump_fs_open(disk, &fs);
1078         if (retval)
1079                 quit("slave couldn't reopen disk: %s\n", error_message(retval));
1080 #endif  /* __linux__ */
1081
1082         /*
1083          * Need the pid of the next slave in the loop...
1084          */
1085         if ((nread = atomic_read( cmd, (char *)&nextslave, sizeof nextslave))
1086             != sizeof nextslave) {
1087                 quit("master/slave protocol botched - didn't get pid of next slave.\n");
1088         }
1089
1090 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB)
1091         /* if we're doing a compressed dump, allocate the compress buffer */
1092         if (compressed) {
1093                 comp_buf = malloc(sizeof(struct tapebuf) + TP_BSIZE + writesize);
1094                 if (comp_buf == NULL)
1095                         quit("couldn't allocate a compress buffer.\n");
1096                 if (bzipflag)
1097                         comp_buf->flags = COMPRESS_BZLIB;
1098                 else
1099                         comp_buf->flags = COMPRESS_ZLIB;
1100         }
1101 #endif /* HAVE_ZLIB || HAVE_BZLIB */
1102
1103         /*
1104          * Get list of blocks to dump, read the blocks into tape buffer
1105          */
1106         while ((nread = atomic_read( cmd, (char *)slp->req, reqsiz)) == reqsiz) {
1107                 register struct req *p = slp->req;
1108
1109                 for (trecno = 0; trecno < ntrec;
1110                      trecno += p->count, p += p->count) {
1111                         if (p->dblk) {  /* read a disk block */
1112                                 bread(p->dblk, slp->tblock[trecno],
1113                                         p->count * TP_BSIZE);
1114                         } else {        /* read record from pipe */
1115                                 if (p->count != 1 || atomic_read( cmd,
1116                                     (char *)slp->tblock[trecno],
1117                                     TP_BSIZE) != TP_BSIZE)
1118                                        quit("master/slave protocol botched.\n");
1119                         }
1120                 }
1121
1122                 /* Try to write the data... */
1123                 wrote = 0;
1124                 eot_count = 0;
1125                 size = 0;
1126                 buffer = (char *) slp->tblock[0];       /* set write pointer */
1127                 bufsize = writesize;                    /* length to write */
1128                 returns.clen = returns.unclen = bufsize;
1129
1130 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB)
1131                 /* 
1132                  * When writing a compressed dump, each block except
1133                  * the first one on each tape is written
1134                  * from struct tapebuf with an 4 byte prefix
1135                  * followed by the data. This can be less than
1136                  * writesize. Restore, on a short read, can compare the
1137                  * length read to the compressed length in the header
1138                  * to verify that the read was good. Blocks which don't
1139                  * compress well are written uncompressed.
1140                  * The first block written by each slave is not compressed
1141                  * and does not have a prefix.
1142                  */
1143
1144                 if (compressed && do_compress) {
1145                         comp_buf->length = bufsize;
1146                         worklen = TP_BSIZE + writesize;
1147                         compresult = 1;
1148 #ifdef HAVE_ZLIB
1149                         if (!bzipflag) {
1150                                 compresult = compress2(comp_buf->buf, 
1151                                                        &worklen,
1152                                                        (char *)slp->tblock[0],
1153                                                        writesize, 
1154                                                        compressed);
1155                                 if (compresult == Z_OK)
1156                                         compresult = 1;
1157                                 else
1158                                         compresult = 0;
1159                         }
1160 #endif /* HAVE_ZLIB */
1161 #ifdef HAVE_BZLIB
1162                         if (bzipflag) {
1163                                 worklen2 = worklen;
1164                                 compresult = BZ2_bzBuffToBuffCompress(
1165                                                        comp_buf->buf,
1166                                                        &worklen2,
1167                                                        (char *)slp->tblock[0],
1168                                                        writesize,
1169                                                        compressed,
1170                                                        0, 30);
1171                                 worklen = worklen2;
1172                                 if (compresult == BZ_OK)
1173                                         compresult = 1;
1174                                 else
1175                                         compresult = 0;
1176                         }
1177
1178 #endif /* HAVE_BZLIB */
1179                         if (compresult && worklen <= (writesize - 16)) {
1180                                 /* write the compressed buffer */
1181                                 comp_buf->length = worklen;
1182                                 comp_buf->compressed = 1;
1183                                 buffer = (char *) comp_buf;
1184                                 returns.clen = bufsize = worklen + sizeof(struct tapebuf);
1185                         }
1186                         else {
1187                                 /* write the data uncompressed */
1188                                 comp_buf->length = writesize;
1189                                 comp_buf->compressed = 0;
1190                                 buffer = (char *) comp_buf;
1191                                 returns.clen = bufsize = writesize + sizeof(struct tapebuf);
1192                                 returns.unclen = returns.clen;
1193                                 memcpy(comp_buf->buf, (char *)slp->tblock[0], writesize);
1194                         }
1195                 }
1196                 /* compress the remaining blocks if we're compressing */
1197                 do_compress = compressed;
1198 #endif /* HAVE_ZLIB  || HAVE_BZLIB */
1199
1200                 if (sigsetjmp(jmpbuf, 1) == 0) {
1201                         ready = 1;
1202                         if (!caught)
1203                                 sigsuspend(&set);
1204                 }
1205                 ready = 0;
1206                 caught = 0;
1207
1208 #ifdef USE_QFA
1209                 if (gTapeposfd >= 0) {
1210                         int i;
1211                         for (i = 0; i < ntrec; ++i) {
1212                                 uspclptr = (union u_spcl *)&slp->tblock[i];
1213                                 spclptr = &uspclptr->s_spcl;
1214                                 if ((spclptr->c_magic == NFS_MAGIC) && 
1215                                     (spclptr->c_type == TS_INODE) &&
1216                                     (spclptr->c_date == gThisDumpDate)) {
1217                                         /* if an error occured previously don't
1218                                          * try again */
1219                                         if (gtperr == 0) {
1220                                                 if ((gtperr = GetTapePos(&curtapepos)) == 0)
1221                                                         MkTapeString(spclptr, curtapepos);
1222                                         }
1223                                 }
1224                         }
1225                 }
1226 #endif /* USE_QFA */
1227                                                 
1228                 while (eot_count < 10 && size < bufsize) {
1229 #ifdef RDUMP
1230                         if (host)
1231                                 wrote = rmtwrite(buffer + size, bufsize - size);
1232                         else
1233 #endif
1234                                 wrote = write(tapefd, buffer + size, bufsize - size);
1235 #ifdef WRITEDEBUG
1236                         printf("slave %d wrote %d\n", slave_number, wrote);
1237 #endif
1238                         if (wrote < 0)
1239                                 break;
1240                         if (wrote == 0)
1241                                 eot_count++;
1242                         size += wrote;
1243                 }
1244
1245 #ifdef WRITEDEBUG
1246                 if (size != bufsize)
1247                  printf("slave %d only wrote %d out of %d bytes and gave up.\n",
1248                      slave_number, size, bufsize);
1249 #endif
1250
1251                 /*
1252                  * Handle ENOSPC as an EOT condition.
1253                  */
1254                 if (wrote < 0 && errno == ENOSPC) {
1255                         wrote = 0;
1256                         eot_count++;
1257                 }
1258
1259                 if (eot_count > 0)
1260                         returns.clen = returns.unclen = 0;
1261
1262                 /*
1263                  * pass errno back to master for special handling
1264                  */
1265                 if (wrote < 0)
1266                         returns.unclen = -errno;
1267
1268                 /*
1269                  * pass size of data and size of write back to master
1270                  * (for EOT handling)
1271                  */
1272                 (void) atomic_write( cmd, (char *)&returns, sizeof returns);
1273
1274                 /*
1275                  * Signal the next slave to go.
1276                  */
1277                 (void) kill(nextslave, SIGUSR2);
1278         }
1279         if (nread != 0)
1280                 quit("error reading command pipe: %s\n", strerror(errno));
1281 }
1282
1283 /*
1284  * Since a read from a pipe may not return all we asked for,
1285  * or a write may not write all we ask if we get a signal,
1286  * loop until the count is satisfied (or error).
1287  */
1288 static ssize_t
1289 atomic_read(int fd, void *buf, size_t count)
1290 {
1291         int got, need = count;
1292
1293         do {
1294                 while ((got = read(fd, buf, need)) > 0 && (need -= got) > 0)
1295                         (char *)buf += got;
1296         } while (got == -1 && errno == EINTR);
1297         return (got < 0 ? got : count - need);
1298 }
1299
1300 /*
1301  * Since a read from a pipe may not return all we asked for,
1302  * or a write may not write all we ask if we get a signal,
1303  * loop until the count is satisfied (or error).
1304  */
1305 static ssize_t
1306 atomic_write(int fd, const void *buf, size_t count)
1307 {
1308         int got, need = count;
1309
1310         do {
1311                 while ((got = write(fd, buf, need)) > 0 && (need -= got) > 0)
1312                         (char *)buf += got;
1313         } while (got == -1 && errno == EINTR);
1314         return (got < 0 ? got : count - need);
1315 }
1316
1317
1318 #ifdef USE_QFA
1319 /*
1320  * read the current tape position
1321  */
1322 static int
1323 GetTapePos(long *pos)
1324 {
1325         int err = 0;
1326
1327         if (magtapeout) {
1328                 *pos = 0;
1329                 err = (ioctl(tapefd, MTIOCPOS, pos) < 0);
1330         }
1331         else {
1332                 *pos = lseek(tapefd, 0, SEEK_CUR);
1333                 err = (*pos < 0);
1334         }
1335         if (err) {
1336                 err = errno;
1337                 msg("[%ld] error: %d (getting tapepos: %ld)\n", getpid(), 
1338                         err, *pos);
1339                 return err;
1340         }
1341         return err;
1342 }
1343
1344 static void 
1345 MkTapeString(struct s_spcl *spclptr, long curtapepos) {
1346
1347 #ifdef DEBUG_QFA
1348         msg("inode %ld at tapepos %ld\n", spclptr->c_inumber, curtapepos);
1349 #endif
1350
1351         snprintf(gTps, sizeof(gTps), "%ld\t%d\t%ld\n", 
1352                  (unsigned long)spclptr->c_inumber, 
1353                  tapeno, 
1354                  curtapepos);
1355         gTps[sizeof(gTps) - 1] = '\0';
1356         if (write(gTapeposfd, gTps, strlen(gTps)) != strlen(gTps)) {
1357                 warn("error writing tapepos file.\n");
1358         }
1359 }
1360 #endif /* USE_QFA */