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