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