Fix ihandle.c indents
[openafs.git] / src / vol / salvaged.c
1 /*
2  * Copyright 2006-2007, Sine Nomine Associates and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /*
11  * demand attach fs
12  * online salvager daemon
13  */
14
15 /* Main program file. Define globals. */
16 #define MAIN 1
17
18 #include <afsconfig.h>
19 #include <afs/param.h>
20
21 #include <roken.h>
22
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <dirent.h>
27 #include <sys/stat.h>
28 #include <time.h>
29 #include <errno.h>
30 #ifdef AFS_NT40_ENV
31 #include <io.h>
32 #include <WINNT/afsevent.h>
33 #else
34 #include <sys/param.h>
35 #include <sys/file.h>
36 #ifndef ITIMER_REAL
37 #include <sys/time.h>
38 #endif /* ITIMER_REAL */
39 #endif
40 #ifndef WCOREDUMP
41 #define WCOREDUMP(x)    ((x) & 0200)
42 #endif
43 #include <rx/xdr.h>
44 #include <afs/afsint.h>
45 #include <afs/afs_assert.h>
46 #if !defined(AFS_SGI_ENV) && !defined(AFS_NT40_ENV)
47 #if defined(AFS_VFSINCL_ENV)
48 #include <sys/vnode.h>
49 #ifdef  AFS_SUN5_ENV
50 #include <sys/fs/ufs_inode.h>
51 #else
52 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
53 #include <ufs/ufs/dinode.h>
54 #include <ufs/ffs/fs.h>
55 #else
56 #include <ufs/inode.h>
57 #endif
58 #endif
59 #else /* AFS_VFSINCL_ENV */
60 #ifdef  AFS_OSF_ENV
61 #include <ufs/inode.h>
62 #else /* AFS_OSF_ENV */
63 #if !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_ARM_DARWIN_ENV)
64 #include <sys/inode.h>
65 #endif
66 #endif
67 #endif /* AFS_VFSINCL_ENV */
68 #endif /* AFS_SGI_ENV */
69 #ifdef  AFS_AIX_ENV
70 #include <sys/vfs.h>
71 #include <sys/lockf.h>
72 #else
73 #ifdef  AFS_HPUX_ENV
74 #include <unistd.h>
75 #include <checklist.h>
76 #else
77 #if defined(AFS_SGI_ENV)
78 #include <unistd.h>
79 #include <fcntl.h>
80 #include <mntent.h>
81 #else
82 #if     defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
83 #ifdef    AFS_SUN5_ENV
84 #include <unistd.h>
85 #include <sys/mnttab.h>
86 #include <sys/mntent.h>
87 #else
88 #include <mntent.h>
89 #endif
90 #else
91 #endif /* AFS_SGI_ENV */
92 #endif /* AFS_HPUX_ENV */
93 #endif
94 #endif
95 #include <fcntl.h>
96 #ifndef AFS_NT40_ENV
97 #include <afs/osi_inode.h>
98 #endif
99 #include <afs/cmd.h>
100 #include <afs/afsutil.h>
101 #include <afs/fileutil.h>
102 #include <afs/procmgmt.h>       /* signal(), kill(), wait(), etc. */
103 #include <afs/dir.h>
104 #ifndef AFS_NT40_ENV
105 #include <syslog.h>
106 #endif
107
108 #include "nfs.h"
109 #include "lwp.h"
110 #include "lock.h"
111 #include <afs/afssyscalls.h>
112 #include "ihandle.h"
113 #include "vnode.h"
114 #include "volume.h"
115 #include "partition.h"
116 #include "daemon_com.h"
117 #include "fssync.h"
118 #include "salvsync.h"
119 #include "viceinode.h"
120 #include "salvage.h"
121 #include "vol-salvage.h"
122 #include "common.h"
123 #ifdef AFS_NT40_ENV
124 #include <pthread.h>
125 #endif
126
127
128 #if !defined(AFS_DEMAND_ATTACH_FS)
129 #error "online salvager only supported for demand attach fileserver"
130 #endif /* AFS_DEMAND_ATTACH_FS */
131
132 #if defined(AFS_NT40_ENV)
133 #error "online salvager not supported on NT"
134 #endif /* AFS_NT40_ENV */
135
136 /*@+fcnmacros +macrofcndecl@*/
137 #ifdef O_LARGEFILE
138 #define afs_fopen       fopen64
139 #else /* !O_LARGEFILE */
140 #define afs_fopen       fopen
141 #endif /* !O_LARGEFILE */
142 /*@=fcnmacros =macrofcndecl@*/
143
144
145
146 static volatile int current_workers = 0;
147 static volatile struct rx_queue pending_q;
148 static pthread_mutex_t worker_lock;
149 static pthread_cond_t worker_cv;
150
151 static void * SalvageChildReaperThread(void *);
152 static int DoSalvageVolume(struct SalvageQueueNode * node, int slot);
153
154 static void SalvageServer(int argc, char **argv);
155 static void SalvageClient(VolumeId vid, char * pname);
156
157 static int Reap_Child(char * prog, int * pid, int * status);
158
159 static void * SalvageLogCleanupThread(void *);
160 static int SalvageLogCleanup(int pid);
161
162 static void * SalvageLogScanningThread(void *);
163 static void ScanLogs(struct rx_queue *log_watch_queue);
164
165 struct cmdline_rock {
166     int argc;
167     char **argv;
168 };
169
170 struct log_cleanup_node {
171     struct rx_queue q;
172     int pid;
173 };
174
175 struct {
176     struct rx_queue queue_head;
177     pthread_cond_t queue_change_cv;
178 } log_cleanup_queue;
179
180
181 #define DEFAULT_PARALLELISM 4 /* allow 4 parallel salvage workers by default */
182
183 static int
184 handleit(struct cmd_syndesc *as, void *arock)
185 {
186     struct cmd_item *ti;
187     char pname[100], *temp;
188     afs_int32 seenpart = 0, seenvol = 0;
189     VolumeId vid = 0;
190     struct cmdline_rock *rock = (struct cmdline_rock *)arock;
191
192 #ifdef AFS_SGI_VNODE_GLUE
193     if (afs_init_kernel_config(-1) < 0) {
194         printf
195             ("Can't determine NUMA configuration, not starting salvager.\n");
196         exit(1);
197     }
198 #endif
199
200     if (as->parms[2].items)     /* -debug */
201         debug = 1;
202     if (as->parms[3].items)     /* -nowrite */
203         Testing = 1;
204     if (as->parms[4].items)     /* -inodes */
205         ListInodeOption = 1;
206     if (as->parms[5].items)     /* -oktozap */
207         OKToZap = 1;
208     if (as->parms[6].items)     /* -rootinodes */
209         ShowRootFiles = 1;
210     if (as->parms[8].items)     /* -ForceReads */
211         forceR = 1;
212     if ((ti = as->parms[9].items)) {    /* -Parallel # */
213         temp = ti->data;
214         if (strncmp(temp, "all", 3) == 0) {
215             PartsPerDisk = 1;
216             temp += 3;
217         }
218         if (strlen(temp) != 0) {
219             Parallel = atoi(temp);
220             if (Parallel < 1)
221                 Parallel = 1;
222             if (Parallel > MAXPARALLEL) {
223                 printf("Setting parallel salvages to maximum of %d \n",
224                        MAXPARALLEL);
225                 Parallel = MAXPARALLEL;
226             }
227         }
228     } else {
229         Parallel = MIN(DEFAULT_PARALLELISM, MAXPARALLEL);
230     }
231     if ((ti = as->parms[10].items)) {   /* -tmpdir */
232         DIR *dirp;
233
234         tmpdir = ti->data;
235         dirp = opendir(tmpdir);
236         if (!dirp) {
237             printf
238                 ("Can't open temporary placeholder dir %s; using current partition \n",
239                  tmpdir);
240             tmpdir = NULL;
241         } else
242             closedir(dirp);
243     }
244     if ((ti = as->parms[11].items))     /* -showlog */
245         ShowLog = 1;
246     if ((ti = as->parms[12].items)) {   /* -orphans */
247         if (Testing)
248             orphans = ORPH_IGNORE;
249         else if (strcmp(ti->data, "remove") == 0
250                  || strcmp(ti->data, "r") == 0)
251             orphans = ORPH_REMOVE;
252         else if (strcmp(ti->data, "attach") == 0
253                  || strcmp(ti->data, "a") == 0)
254             orphans = ORPH_ATTACH;
255     }
256 #ifndef AFS_NT40_ENV            /* ignore options on NT */
257     if ((ti = as->parms[13].items)) {   /* -syslog */
258         useSyslog = 1;
259         ShowLog = 0;
260     }
261     if ((ti = as->parms[14].items)) {   /* -syslogfacility */
262         useSyslogFacility = atoi(ti->data);
263     }
264
265     if ((ti = as->parms[15].items)) {   /* -datelogs */
266         TimeStampLogFile((char *)AFSDIR_SERVER_SALSRVLOG_FILEPATH);
267     }
268 #endif
269
270     if ((ti = as->parms[16].items)) {   /* -client */
271         if ((ti = as->parms[0].items)) {        /* -partition */
272             seenpart = 1;
273             strlcpy(pname, ti->data, sizeof(pname));
274         }
275         if ((ti = as->parms[1].items)) {        /* -volumeid */
276             char *end;
277             unsigned long vid_l;
278             seenvol = 1;
279             vid_l = strtoul(ti->data, &end, 10);
280             if (vid_l >= MAX_AFS_UINT32 || vid_l == ULONG_MAX || *end != '\0') {
281                 printf("Invalid volume id specified; salvage aborted\n");
282                 exit(-1);
283             }
284             vid = (VolumeId)vid_l;
285         }
286
287         if (ShowLog) {
288             printf("-showlog does not work with -client\n");
289             exit(-1);
290         }
291
292         if (!seenpart || !seenvol) {
293             printf("You must specify '-partition' and '-volumeid' with the '-client' option\n");
294             exit(-1);
295         }
296
297         SalvageClient(vid, pname);
298
299     } else {  /* salvageserver mode */
300         SalvageServer(rock->argc, rock->argv);
301     }
302     return (0);
303 }
304
305
306 #ifndef AFS_NT40_ENV
307 #include "AFS_component_version_number.c"
308 #endif
309 #define MAX_ARGS 128
310 #ifdef AFS_NT40_ENV
311 char *save_args[MAX_ARGS];
312 int n_save_args = 0;
313 pthread_t main_thread;
314 #endif
315
316 int
317 main(int argc, char **argv)
318 {
319     struct cmd_syndesc *ts;
320     int err = 0;
321     struct cmdline_rock arock;
322
323 #ifdef  AFS_AIX32_ENV
324     /*
325      * The following signal action for AIX is necessary so that in case of a
326      * crash (i.e. core is generated) we can include the user's data section
327      * in the core dump. Unfortunately, by default, only a partial core is
328      * generated which, in many cases, isn't too useful.
329      */
330     struct sigaction nsa;
331
332     sigemptyset(&nsa.sa_mask);
333     nsa.sa_handler = SIG_DFL;
334     nsa.sa_flags = SA_FULLDUMP;
335     sigaction(SIGABRT, &nsa, NULL);
336     sigaction(SIGSEGV, &nsa, NULL);
337 #endif
338
339     /* Initialize directory paths */
340     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
341 #ifdef AFS_NT40_ENV
342         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
343 #endif
344         fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
345                 argv[0]);
346         exit(2);
347     }
348 #ifdef AFS_NT40_ENV
349     /* Default to binary mode for fopen() */
350     _set_fmode(_O_BINARY);
351
352     main_thread = pthread_self();
353     if (spawnDatap && spawnDataLen) {
354         /* This is a child per partition salvager. Don't setup log or
355          * try to lock the salvager lock.
356          */
357         if (nt_SetupPartitionSalvage(spawnDatap, spawnDataLen) < 0)
358             exit(3);
359     } else {
360 #endif
361
362 #ifndef AFS_NT40_ENV
363         if (geteuid() != 0) {
364             printf("Salvager must be run as root.\n");
365             fflush(stdout);
366             Exit(0);
367         }
368 #endif
369
370         /* bad for normal help flag processing, but can do nada */
371
372 #ifdef AFS_NT40_ENV
373     }
374 #endif
375
376     arock.argc = argc;
377     arock.argv = argv;
378
379     ts = cmd_CreateSyntax("initcmd", handleit, &arock, "initialize the program");
380     cmd_AddParm(ts, "-partition", CMD_SINGLE, CMD_OPTIONAL,
381                 "Name of partition to salvage");
382     cmd_AddParm(ts, "-volumeid", CMD_SINGLE, CMD_OPTIONAL,
383                 "Volume Id to salvage");
384     cmd_AddParm(ts, "-debug", CMD_FLAG, CMD_OPTIONAL,
385                 "Run in Debugging mode");
386     cmd_AddParm(ts, "-nowrite", CMD_FLAG, CMD_OPTIONAL,
387                 "Run readonly/test mode");
388     cmd_AddParm(ts, "-inodes", CMD_FLAG, CMD_OPTIONAL,
389                 "Just list affected afs inodes - debugging flag");
390     cmd_AddParm(ts, "-oktozap", CMD_FLAG, CMD_OPTIONAL,
391                 "Give permission to destroy bogus inodes/volumes - debugging flag");
392     cmd_AddParm(ts, "-rootinodes", CMD_FLAG, CMD_OPTIONAL,
393                 "Show inodes owned by root - debugging flag");
394     cmd_AddParm(ts, "-salvagedirs", CMD_FLAG, CMD_OPTIONAL,
395                 "Force rebuild/salvage of all directories");
396     cmd_AddParm(ts, "-blockreads", CMD_FLAG, CMD_OPTIONAL,
397                 "Read smaller blocks to handle IO/bad blocks");
398     cmd_AddParm(ts, "-parallel", CMD_SINGLE, CMD_OPTIONAL,
399                 "# of max parallel partition salvaging");
400     cmd_AddParm(ts, "-tmpdir", CMD_SINGLE, CMD_OPTIONAL,
401                 "Name of dir to place tmp files ");
402     cmd_AddParm(ts, "-showlog", CMD_FLAG, CMD_OPTIONAL,
403                 "Show log file upon completion");
404     cmd_AddParm(ts, "-orphans", CMD_SINGLE, CMD_OPTIONAL,
405                 "ignore | remove | attach");
406
407     /* note - syslog isn't avail on NT, but if we make it conditional, have
408      * to deal with screwy offsets for cmd params */
409     cmd_AddParm(ts, "-syslog", CMD_FLAG, CMD_OPTIONAL,
410                 "Write salvage log to syslogs");
411     cmd_AddParm(ts, "-syslogfacility", CMD_SINGLE, CMD_OPTIONAL,
412                 "Syslog facility number to use");
413     cmd_AddParm(ts, "-datelogs", CMD_FLAG, CMD_OPTIONAL,
414                 "Include timestamp in logfile filename");
415
416     cmd_AddParm(ts, "-client", CMD_FLAG, CMD_OPTIONAL,
417                 "Use SALVSYNC to ask salvageserver to salvage a volume");
418
419     err = cmd_Dispatch(argc, argv);
420     Exit(err);
421     return 0; /* not reached */
422 }
423
424 static void
425 SalvageClient(VolumeId vid, char * pname)
426 {
427     int done = 0;
428     afs_int32 code;
429     SYNC_response res;
430     SALVSYNC_response_hdr sres;
431     VolumePackageOptions opts;
432
433     VOptDefaults(volumeUtility, &opts);
434     if (VInitVolumePackage2(volumeUtility, &opts)) {
435         /* VInitVolumePackage2 can fail on e.g. partition attachment errors,
436          * but we don't really care, since all we're doing is trying to use
437          * SALVSYNC */
438         fprintf(stderr, "errors encountered initializing volume package, but "
439                         "trying to continue anyway\n");
440     }
441     SALVSYNC_clientInit();
442
443     code = SALVSYNC_SalvageVolume(vid, pname, SALVSYNC_SALVAGE, SALVSYNC_OPERATOR, 0, NULL);
444     if (code != SYNC_OK) {
445         goto sync_error;
446     }
447
448     res.payload.buf = (void *) &sres;
449     res.payload.len = sizeof(sres);
450
451     while(!done) {
452         sleep(2);
453         code = SALVSYNC_SalvageVolume(vid, pname, SALVSYNC_QUERY, SALVSYNC_WHATEVER, 0, &res);
454         if (code != SYNC_OK) {
455             goto sync_error;
456         }
457         switch (sres.state) {
458         case SALVSYNC_STATE_ERROR:
459             printf("salvageserver reports salvage ended in an error; check log files for more details\n");
460         case SALVSYNC_STATE_DONE:
461         case SALVSYNC_STATE_UNKNOWN:
462             done = 1;
463         }
464     }
465     SALVSYNC_clientFinis();
466     return;
467
468  sync_error:
469     if (code == SYNC_DENIED) {
470         printf("salvageserver refused to salvage volume %u on partition %s\n",
471                vid, pname);
472     } else if (code == SYNC_BAD_COMMAND) {
473         printf("SALVSYNC protocol mismatch; please make sure fileserver, volserver, salvageserver and salvager are same version\n");
474     } else if (code == SYNC_COM_ERROR) {
475         printf("SALVSYNC communications error\n");
476     }
477     SALVSYNC_clientFinis();
478     exit(-1);
479 }
480
481 static int * child_slot;
482
483 static void
484 SalvageServer(int argc, char **argv)
485 {
486     int pid, ret;
487     struct SalvageQueueNode * node;
488     pthread_t tid;
489     pthread_attr_t attrs;
490     int slot;
491     VolumePackageOptions opts;
492
493     /* All entries to the log will be appended.  Useful if there are
494      * multiple salvagers appending to the log.
495      */
496
497     CheckLogFile((char *)AFSDIR_SERVER_SALSRVLOG_FILEPATH);
498 #ifndef AFS_NT40_ENV
499 #ifdef AFS_LINUX20_ENV
500     fcntl(fileno(logFile), F_SETFL, O_APPEND);  /* Isn't this redundant? */
501 #else
502     fcntl(fileno(logFile), F_SETFL, FAPPEND);   /* Isn't this redundant? */
503 #endif
504 #endif
505     setlinebuf(logFile);
506
507     fprintf(logFile, "%s\n", cml_version_number);
508     LogCommandLine(argc, argv, "Online Salvage Server",
509                    SalvageVersion, "Starting OpenAFS", Log);
510     /* Get and hold a lock for the duration of the salvage to make sure
511      * that no other salvage runs at the same time.  The routine
512      * VInitVolumePackage2 (called below) makes sure that a file server or
513      * other volume utilities don't interfere with the salvage.
514      */
515
516     /* even demand attach online salvager
517      * still needs this because we don't want
518      * a stand-alone salvager to conflict with
519      * the salvager daemon */
520     ObtainSharedSalvageLock();
521
522     child_slot = (int *) malloc(Parallel * sizeof(int));
523     osi_Assert(child_slot != NULL);
524     memset(child_slot, 0, Parallel * sizeof(int));
525
526     /* initialize things */
527     VOptDefaults(salvageServer, &opts);
528     if (VInitVolumePackage2(salvageServer, &opts)) {
529         Log("Shutting down: errors encountered initializing volume package\n");
530         Exit(1);
531     }
532     DInit(10);
533     queue_Init(&pending_q);
534     queue_Init(&log_cleanup_queue);
535     MUTEX_INIT(&worker_lock, "worker", MUTEX_DEFAULT, 0);
536     CV_INIT(&worker_cv, "worker", CV_DEFAULT, 0);
537     CV_INIT(&log_cleanup_queue.queue_change_cv, "queuechange", CV_DEFAULT, 0);
538     osi_Assert(pthread_attr_init(&attrs) == 0);
539
540     /* start up the reaper and log cleaner threads */
541     osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
542     osi_Assert(pthread_create(&tid,
543                           &attrs,
544                           &SalvageChildReaperThread,
545                           NULL) == 0);
546     osi_Assert(pthread_create(&tid,
547                           &attrs,
548                           &SalvageLogCleanupThread,
549                           NULL) == 0);
550     osi_Assert(pthread_create(&tid,
551                           &attrs,
552                           &SalvageLogScanningThread,
553                           NULL) == 0);
554
555     /* loop forever serving requests */
556     while (1) {
557         node = SALVSYNC_getWork();
558         osi_Assert(node != NULL);
559
560         Log("dispatching child to salvage volume %u...\n",
561             node->command.sop.parent);
562
563         VOL_LOCK;
564         /* find a slot */
565         for (slot = 0; slot < Parallel; slot++) {
566           if (!child_slot[slot])
567             break;
568         }
569         osi_Assert (slot < Parallel);
570
571     do_fork:
572         pid = Fork();
573         if (pid == 0) {
574             VOL_UNLOCK;
575             ret = DoSalvageVolume(node, slot);
576             Exit(ret);
577         } else if (pid < 0) {
578             Log("failed to fork child worker process\n");
579             sleep(1);
580             goto do_fork;
581         } else {
582             child_slot[slot] = pid;
583             node->pid = pid;
584             VOL_UNLOCK;
585
586             MUTEX_ENTER(&worker_lock);
587             current_workers++;
588
589             /* let the reaper thread know another worker was spawned */
590             CV_BROADCAST(&worker_cv);
591
592             /* if we're overquota, wait for the reaper */
593             while (current_workers >= Parallel) {
594                 CV_WAIT(&worker_cv, &worker_lock);
595             }
596             MUTEX_EXIT(&worker_lock);
597         }
598     }
599 }
600
601 static int
602 DoSalvageVolume(struct SalvageQueueNode * node, int slot)
603 {
604     char childLog[AFSDIR_PATH_MAX];
605     struct DiskPartition64 * partP;
606
607     /* do not allow further forking inside salvager */
608     canfork = 0;
609
610     /* do not attempt to close parent's logFile handle as
611      * another thread may have held the lock on the FILE
612      * structure when fork was called! */
613
614     afs_snprintf(childLog, sizeof(childLog), "%s.%d",
615                  AFSDIR_SERVER_SLVGLOG_FILEPATH, getpid());
616
617     logFile = afs_fopen(childLog, "a");
618     if (!logFile) {             /* still nothing, use stdout */
619         logFile = stdout;
620         ShowLog = 0;
621     }
622
623     if (node->command.sop.parent <= 0) {
624         Log("salvageServer: invalid volume id specified; salvage aborted\n");
625         return 1;
626     }
627
628     partP = VGetPartition(node->command.sop.partName, 0);
629     if (!partP) {
630         Log("salvageServer: Unknown or unmounted partition %s; salvage aborted\n",
631             node->command.sop.partName);
632         return 1;
633     }
634
635     /* obtain a shared salvage lock in the child worker, so if the
636      * salvageserver restarts (and we continue), we will still hold a lock and
637      * prevent standalone salvagers from interfering */
638     ObtainSharedSalvageLock();
639
640     /* Salvage individual volume; don't notify fs */
641     SalvageFileSys1(partP, node->command.sop.parent);
642
643     fclose(logFile);
644     return 0;
645 }
646
647
648 static void *
649 SalvageChildReaperThread(void * args)
650 {
651     int slot, pid, status;
652     struct log_cleanup_node * cleanup;
653
654     MUTEX_ENTER(&worker_lock);
655
656     /* loop reaping our children */
657     while (1) {
658         /* wait() won't block unless we have children, so
659          * block on the cond var if we're childless */
660         while (current_workers == 0) {
661             CV_WAIT(&worker_cv, &worker_lock);
662         }
663
664         MUTEX_EXIT(&worker_lock);
665
666         cleanup = (struct log_cleanup_node *) malloc(sizeof(struct log_cleanup_node));
667
668         while (Reap_Child("salvageserver", &pid, &status) < 0) {
669             /* try to prevent livelock if something goes wrong */
670             sleep(1);
671         }
672
673         VOL_LOCK;
674         for (slot = 0; slot < Parallel; slot++) {
675             if (child_slot[slot] == pid)
676                 break;
677         }
678         osi_Assert(slot < Parallel);
679         child_slot[slot] = 0;
680         VOL_UNLOCK;
681
682         SALVSYNC_doneWorkByPid(pid, status);
683
684         MUTEX_ENTER(&worker_lock);
685
686         if (cleanup) {
687             cleanup->pid = pid;
688             queue_Append(&log_cleanup_queue, cleanup);
689             CV_SIGNAL(&log_cleanup_queue.queue_change_cv);
690         }
691
692         /* ok, we've reaped a child */
693         current_workers--;
694         CV_BROADCAST(&worker_cv);
695     }
696
697     return NULL;
698 }
699
700 static int
701 Reap_Child(char *prog, int * pid, int * status)
702 {
703     int ret;
704     ret = wait(status);
705
706     if (ret >= 0) {
707         *pid = ret;
708         if (WCOREDUMP(*status))
709             Log("\"%s\" core dumped!\n", prog);
710         if ((WIFSIGNALED(*status) != 0) ||
711             ((WEXITSTATUS(*status) != 0) &&
712              (WEXITSTATUS(*status) != SALSRV_EXIT_VOLGROUP_LINK)))
713             Log("\"%s\" (pid=%d) terminated abnormally!\n", prog, ret);
714     } else {
715         Log("wait returned -1\n");
716     }
717     return ret;
718 }
719
720 /*
721  * thread to combine salvager child logs
722  * back into the main salvageserver log
723  */
724 static void *
725 SalvageLogCleanupThread(void * arg)
726 {
727     struct log_cleanup_node * cleanup;
728
729     MUTEX_ENTER(&worker_lock);
730
731     while (1) {
732         while (queue_IsEmpty(&log_cleanup_queue)) {
733             CV_WAIT(&log_cleanup_queue.queue_change_cv, &worker_lock);
734         }
735
736         while (queue_IsNotEmpty(&log_cleanup_queue)) {
737             cleanup = queue_First(&log_cleanup_queue, log_cleanup_node);
738             queue_Remove(cleanup);
739             MUTEX_EXIT(&worker_lock);
740             SalvageLogCleanup(cleanup->pid);
741             free(cleanup);
742             MUTEX_ENTER(&worker_lock);
743         }
744     }
745
746     MUTEX_EXIT(&worker_lock);
747     return NULL;
748 }
749
750 #define LOG_XFER_BUF_SIZE 65536
751 static int
752 SalvageLogCleanup(int pid)
753 {
754     int pidlog, len;
755     char fn[AFSDIR_PATH_MAX];
756     static char buf[LOG_XFER_BUF_SIZE];
757
758     afs_snprintf(fn, sizeof(fn), "%s.%d",
759                  AFSDIR_SERVER_SLVGLOG_FILEPATH, pid);
760
761
762     pidlog = open(fn, O_RDONLY);
763     unlink(fn);
764     if (pidlog < 0)
765         return 1;
766
767     len = read(pidlog, buf, LOG_XFER_BUF_SIZE);
768     while (len) {
769         fwrite(buf, len, 1, logFile);
770         len = read(pidlog, buf, LOG_XFER_BUF_SIZE);
771     }
772
773     close(pidlog);
774
775     return 0;
776 }
777
778 /* wake up every five minutes to see if a non-child salvage has finished */
779 #define SALVAGE_SCAN_POLL_INTERVAL 300
780
781 /**
782  * Thread to look for SalvageLog.$pid files that are not from our child
783  * worker salvagers, and notify SalvageLogCleanupThread to clean them
784  * up. This can happen if we restart during salvages, or the
785  * salvageserver crashes or something.
786  *
787  * @param arg  unused
788  *
789  * @return always NULL
790  */
791 static void *
792 SalvageLogScanningThread(void * arg)
793 {
794     struct rx_queue log_watch_queue;
795
796     queue_Init(&log_watch_queue);
797
798     {
799         DIR *dp;
800         struct dirent *dirp;
801         char prefix[AFSDIR_PATH_MAX];
802         size_t prefix_len;
803
804         afs_snprintf(prefix, sizeof(prefix), "%s.", AFSDIR_SLVGLOG_FILE);
805         prefix_len = strlen(prefix);
806
807         dp = opendir(AFSDIR_LOGS_DIR);
808         osi_Assert(dp);
809
810         while ((dirp = readdir(dp)) != NULL) {
811             pid_t pid;
812             struct log_cleanup_node *cleanup;
813             int i;
814
815             if (strncmp(dirp->d_name, prefix, prefix_len) != 0) {
816                 /* not a salvage logfile; skip */
817                 continue;
818             }
819
820             errno = 0;
821             pid = strtol(dirp->d_name + prefix_len, NULL, 10);
822
823             if (errno != 0) {
824                 /* file is SalvageLog.<something> but <something> isn't
825                  * a pid, so skip */
826                  continue;
827             }
828
829             VOL_LOCK;
830             for (i = 0; i < Parallel; ++i) {
831                 if (pid == child_slot[i]) {
832                     break;
833                 }
834             }
835             VOL_UNLOCK;
836             if (i < Parallel) {
837                 /* this pid is one of our children, so the reaper thread
838                  * will take care of it; skip */
839                 continue;
840             }
841
842             cleanup =
843                 (struct log_cleanup_node *) malloc(sizeof(struct log_cleanup_node));
844             cleanup->pid = pid;
845
846             queue_Append(&log_watch_queue, cleanup);
847         }
848
849         closedir(dp);
850     }
851
852     ScanLogs(&log_watch_queue);
853
854     while (queue_IsNotEmpty(&log_watch_queue)) {
855         sleep(SALVAGE_SCAN_POLL_INTERVAL);
856         ScanLogs(&log_watch_queue);
857     }
858
859     return NULL;
860 }
861
862 /**
863  * look through log_watch_queue, and if any processes are not still
864  * running, hand them off to the SalvageLogCleanupThread
865  *
866  * @param log_watch_queue  a queue of PIDs that we should clean up if
867  * that PID has died
868  */
869 static void
870 ScanLogs(struct rx_queue *log_watch_queue)
871 {
872     struct log_cleanup_node *cleanup, *next;
873
874     MUTEX_ENTER(&worker_lock);
875
876     for (queue_Scan(log_watch_queue, cleanup, next, log_cleanup_node)) {
877         /* if a process is still running, assume it's the salvage process
878          * still going, and keep waiting for it */
879         if (kill(cleanup->pid, 0) < 0 && errno == ESRCH) {
880             queue_Remove(cleanup);
881             queue_Append(&log_cleanup_queue, cleanup);
882             CV_SIGNAL(&log_cleanup_queue.queue_change_cv);
883         }
884     }
885
886     MUTEX_EXIT(&worker_lock);
887 }