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