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