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