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