viced: Use libcmd for command line options
[openafs.git] / src / viced / viced.c
1 /*
2  * Copyright 2000, International Business Machines Corporation 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  * Portions Copyright (c) 2006 Sine Nomine Associates
10  */
11
12 /*  viced.c     - File Server main loop                                  */
13 /*                                                                       */
14 /*  Date: 5/1/85                                                         */
15 /*                                                                       */
16 /*  Function    - This routine has the initialization code for           */
17 /*                FileServer II                                          */
18 /*                                                                       */
19 /* ********************************************************************** */
20
21 #include <afsconfig.h>
22 #include <afs/param.h>
23 #include <afs/stds.h>
24
25 #include <afs/procmgmt.h>
26 #include <roken.h>
27
28 #ifdef AFS_NT40_ENV
29 # include <windows.h>
30 # include <WINNT/afsevent.h>
31 #endif
32
33 #ifdef HAVE_SYS_FILE_H
34 # include <sys/file.h>
35 #endif
36
37 #ifdef HAVE_SYS_RESOURCE_H
38 # include <sys/resource.h>
39 #endif
40
41 #undef SHARED
42
43 #include <rx/xdr.h>
44 #include <afs/nfs.h>
45 #include <afs/afs_assert.h>
46 #include <lwp.h>
47 #include <lock.h>
48 #include <afs/cmd.h>
49 #include <afs/ptclient.h>
50 #include <afs/afsint.h>
51 #include <afs/vldbint.h>
52 #include <afs/errors.h>
53 #include <afs/ihandle.h>
54 #include <afs/vnode.h>
55 #include <afs/volume.h>
56 #include <afs/auth.h>
57 #include <afs/cellconfig.h>
58 #include <afs/acl.h>
59 #include <afs/prs_fs.h>
60 #include <rx/rx.h>
61 #include <rx/rxstat.h>
62 #include <afs/keys.h>
63 #include <afs/afs_args.h>
64 #include <afs/vlserver.h>
65 #include <afs/afsutil.h>
66 #include <afs/fileutil.h>
67 #include <afs/ptuser.h>
68 #include <afs/audit.h>
69 #include <afs/partition.h>
70 #include <afs/dir.h>
71 #ifndef AFS_NT40_ENV
72 # include <afs/netutils.h>
73 #endif
74 #include "viced_prototypes.h"
75 #include "viced.h"
76 #include "host.h"
77 #ifdef AFS_PTHREAD_ENV
78 # include <afs/softsig.h>
79 #endif
80 #if defined(AFS_SGI_ENV)
81 # include "sys/schedctl.h"
82 # include "sys/lock.h"
83 #endif
84 #include <rx/rx_globals.h>
85
86 extern int etext;
87
88 void *ShutDown(void *);
89 static void ClearXStatValues(void);
90 static void PrintCounters(void);
91 static void ResetCheckDescriptors(void);
92 static void ResetCheckSignal(void);
93 static void *CheckSignal(void *);
94
95 static afs_int32 Do_VLRegisterRPC(void);
96
97 int eventlog = 0, rxlog = 0;
98 FILE *debugFile;
99
100 #ifdef AFS_PTHREAD_ENV
101 pthread_mutex_t fsync_glock_mutex;
102 pthread_cond_t fsync_cond;
103 #else
104 char fsync_wait[1];
105 #endif /* AFS_PTHREAD_ENV */
106
107 #ifdef AFS_NT40_ENV
108 # define NT_OPEN_MAX    1024    /* This is an arbitrary no. we came up with for
109                                  * now. We hope this will be replaced by a more
110                                  * intelligent estimate later. */
111 #endif
112
113 int SystemId;                   /* ViceID of "Administrators" */
114 int SystemAnyUser;              /* Viceid of "System:AnyUser" */
115 prlist SystemAnyUserCPS;        /* CPS for "system:AnyUser */
116 int AnonymousID = 0;            /* ViceId of "Anonymous" */
117 prlist AnonCPS;                 /* CPS for "Anonymous" */
118
119 struct afsconf_dir *confDir;    /* Configuration dir object */
120
121 int restartMode = RESTART_ORDINARY;
122
123 /*
124  * Home for the performance statistics.
125  */
126 struct afs_PerfStats afs_perfstats;
127
128 extern int LogLevel;
129 extern int Statistics;
130
131 int busyonrst = 1;
132 int timeout = 30;
133 int printBanner = 0;
134 int rxJumbograms = 0;           /* default is to not send and receive jumbograms. */
135 int rxBind = 0;         /* don't bind */
136 int rxkadDisableDotCheck = 0;      /* disable check for dot in principal name */
137 int rxMaxMTU = -1;
138 afs_int32 implicitAdminRights = PRSFS_LOOKUP;   /* The ADMINISTER right is
139                                                  * already implied */
140 afs_int32 readonlyServer = 0;
141
142 int stack = 24;
143 int stackSize = 24000;
144 int fiveminutes = 300;          /* 5 minutes.  Change this for debugging only */
145 int CurrentConnections = 0;
146 int hostaclRefresh = 7200;      /* refresh host clients' acls every 2 hrs */
147 #if defined(AFS_SGI_ENV)
148 int SawLock;
149 #endif
150 time_t StartTime;
151
152 /**
153  * seconds to wait until forcing a panic during ShutDownAndCore(PANIC)
154  * in case we get stuck.
155  */
156 #ifdef AFS_DEMAND_ATTACH_FS
157 static int panic_timeout = 2 * 60;
158 #else
159 static int panic_timeout = 30 * 60;
160 #endif
161
162 int rxpackets = 150;            /* 100 */
163 int nSmallVns = 400;            /* 200 */
164 int large = 400;                /* 200 */
165 int volcache = 400;             /* 400 */
166 int numberofcbs = 60000;        /* 60000 */
167 int lwps = 9;                   /* 6 */
168 int buffs = 90;                 /* 70 */
169 int novbc = 0;                  /* Enable Volume Break calls */
170 int busy_threshold = 600;
171 int abort_threshold = 10;
172 int udpBufSize = 0;             /* UDP buffer size for receive */
173 int sendBufSize = 16384;        /* send buffer size */
174 int saneacls = 0;               /* Sane ACLs Flag */
175 static int unsafe_attach = 0;   /* avoid inUse check on vol attach? */
176 static int offline_timeout = -1; /* -offline-timeout option */
177 static int offline_shutdown_timeout = -1; /* -offline-shutdown-timeout option */
178
179 struct timeval tp;
180
181 #ifdef AFS_PTHREAD_ENV
182 pthread_key_t viced_uclient_key;
183 #endif
184
185 #ifdef AFS_PTHREAD_ENV
186 pthread_key_t viced_uclient_key;
187 #endif
188
189 /*
190  * FileServer's name and IP address, both network byte order and
191  * host byte order.
192  */
193 #define ADDRSPERSITE 16         /* Same global is in rx/rx_user.c */
194
195 char FS_HostName[128] = "localhost";
196 afs_uint32 FS_HostAddr_NBO;
197 afs_uint32 FS_HostAddr_HBO;
198 afs_uint32 FS_HostAddrs[ADDRSPERSITE], FS_HostAddr_cnt = 0, FS_registered = 0;
199 /* All addresses in FS_HostAddrs are in NBO */
200 afsUUID FS_HostUUID;
201
202 #ifdef AFS_DEMAND_ATTACH_FS
203 /*
204  * demand attach fs
205  * fileserver mode support
206  *
207  * during fileserver shutdown, we have to track the graceful shutdown of
208  * certain background threads before we are allowed to dump state to
209  * disk
210  */
211
212 # if !defined(PTHREAD_RWLOCK_INITIALIZER) && defined(AFS_DARWIN80_ENV)
213 #  define PTHREAD_RWLOCK_INITIALIZER {0x2DA8B3B4, {0}}
214 # endif
215
216 # ifndef AFS_NT40_ENV
217 struct fs_state fs_state =
218     { FS_MODE_NORMAL,
219       0,
220       0,
221       0,
222       0,
223       { 1,1,1,1 },
224       PTHREAD_COND_INITIALIZER,
225       PTHREAD_RWLOCK_INITIALIZER
226     };
227 # else /* AFS_NT40_ENV */
228 struct fs_state fs_state;
229
230 static int fs_stateInit(void)
231 {
232     fs_state.mode = FS_MODE_NORMAL;
233     fs_state.FiveMinuteLWP_tranquil = 0;
234     fs_state.HostCheckLWP_tranquil = 0;
235     fs_state.FsyncCheckLWP_tranquil = 0;
236     fs_state.salvsync_fatal_error = 0;
237
238     fs_state.options.fs_state_save = 1;
239     fs_state.options.fs_state_restore = 1;
240     fs_state.options.fs_state_verify_before_save = 1;
241     fs_state.options.fs_state_verify_after_restore = 1;
242
243     CV_INIT(&fs_state.worker_done_cv, "worker done", CV_DEFAULT, 0);
244     osi_Assert(pthread_rwlock_init(&fs_state.state_lock, NULL) == 0);
245 }
246 # endif /* AFS_NT40_ENV */
247 #endif /* AFS_DEMAND_ATTACH_FS */
248
249 /*
250  * Home for the performance statistics.
251  */
252
253 /* DEBUG HACK */
254 static void *
255 CheckDescriptors(void *unused)
256 {
257 #ifndef AFS_NT40_ENV
258     struct afs_stat status;
259     int tsize = getdtablesize();
260     int i;
261     for (i = 0; i < tsize; i++) {
262         if (afs_fstat(i, &status) != -1) {
263             printf("%d: dev %x, inode %u, length %u, type/mode %x\n", i,
264                    (unsigned int) status.st_dev,
265                    (unsigned int) status.st_ino,
266                    (unsigned int) status.st_size,
267                    status.st_mode);
268         }
269     }
270     fflush(stdout);
271     ResetCheckDescriptors();
272 #endif
273     return 0;
274 }                               /*CheckDescriptors */
275
276
277 #ifdef AFS_PTHREAD_ENV
278 void
279 CheckSignal_Signal(int x)
280 {
281     CheckSignal(NULL);
282 }
283
284 void
285 ShutDown_Signal(int x)
286 {
287     ShutDown(NULL);
288 }
289
290 void
291 CheckDescriptors_Signal(int x)
292 {
293     CheckDescriptors(NULL);
294 }
295 #else /* AFS_PTHREAD_ENV */
296 void
297 CheckSignal_Signal(int x)
298 {
299     IOMGR_SoftSig(CheckSignal, 0);
300 }
301
302 void
303 ShutDown_Signal(int x)
304 {
305     IOMGR_SoftSig(ShutDown, 0);
306 }
307
308 void
309 CheckDescriptors_Signal(int x)
310 {
311     IOMGR_SoftSig(CheckDescriptors, 0);
312 }
313 #endif /* AFS_PTHREAD_ENV */
314
315 /* check whether caller is authorized to manage RX statistics */
316 int
317 fs_rxstat_userok(struct rx_call *call)
318 {
319     return afsconf_SuperUser(confDir, call, NULL);
320 }
321
322 static void
323 ResetCheckSignal(void)
324 {
325     int signo;
326
327 #if defined(AFS_HPUX_ENV)
328     signo = SIGPOLL;
329 #elif defined(AFS_NT40_ENV)
330     signo = SIGUSR2;
331 #else
332     signo = SIGXCPU;
333 #endif
334
335 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
336     softsig_signal(signo, CheckSignal_Signal);
337 #else
338     signal(signo, CheckSignal_Signal);
339 #endif
340 }
341
342 static void
343 ResetCheckDescriptors(void)
344 {
345 #ifndef AFS_NT40_ENV
346 # if defined(AFS_PTHREAD_ENV)
347     softsig_signal(SIGTERM, CheckDescriptors_Signal);
348 # else
349     (void)signal(SIGTERM, CheckDescriptors_Signal);
350 # endif
351 #endif
352 }
353
354 #ifndef AFS_NT40_ENV
355 int
356 viced_syscall(afs_uint32 a3, afs_uint32 a4, void *a5)
357 {
358     afs_uint32 rcode;
359 # ifndef AFS_LINUX20_ENV
360     void (*old) (int);
361
362     old = (void (*)(int))signal(SIGSYS, SIG_IGN);
363 # endif
364     rcode = syscall(AFS_SYSCALL, 28 /* AFSCALL_CALL */ , a3, a4, a5);
365 # ifndef AFS_LINUX20_ENV
366     signal(SIGSYS, old);
367 # endif
368
369     return rcode;
370 }
371 #endif
372
373 #if !defined(AFS_NT40_ENV)
374 # include "AFS_component_version_number.c"
375 #endif /* !AFS_NT40_ENV */
376
377 #define MAXADMINNAME 64
378 char adminName[MAXADMINNAME];
379
380 static void
381 CheckAdminName(void)
382 {
383     int fd = 0;
384     struct afs_stat status;
385
386     if ((afs_stat("/AdminName", &status)) ||    /* if file does not exist */
387         (status.st_size <= 0) ||        /* or it is too short */
388         (status.st_size >= (MAXADMINNAME)) ||   /* or it is too long */
389         !(fd = afs_open("/AdminName", O_RDONLY, 0))) {  /* or the open fails */
390         strcpy(adminName, "System:Administrators");     /* use the default name */
391     } else {
392         (void)read(fd, adminName, status.st_size);      /* use name from the file */
393     }
394     if (fd)
395         close(fd);              /* close fd if it was opened */
396
397 }                               /*CheckAdminName */
398
399
400 static void
401 setThreadId(char *s)
402 {
403 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
404     int threadId;
405
406     /* set our 'thread-id' so that the host hold table works */
407     threadId = rx_SetThreadNum();
408     afs_pthread_setname_self(s);
409     ViceLog(0, ("Set thread id 0x%x for '%s'\n", threadId, s));
410 #endif
411 }
412
413 /* This LWP does things roughly every 5 minutes */
414 static void *
415 FiveMinuteCheckLWP(void *unused)
416 {
417     static int msg = 0;
418     char tbuffer[32];
419
420     ViceLog(1, ("Starting five minute check process\n"));
421     setThreadId("FiveMinuteCheckLWP");
422
423 #ifdef AFS_DEMAND_ATTACH_FS
424     FS_STATE_WRLOCK;
425     while (fs_state.mode == FS_MODE_NORMAL) {
426         fs_state.FiveMinuteLWP_tranquil = 1;
427         FS_STATE_UNLOCK;
428 #else
429     while (1) {
430 #endif
431
432 #ifdef AFS_PTHREAD_ENV
433         sleep(fiveminutes);
434 #else /* AFS_PTHREAD_ENV */
435         IOMGR_Sleep(fiveminutes);
436 #endif /* AFS_PTHREAD_ENV */
437
438 #ifdef AFS_DEMAND_ATTACH_FS
439         FS_STATE_WRLOCK;
440         if (fs_state.mode != FS_MODE_NORMAL) {
441             break;
442         }
443         fs_state.FiveMinuteLWP_tranquil = 0;
444         FS_STATE_UNLOCK;
445 #endif
446
447         /* close the log so it can be removed */
448         ReOpenLog(AFSDIR_SERVER_FILELOG_FILEPATH);      /* don't trunc, just append */
449         ViceLog(2, ("Cleaning up timed out callbacks\n"));
450         if (CleanupTimedOutCallBacks())
451             ViceLog(5, ("Timed out callbacks deleted\n"));
452         ViceLog(2, ("Set disk usage statistics\n"));
453         VSetDiskUsage();
454         if (FS_registered == 1)
455             Do_VLRegisterRPC();
456         /* Force wakeup in case we missed something; pthreads does timedwait */
457 #ifndef AFS_PTHREAD_ENV
458         LWP_NoYieldSignal(fsync_wait);
459 #endif
460         if (printBanner && (++msg & 1)) {       /* Every 10 minutes */
461             time_t now = FT_ApproxTime();
462             struct tm tm;
463             strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
464                      localtime_r(&now, &tm));
465             ViceLog(2,
466                     ("File server is running at %s\n", tbuffer));
467         }
468 #ifdef AFS_DEMAND_ATTACH_FS
469         FS_STATE_WRLOCK;
470 #endif
471     }
472 #ifdef AFS_DEMAND_ATTACH_FS
473     fs_state.FiveMinuteLWP_tranquil = 1;
474     FS_LOCK;
475     CV_BROADCAST(&fs_state.worker_done_cv);
476     FS_UNLOCK;
477     FS_STATE_UNLOCK;
478 #endif
479     return NULL;
480 }                               /*FiveMinuteCheckLWP */
481
482
483 /* This LWP does host checks every 5 minutes:  it should not be used for
484  * other 5 minute activities because it may be delayed by timeouts when
485  * it probes the workstations
486  */
487
488 static void *
489 HostCheckLWP(void *unused)
490 {
491     ViceLog(1, ("Starting Host check process\n"));
492     setThreadId("HostCheckLWP");
493 #ifdef AFS_DEMAND_ATTACH_FS
494     FS_STATE_WRLOCK;
495     while (fs_state.mode == FS_MODE_NORMAL) {
496         fs_state.HostCheckLWP_tranquil = 1;
497         FS_STATE_UNLOCK;
498 #else
499     while(1) {
500 #endif
501
502 #ifdef AFS_PTHREAD_ENV
503         sleep(fiveminutes);
504 #else /* AFS_PTHREAD_ENV */
505         IOMGR_Sleep(fiveminutes);
506 #endif /* AFS_PTHREAD_ENV */
507
508 #ifdef AFS_DEMAND_ATTACH_FS
509         FS_STATE_WRLOCK;
510         if (fs_state.mode != FS_MODE_NORMAL) {
511             break;
512         }
513         fs_state.HostCheckLWP_tranquil = 0;
514         FS_STATE_UNLOCK;
515 #endif
516
517         ViceLog(2, ("Checking for dead venii & clients\n"));
518         h_CheckHosts();
519
520 #ifdef AFS_DEMAND_ATTACH_FS
521         FS_STATE_WRLOCK;
522 #endif
523     }
524 #ifdef AFS_DEMAND_ATTACH_FS
525     fs_state.HostCheckLWP_tranquil = 1;
526     FS_LOCK;
527     CV_BROADCAST(&fs_state.worker_done_cv);
528     FS_UNLOCK;
529     FS_STATE_UNLOCK;
530 #endif
531     return NULL;
532 }                               /*HostCheckLWP */
533
534 /* This LWP does fsync checks every 5 minutes:  it should not be used for
535  * other 5 minute activities because it may be delayed by timeouts when
536  * it probes the workstations
537  */
538 static void *
539 FsyncCheckLWP(void *unused)
540 {
541     afs_int32 code;
542 #ifdef AFS_PTHREAD_ENV
543     struct timespec fsync_next;
544 #endif
545     ViceLog(1, ("Starting fsync check process\n"));
546
547     setThreadId("FsyncCheckLWP");
548
549 #ifdef AFS_DEMAND_ATTACH_FS
550     FS_STATE_WRLOCK;
551     while (fs_state.mode == FS_MODE_NORMAL) {
552         fs_state.FsyncCheckLWP_tranquil = 1;
553         FS_STATE_UNLOCK;
554 #else
555     while(1) {
556 #endif
557         FSYNC_LOCK;
558 #ifdef AFS_PTHREAD_ENV
559         /* rounding is fine */
560         fsync_next.tv_nsec = 0;
561         fsync_next.tv_sec = time(0) + fiveminutes;
562
563         code = CV_TIMEDWAIT(&fsync_cond, &fsync_glock_mutex,
564                             &fsync_next);
565         if (code != 0 && code != ETIMEDOUT)
566             ViceLog(0, ("pthread_cond_timedwait returned %d\n", code));
567 #else /* AFS_PTHREAD_ENV */
568         if ((code = LWP_WaitProcess(fsync_wait)) != LWP_SUCCESS)
569             ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
570 #endif /* AFS_PTHREAD_ENV */
571         FSYNC_UNLOCK;
572
573 #ifdef AFS_DEMAND_ATTACH_FS
574         FS_STATE_WRLOCK;
575         if (fs_state.mode != FS_MODE_NORMAL) {
576             break;
577         }
578         fs_state.FsyncCheckLWP_tranquil = 0;
579         FS_STATE_UNLOCK;
580 #endif /* AFS_DEMAND_ATTACH_FS */
581
582         ViceLog(2, ("Checking for fsync events\n"));
583         do {
584             code = BreakLaterCallBacks();
585         } while (code != 0);
586 #ifdef AFS_DEMAND_ATTACH_FS
587         FS_STATE_WRLOCK;
588 #endif
589     }
590 #ifdef AFS_DEMAND_ATTACH_FS
591     fs_state.FsyncCheckLWP_tranquil = 1;
592     FS_LOCK;
593     CV_BROADCAST(&fs_state.worker_done_cv);
594     FS_UNLOCK;
595     FS_STATE_UNLOCK;
596 #endif /* AFS_DEMAND_ATTACH_FS */
597     return NULL;
598 }
599
600 /*------------------------------------------------------------------------
601  * PRIVATE ClearXStatValues
602  *
603  * Description:
604  *      Initialize all of the values collected via the xstat
605  *      interface.
606  *
607  * Arguments:
608  *      None.
609  *
610  * Returns:
611  *      Nothing.
612  *
613  * Environment:
614  *      Must be called during File Server initialization.
615  *
616  * Side Effects:
617  *      As advertised.
618  *------------------------------------------------------------------------*/
619
620 static void
621 ClearXStatValues(void)
622 {                               /*ClearXStatValues */
623
624     struct fs_stats_opTimingData *opTimeP;      /*Ptr to timing struct */
625     struct fs_stats_xferData *opXferP;  /*Ptr to xfer struct */
626     int i;                      /*Loop counter */
627
628     /*
629      * Zero all xstat-related structures.
630      */
631     memset((&afs_perfstats), 0, sizeof(struct afs_PerfStats));
632 #if FS_STATS_DETAILED
633     memset((&afs_FullPerfStats), 0,
634            sizeof(struct fs_stats_FullPerfStats));
635
636     /*
637      * That's not enough.  We have to set reasonable minima for
638      * time and xfer values in the detailed stats.
639      */
640     opTimeP = &(afs_FullPerfStats.det.rpcOpTimes[0]);
641     for (i = 0; i < FS_STATS_NUM_RPC_OPS; i++, opTimeP++)
642         opTimeP->minTime.tv_sec = 999999;
643
644     opXferP = &(afs_FullPerfStats.det.xferOpTimes[0]);
645     for (i = 0; i < FS_STATS_NUM_XFER_OPS; i++, opXferP++) {
646         opXferP->minTime.tv_sec = 999999;
647         opXferP->minBytes = 999999999;
648     }
649
650     /*
651      * There's more.  We have to set our unique system identifier, as
652      * declared in param.h.  If such a thing is not defined, we bitch
653      * and declare ourselves to be an unknown system type.
654      */
655 # ifdef SYS_NAME_ID
656     afs_perfstats.sysname_ID = SYS_NAME_ID;
657 # else
658 #  ifndef AFS_NT40_ENV
659     ViceLog(0, ("Sys name ID constant not defined in param.h!!\n"));
660     ViceLog(0, ("[Choosing ``undefined'' sys name ID.\n"));
661 #  endif
662     afs_perfstats.sysname_ID = SYS_NAME_ID_UNDEFINED;
663 # endif /* SYS_NAME_ID */
664 #endif
665
666 }                               /*ClearXStatValues */
667
668 int CopyOnWrite_calls = 0, CopyOnWrite_off0 = 0, CopyOnWrite_size0 = 0;
669 afs_fsize_t CopyOnWrite_maxsize = 0;
670
671 static void
672 PrintCounters(void)
673 {
674     int dirbuff, dircall, dirio;
675     struct timeval tpl;
676     int workstations, activeworkstations, delworkstations;
677     int processSize = 0;
678     char tbuffer[32];
679     struct tm tm;
680 #ifdef AFS_DEMAND_ATTACH_FS
681     int stats_flags = 0;
682 #endif
683
684     FT_GetTimeOfDay(&tpl, 0);
685     Statistics = 1;
686     strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
687              localtime_r(&StartTime, &tm));
688     ViceLog(0, ("Vice was last started at %s\n", tbuffer));
689
690 #ifdef AFS_DEMAND_ATTACH_FS
691     if (LogLevel >= 125) {
692         stats_flags = VOL_STATS_PER_CHAIN2;
693     } else if (LogLevel >= 25) {
694         stats_flags = VOL_STATS_PER_CHAIN;
695     }
696     VPrintExtendedCacheStats(stats_flags);
697 #endif
698     VPrintCacheStats();
699     VPrintDiskStats();
700     DStat(&dirbuff, &dircall, &dirio);
701     ViceLog(0,
702             ("With %d directory buffers; %d reads resulted in %d read I/Os\n",
703              dirbuff, dircall, dirio));
704     rx_PrintStats(stderr);
705     audit_PrintStats(stderr);
706     h_PrintStats();
707     PrintCallBackStats();
708 #ifdef AFS_NT40_ENV
709     processSize = -1;           /* TODO: */
710 #else
711     processSize = (int)((long)sbrk(0) >> 10);
712 #endif
713     ViceLog(0,
714             ("There are %d connections, process size %d\n",
715              CurrentConnections, processSize));
716     h_GetWorkStats(&workstations, &activeworkstations, &delworkstations,
717                    tpl.tv_sec - 15 * 60);
718     ViceLog(0,
719             ("There are %d workstations, %d are active (req in < 15 mins), %d marked \"down\"\n",
720              workstations, activeworkstations, delworkstations));
721     ViceLog(0, ("CopyOnWrite: calls %d off0 %d size0 %d maxsize 0x%llx\n",
722                 CopyOnWrite_calls, CopyOnWrite_off0, CopyOnWrite_size0, CopyOnWrite_maxsize));
723
724     Statistics = 0;
725
726 }                               /*PrintCounters */
727
728
729
730 static void *
731 CheckSignal(void *unused)
732 {
733     if (FS_registered > 0) {
734         /*
735          * We have proper ip addresses; tell the vlserver what we got; the following
736          * routine will do the proper reporting for us
737          */
738         Do_VLRegisterRPC();
739     }
740     h_DumpHosts();
741     h_PrintClients();
742     DumpCallBackState();
743     PrintCounters();
744     ResetCheckSignal();
745     return 0;
746 }                               /*CheckSignal */
747
748 static void *
749 ShutdownWatchdogLWP(void *unused)
750 {
751     afs_pthread_setname_self("ShutdownWatchdog");
752     sleep(panic_timeout);
753     ViceLogThenPanic(0, ("ShutdownWatchdogLWP: Failed to shutdown and panic "
754                          "within %d seconds; forcing panic\n",
755                          panic_timeout));
756     return NULL;
757 }
758
759 void
760 ShutDownAndCore(int dopanic)
761 {
762     time_t now = time(NULL);
763     struct tm tm;
764     char tbuffer[32];
765
766     if (dopanic) {
767 #ifdef AFS_PTHREAD_ENV
768         pthread_t watchdogPid;
769         pthread_attr_t tattr;
770         osi_Assert(pthread_attr_init(&tattr) == 0);
771         osi_Assert(pthread_create(&watchdogPid, &tattr, ShutdownWatchdogLWP, NULL) == 0);
772 #else
773         PROCESS watchdogPid;
774         osi_Assert(LWP_CreateProcess
775                (ShutdownWatchdogLWP, stack * 1024, LWP_MAX_PRIORITY - 2,
776                 NULL, "ShutdownWatchdog", &watchdogPid) == LWP_SUCCESS);
777 #endif
778     }
779
780     /* do not allows new reqests to be served from now on, all new requests
781      * are returned with an error code of RX_RESTARTING ( transient failure ) */
782     rx_SetRxTranquil();         /* dhruba */
783
784     VSetTranquil();
785
786 #ifdef AFS_DEMAND_ATTACH_FS
787     FS_STATE_WRLOCK;
788     if (fs_state.mode == FS_MODE_SHUTDOWN) {
789         /* it is possible for at least fs_stateSave() (called below) to call
790          * ShutDownAndCore if there's host list corruption; prevent
791          * deinitializing some stuff twice */
792         ViceLog(0, ("ShutDownAndCore called during shutdown? Skipping volume "
793                     "and host package shutdown\n"));
794         FS_STATE_UNLOCK;
795         goto done_vol_host;
796     }
797     fs_state.mode = FS_MODE_SHUTDOWN;
798     FS_STATE_UNLOCK;
799 #endif
800
801     strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
802              localtime_r(&now, &tm));
803     ViceLog(0, ("Shutting down file server at %s\n", tbuffer));
804     if (dopanic)
805         ViceLog(0, ("ABNORMAL SHUTDOWN, see core file.\n"));
806     DFlush();
807     if (!dopanic)
808         PrintCounters();
809
810     /* shut down volume package */
811     VShutdown();
812
813 #ifdef AFS_DEMAND_ATTACH_FS
814     if (fs_state.options.fs_state_save) {
815         /*
816          * demand attach fs
817          * save fileserver state to disk */
818
819         if (dopanic) {
820             ViceLog(0, ("Not saving fileserver state; abnormal shutdown\n"));
821
822         } else {
823             /* make sure background threads have finished all of their asynchronous
824              * work on host and callback structures */
825             FS_STATE_RDLOCK;
826             while (!fs_state.FiveMinuteLWP_tranquil ||
827                    !fs_state.HostCheckLWP_tranquil ||
828                    !fs_state.FsyncCheckLWP_tranquil) {
829                 FS_LOCK;
830                 FS_STATE_UNLOCK;
831                 ViceLog(0, ("waiting for background host/callback threads to quiesce before saving fileserver state...\n"));
832                 CV_WAIT(&fs_state.worker_done_cv, &fileproc_glock_mutex);
833                 FS_UNLOCK;
834                 FS_STATE_RDLOCK;
835             }
836             FS_STATE_UNLOCK;
837
838             /* ok. it should now be fairly safe. let's do the state dump */
839             fs_stateSave();
840         }
841     }
842  done_vol_host:
843
844 #endif /* AFS_DEMAND_ATTACH_FS */
845
846     if (debugFile) {
847         rx_PrintStats(debugFile);
848         fflush(debugFile);
849     }
850     now = time(0);
851     strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
852              localtime_r(&now, &tm));
853     if (dopanic) {
854       ViceLog(0, ("File server has terminated abnormally at %s\n", tbuffer));
855     } else {
856       ViceLog(0, ("File server has terminated normally at %s\n", tbuffer));
857     }
858
859     if (dopanic) /* XXX pass in file and line? */
860         osi_Panic("Panic requested\n");
861
862     exit(0);
863 }
864
865 void *
866 ShutDown(void *unused)
867 {                               /* backward compatibility */
868     ShutDownAndCore(DONTPANIC);
869     return 0;
870 }
871
872 static afs_int32
873 ParseRights(char *arights)
874 {
875     afs_int32 mode = 0;
876     int i, len;
877     char tc;
878
879     if (!arights || !strcmp(arights, "")) {
880         printf("Missing list of mode bits on -implicit option\n");
881         return -1;
882     }
883     if (!strcmp(arights, "none"))
884         mode = 0;
885     else if (!strcmp(arights, "read"))
886         mode = PRSFS_READ | PRSFS_LOOKUP;
887     else if (!strcmp(arights, "write"))
888         mode =
889             PRSFS_READ | PRSFS_LOOKUP | PRSFS_INSERT | PRSFS_DELETE |
890             PRSFS_WRITE | PRSFS_LOCK;
891     else if (!strcmp(arights, "all"))
892         mode =
893             PRSFS_READ | PRSFS_LOOKUP | PRSFS_INSERT | PRSFS_DELETE |
894             PRSFS_WRITE | PRSFS_LOCK | PRSFS_ADMINISTER;
895     else {
896         len = strlen(arights);
897         for (i = 0; i < len; i++) {
898             tc = *arights++;
899             if (tc == 'r')
900                 mode |= PRSFS_READ;
901             else if (tc == 'l')
902                 mode |= PRSFS_LOOKUP;
903             else if (tc == 'i')
904                 mode |= PRSFS_INSERT;
905             else if (tc == 'd')
906                 mode |= PRSFS_DELETE;
907             else if (tc == 'w')
908                 mode |= PRSFS_WRITE;
909             else if (tc == 'k')
910                 mode |= PRSFS_LOCK;
911             else if (tc == 'a')
912                 mode |= PRSFS_ADMINISTER;
913             else if (tc == 'A')
914                 mode |= PRSFS_USR0;
915             else if (tc == 'B')
916                 mode |= PRSFS_USR1;
917             else if (tc == 'C')
918                 mode |= PRSFS_USR2;
919             else if (tc == 'D')
920                 mode |= PRSFS_USR3;
921             else if (tc == 'E')
922                 mode |= PRSFS_USR4;
923             else if (tc == 'F')
924                 mode |= PRSFS_USR5;
925             else if (tc == 'G')
926                 mode |= PRSFS_USR6;
927             else if (tc == 'H')
928                 mode |= PRSFS_USR7;
929             else {
930                 printf("Illegal -implicit rights character '%c'.\n", tc);
931                 return -1;
932             }
933         }
934     }
935     return mode;
936 }
937
938 /*
939  * Limit MAX_FILESERVER_THREAD by the system limit on the number of
940  * pthreads (sysconf(_SC_THREAD_THREADS_MAX)), if applicable and
941  * available.
942  *
943  * AIX:         sysconf() limit is real
944  * HP-UX:       sysconf() limit is real
945  * IRIX:        sysconf() limit is apparently NOT real -- too small
946  * DUX:         sysconf() limit is apparently NOT real -- too big
947  * Linux:       sysconf() limit is apparently NOT real -- too big
948  * Solaris:     no sysconf() limit
949  */
950 static int
951 max_fileserver_thread(void)
952 {
953 #if defined(AFS_PTHREAD_ENV) && (defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV))
954     long ans;
955
956     ans = sysconf(_SC_THREAD_THREADS_MAX);
957     if (0 < ans && ans < MAX_FILESERVER_THREAD)
958         return (int)ans;
959 #endif /* defined(AFS_PTHREAD_ENV) */
960     return MAX_FILESERVER_THREAD;
961 }
962
963 /* from ihandle.c */
964 extern ih_init_params vol_io_params;
965
966 enum optionsList {
967     OPT_large,
968     OPT_small,
969     OPT_banner,
970     OPT_implicit,
971     OPT_lock,
972     OPT_readonly,
973     OPT_saneacls,
974     OPT_buffers,
975     OPT_callbacks,
976     OPT_vcsize,
977     OPT_lvnodes,
978     OPT_svnodes,
979     OPT_sendsize,
980     OPT_minspare,
981     OPT_spare,
982     OPT_pctspare,
983     OPT_hostcpsrefresh,
984     OPT_vattachthreads,
985     OPT_abortthreshold,
986     OPT_busyat,
987     OPT_nobusy,
988     OPT_offline_timeout,
989     OPT_offline_shutdown_timeout,
990     OPT_vhandle_setaside,
991     OPT_vhandle_max_cachesize,
992     OPT_vhandle_initial_cachesize,
993     OPT_fs_state_dont_save,
994     OPT_fs_state_dont_restore,
995     OPT_fs_state_verify,
996     OPT_vhashsize,
997     OPT_vlrudisable,
998     OPT_vlruthresh,
999     OPT_vlruinterval,
1000     OPT_vlrumax,
1001     OPT_unsafe_nosalvage,
1002     OPT_stack,
1003     OPT_cbwait,
1004     OPT_novbc,
1005     OPT_auditlog,
1006     OPT_auditiface,
1007     OPT_config,
1008     OPT_debug,
1009     OPT_logfile,
1010     OPT_mrafslogs,
1011     OPT_threads,
1012     OPT_syslog,
1013     OPT_peer,
1014     OPT_process,
1015     OPT_nojumbo,
1016     OPT_jumbo,
1017     OPT_rxbind,
1018     OPT_rxdbg,
1019     OPT_rxdbge,
1020     OPT_rxpck,
1021     OPT_rxmaxmtu,
1022     OPT_udpsize,
1023     OPT_dotted,
1024     OPT_realm
1025 };
1026
1027 static int
1028 ParseArgs(int argc, char *argv[])
1029 {
1030     int code;
1031     int optval;
1032     char *optstring;
1033     struct cmd_item *optlist;
1034     struct cmd_syndesc *opts;
1035
1036     int lwps_max;
1037     char *auditFileName = NULL;
1038
1039 #if defined(AFS_AIX32_ENV)
1040     extern int aixlow_water;
1041 #endif
1042
1043     opts = cmd_CreateSyntax(NULL, NULL, NULL, NULL);
1044
1045     /* fileserver options */
1046     cmd_AddParmAtOffset(opts, OPT_large, "-L", CMD_FLAG,
1047                         CMD_OPTIONAL, "defaults for a 'large' server");
1048     cmd_AddParmAtOffset(opts, OPT_small, "-S", CMD_FLAG,
1049                         CMD_OPTIONAL, "defaults for a 'small' server");
1050
1051     cmd_AddParmAtOffset(opts, OPT_banner, "-banner", CMD_FLAG,
1052                         CMD_OPTIONAL, "print regular banners to log");
1053     cmd_AddParmAtOffset(opts, OPT_implicit, "-implicit", CMD_SINGLE,
1054                         CMD_OPTIONAL, "implicit admin access bits");
1055
1056 #if defined(AFS_SGI_ENV)
1057     cmd_AddParmAtOffset(opts, OPT_lock, "-lock", CMD_FLAG,
1058                         CMD_OPTIONAL, "lock filserver binary in memory");
1059 #endif
1060     cmd_AddParmAtOffset(opts, OPT_readonly, "-readonly", CMD_FLAG,
1061                         CMD_OPTIONAL, "be a readonly fileserver");
1062     cmd_AddParmAtOffset(opts, OPT_saneacls, "-saneacls", CMD_FLAG,
1063                         CMD_OPTIONAL, "set the saneacls capability bit");
1064
1065     cmd_AddParmAtOffset(opts, OPT_buffers, "-b", CMD_SINGLE,
1066                         CMD_OPTIONAL, "buffers");
1067     cmd_AddParmAtOffset(opts, OPT_callbacks, "-cb", CMD_SINGLE,
1068                         CMD_OPTIONAL, "number of callbacks");
1069     cmd_AddParmAtOffset(opts, OPT_vcsize, "-vc", CMD_SINGLE,
1070                         CMD_OPTIONAL, "volume cachesize");
1071     cmd_AddParmAtOffset(opts, OPT_lvnodes, "-l", CMD_SINGLE,
1072                         CMD_OPTIONAL, "large vnodes");
1073     cmd_AddParmAtOffset(opts, OPT_svnodes, "-s", CMD_SINGLE,
1074                         CMD_OPTIONAL, "small vnodes");
1075     cmd_AddParmAtOffset(opts, OPT_sendsize, "-sendsize", CMD_SINGLE,
1076                         CMD_OPTIONAL, "size of send buffer in bytes");
1077
1078 #if defined(AFS_AIX32_ENV)
1079     cmd_AddParmAtOffset(opts, OPT_minspare, "-m", CMD_SINGLE,
1080                         CMD_OPTIONAL, "minimum percentage spare in partition");
1081 #endif
1082
1083     cmd_AddParmAtOffset(opts, OPT_spare, "-spare", CMD_SINGLE,
1084                         CMD_OPTIONAL, "kB overage on volume quota");
1085     cmd_AddParmAtOffset(opts, OPT_pctspare, "pctspare", CMD_SINGLE,
1086                         CMD_OPTIONAL, "percentage overage on volume quota");
1087
1088     cmd_AddParmAtOffset(opts, OPT_hostcpsrefresh, "-hr", CMD_SINGLE,
1089                         CMD_OPTIONAL, "hours between host CPS refreshes");
1090
1091 #if defined(AFS_PTHREAD_ENV)
1092     cmd_AddParmAtOffset(opts, OPT_vattachthreads, "-vattachpar", CMD_SINGLE,
1093                         CMD_OPTIONAL, "# of volume attachment threads");
1094 #endif
1095
1096     cmd_AddParmAtOffset(opts, OPT_abortthreshold, "-abortthreshold",
1097                         CMD_SINGLE, CMD_OPTIONAL,
1098                         "abort threshold");
1099     cmd_AddParmAtOffset(opts, OPT_busyat, "-busyat", CMD_SINGLE, CMD_OPTIONAL,
1100                         "# of queued entries after which server is busy");
1101     cmd_AddParmAtOffset(opts, OPT_nobusy, "-nobusy", CMD_FLAG, CMD_OPTIONAL,
1102                         "send VRESTARTING while restarting the server");
1103
1104     cmd_AddParmAtOffset(opts, OPT_offline_timeout, "-offline-timeout",
1105                         CMD_SINGLE, CMD_OPTIONAL,
1106                         "timeout for offlining volumes");
1107     cmd_AddParmAtOffset(opts, OPT_offline_shutdown_timeout,
1108                         "-offline-shutdown-timeout", CMD_SINGLE, CMD_OPTIONAL,
1109                         "timeout offlining volumes during shutdown");
1110
1111     cmd_AddParmAtOffset(opts, OPT_vhandle_setaside, "-vhandle-setaside",
1112                         CMD_SINGLE, CMD_OPTIONAL,
1113                         "# fds reserved for non-cache IO");
1114     cmd_AddParmAtOffset(opts, OPT_vhandle_max_cachesize, 
1115                         "-vhandle-max-cachesize", CMD_SINGLE, CMD_OPTIONAL,
1116                         "max open files");
1117     cmd_AddParmAtOffset(opts, OPT_vhandle_initial_cachesize,
1118                         "-vhandle-initial-cachesize", CMD_SINGLE,
1119                         CMD_OPTIONAL, "# fds reserved for cache IO");
1120
1121 #ifdef AFS_DEMAND_ATTACH_FS
1122     /* dafs options */
1123     cmd_AddParmAtOffset(opts, OPT_fs_state_dont_save,
1124                         "-fs-state-dont-save", CMD_FLAG, CMD_OPTIONAL,
1125                         "disable state save during shutdown");
1126     cmd_AddParmAtOffset(opts, OPT_fs_state_dont_restore,
1127                         "-fs-state-dont-restore", CMD_FLAG, CMD_OPTIONAL,
1128                         "disable state restore during startup");
1129     cmd_AddParmAtOffset(opts, OPT_fs_state_verify, "-fs-state-verify",
1130                         CMD_SINGLE, CMD_OPTIONAL, "none|save|restore|both");
1131     cmd_AddParmAtOffset(opts, OPT_vhashsize, "-vhashsize",
1132                         CMD_SINGLE, CMD_OPTIONAL,
1133                         "log(2) of # of volume hash buckets");
1134     cmd_AddParmAtOffset(opts, OPT_vlrudisable, "-vlrudisable",
1135                         CMD_FLAG, CMD_OPTIONAL, "disable VLRU functionality");
1136     cmd_AddParmAtOffset(opts, OPT_vlruthresh, "-vlruthresh",
1137                         CMD_FLAG, CMD_OPTIONAL,
1138                         "mins before unused vols become eligible for detach");
1139     cmd_AddParmAtOffset(opts, OPT_vlruinterval, "-vlruinterval",
1140                         CMD_FLAG, CMD_OPTIONAL, "secs between VLRU scans");
1141     cmd_AddParmAtOffset(opts, OPT_vlrumax, "-vlrumax", CMD_FLAG, CMD_OPTIONAL,
1142                         "max volumes to detach in one scan");
1143     cmd_AddParmAtOffset(opts, OPT_unsafe_nosalvage, "-unsafe-nosalvage",
1144                         CMD_FLAG, CMD_OPTIONAL,
1145                         "bybass safety checks on volume attach");
1146 #endif
1147
1148     /* unrecommend options - should perhaps be CMD_HIDE */
1149     cmd_AddParmAtOffset(opts, OPT_stack, "-k", CMD_SINGLE, CMD_OPTIONAL,
1150                         "stack size");
1151     cmd_AddParmAtOffset(opts, OPT_cbwait, "-w", CMD_SINGLE, CMD_OPTIONAL,
1152                         "callback wait interval");
1153     cmd_AddParmAtOffset(opts, OPT_novbc, "-novbc", CMD_SINGLE, CMD_FLAG,
1154                         "disable callback breaks on reattach");
1155
1156     /* general options */
1157     cmd_AddParmAtOffset(opts, OPT_auditlog, "-auditlog", CMD_SINGLE,
1158                         CMD_OPTIONAL, "location of audit log");
1159     cmd_AddParmAtOffset(opts, OPT_auditiface, "-audit-interface", CMD_SINGLE,
1160                         CMD_OPTIONAL, "interface to use for audit logging");
1161     cmd_AddParmAtOffset(opts, OPT_config, "-config", CMD_SINGLE, CMD_OPTIONAL,
1162                         "configuration location");
1163     cmd_AddParmAtOffset(opts, OPT_debug, "-d", CMD_SINGLE, CMD_OPTIONAL,
1164                         "debug level");
1165     cmd_AddParmAtOffset(opts, OPT_logfile, "-logfile", CMD_SINGLE,
1166                         CMD_OPTIONAL, "location of logfile");
1167     cmd_AddParmAtOffset(opts, OPT_mrafslogs, "-mrafslogs", CMD_FLAG,
1168                         CMD_OPTIONAL, "enable MRAFS style logging");
1169     cmd_AddParmAtOffset(opts, OPT_threads, "-p", CMD_SINGLE, CMD_OPTIONAL,
1170                         "number of threads");
1171 #if !defined(AFS_NT40_ENV)
1172     cmd_AddParmAtOffset(opts, OPT_syslog, "-syslog", CMD_SINGLE_OR_FLAG,
1173                         CMD_OPTIONAL, "log to syslog");
1174 #endif
1175
1176     /* rx options */
1177     cmd_AddParmAtOffset(opts, OPT_peer, "-enable_peer_stats", CMD_FLAG,
1178                         CMD_OPTIONAL, "enable RX transport statistics");
1179     cmd_AddParmAtOffset(opts, OPT_process, "-enable_process_stats", CMD_FLAG,
1180                         CMD_OPTIONAL, "enable RX RPC statistics");
1181     cmd_AddParmAtOffset(opts, OPT_nojumbo, "-nojumbo", CMD_FLAG,
1182                         CMD_OPTIONAL, "disable jumbograms");
1183     cmd_AddParmAtOffset(opts, OPT_jumbo, "-jumbo", CMD_FLAG, CMD_OPTIONAL,
1184                         "enable jumbograms");
1185     cmd_AddParmAtOffset(opts, OPT_rxbind, "-rxbind", CMD_FLAG, CMD_OPTIONAL,
1186                         "bind only to the primary interface");
1187     cmd_AddParmAtOffset(opts, OPT_rxdbg, "-rxdbg", CMD_FLAG, CMD_OPTIONAL,
1188                         "enable rx debugging");
1189     cmd_AddParmAtOffset(opts, OPT_rxdbge, "-rxdbge", CMD_FLAG, CMD_OPTIONAL,
1190                         "enable rx event debugging");
1191     cmd_AddParmAtOffset(opts, OPT_rxpck, "-rxpck", CMD_SINGLE, CMD_OPTIONAL,
1192                         "# of extra rx packets");
1193     cmd_AddParmAtOffset(opts, OPT_rxmaxmtu, "-rxmaxmtu", CMD_SINGLE,
1194                         CMD_OPTIONAL, "maximum MTU for RX");
1195     cmd_AddParmAtOffset(opts, OPT_udpsize, "-udpsize", CMD_SINGLE,
1196                         CMD_OPTIONAL, "size of socket buffer in bytes");
1197
1198     /* rxkad options */
1199     cmd_AddParmAtOffset(opts, OPT_dotted, "-allow-dotted-principals",
1200                         CMD_FLAG, CMD_OPTIONAL,
1201                         "permit Kerberos 5 principals with dots");
1202     cmd_AddParmAtOffset(opts, OPT_realm, "-realm",
1203                         CMD_LIST, CMD_OPTIONAL, "local realm");
1204
1205     code = cmd_Parse(argc, argv, &opts);
1206     if (code)
1207         return -1;
1208
1209     if (cmd_OptionPresent(opts, OPT_large)
1210         && cmd_OptionPresent(opts, OPT_small)) {
1211         printf("Only one of -L or -S must be specified\n");
1212         return -1;
1213     }
1214
1215     if (cmd_OptionPresent(opts, OPT_spare)
1216         && cmd_OptionPresent(opts, OPT_pctspare)) {
1217         printf("Both -spare and -pctspare specified, exiting.\n");
1218         return -1;
1219     }
1220
1221     if (cmd_OptionPresent(opts, OPT_large)) {
1222         rxpackets = 200;
1223         nSmallVns = 600;
1224         large = 600;
1225         numberofcbs = 64000;
1226         lwps = 128;
1227         buffs = 120;
1228         volcache = 600;
1229     }
1230
1231     if (cmd_OptionPresent(opts, OPT_small)) {
1232         rxpackets = 100;
1233         nSmallVns = 200;
1234         large = 200;
1235         numberofcbs = 20000;
1236         lwps = 6;
1237         buffs = 70;
1238         volcache = 200;
1239     }
1240
1241     cmd_OptionAsFlag(opts, OPT_banner, &printBanner);
1242
1243     if (cmd_OptionAsString(opts, OPT_implicit, &optstring) == 0) {
1244         implicitAdminRights = ParseRights(optstring);
1245         free(optstring);
1246         optstring = NULL;
1247         if (implicitAdminRights < 0)
1248             return implicitAdminRights;
1249     }
1250
1251 #if defined(AFS_SGI_ENV)
1252     cmd_OptionAsFlag(opts, OPT_lock, &SawLock);
1253 #endif
1254     cmd_OptionAsFlag(opts, OPT_readonly, &readonlyServer);
1255     cmd_OptionAsFlag(opts, OPT_saneacls, &saneacls);
1256     cmd_OptionAsInt(opts, OPT_buffers, &buffs);
1257
1258     if (cmd_OptionAsInt(opts, OPT_callbacks, &numberofcbs) == 0) {
1259         printf("number of cbs %d invalid; "
1260                "must be between 10000 and 2147483647\n", numberofcbs);
1261         return -1;
1262     }
1263
1264     cmd_OptionAsInt(opts, OPT_vcsize, &volcache);
1265     cmd_OptionAsInt(opts, OPT_lvnodes, &large);
1266     cmd_OptionAsInt(opts, OPT_svnodes, &nSmallVns);
1267     if (cmd_OptionAsInt(opts, OPT_sendsize, &optval) == 0) {
1268         if (optval < 16384) {
1269             printf("Warning:sendsize %d is less than minimum %d; ignoring\n",
1270                    optval, 16384);
1271         } else
1272             sendBufSize = optval;
1273     }
1274
1275 #if defined(AFS_AIX32_ENV)
1276     if (cmd_OptionAsInt(opts, OPT_minspare, &aixlow_water) == 0) {
1277         if ((aixlow_water < 0) || (aixlow_water > 30)) {
1278             printf("space reserved %d%% invalid; must be between 0-30%\n",
1279                    aixlow_water);
1280             return -1;
1281         }
1282     }
1283 #endif
1284
1285     cmd_OptionAsInt(opts, OPT_spare, &BlocksSpare);
1286     if (cmd_OptionAsInt(opts, OPT_pctspare, &PctSpare) == 0) {
1287         BlocksSpare = 0;
1288     }
1289
1290     if (cmd_OptionAsInt(opts, OPT_hostcpsrefresh, &optval) == 0) {
1291         if ((optval < 1) || (optval > 36)) {
1292             printf("host acl refresh interval of %d hours is invalid; "
1293                    "hours must be between 1 and 36\n\n", optval);
1294             return -1;
1295         }
1296         hostaclRefresh = optval * 60 * 60;
1297     }
1298
1299 #ifdef AFS_PTHREAD_ENV
1300     cmd_OptionAsInt(opts, OPT_vattachthreads, &vol_attach_threads);
1301 #endif /* AFS_PTHREAD_ENV */
1302
1303     cmd_OptionAsInt(opts, OPT_abortthreshold, &abort_threshold);
1304
1305     /* busyat is at the end, as rxpackets has to be set before we can use it */
1306     if (cmd_OptionPresent(opts, OPT_nobusy))
1307         busyonrst = 0;
1308
1309     if (cmd_OptionAsInt(opts, OPT_offline_timeout, &offline_timeout) == 0) {
1310 #ifndef AFS_PTHREAD_ENV
1311         if (offline_timeout != -1) {
1312             printf("The only valid -offline-timeout value for the LWP "
1313                    "fileserver is -1\n");
1314             return -1;
1315         }
1316 #endif /* AFS_PTHREAD_ENV */
1317         if (offline_timeout < -1) {
1318             printf("Invalid -offline-timeout value %d; the only valid "
1319                    "negative value is -1\n", offline_timeout);
1320             return -1;
1321         }
1322     }
1323
1324     if (cmd_OptionAsInt(opts, OPT_offline_shutdown_timeout,
1325                         &offline_shutdown_timeout) == 0) {
1326 #ifndef AFS_PTHREAD_ENV
1327         if (offline_shutdown_timeout != -1) {
1328             printf("The only valid -offline-shutdown-timeout value for the "
1329                    "LWP fileserver is -1\n");
1330             return -1;
1331         }
1332 #endif /* AFS_PTHREAD_ENV */
1333         if (offline_shutdown_timeout < -1) {
1334             printf("Invalid -offline-timeout value %d; the only valid "
1335                    "negative value is -1\n", offline_shutdown_timeout);
1336             return -1;
1337         }
1338     }
1339
1340     cmd_OptionAsUint(opts, OPT_vhandle_setaside,
1341                     &vol_io_params.fd_handle_setaside);
1342     cmd_OptionAsUint(opts, OPT_vhandle_max_cachesize,
1343                     &vol_io_params.fd_max_cachesize);
1344     cmd_OptionAsUint(opts, OPT_vhandle_initial_cachesize,
1345                     &vol_io_params.fd_initial_cachesize);
1346
1347 #ifdef AFS_DEMAND_ATTACH_FS
1348     if (cmd_OptionPresent(opts, OPT_fs_state_dont_save))
1349         fs_state.options.fs_state_save = 0;
1350     if (cmd_OptionPresent(opts, OPT_fs_state_dont_restore))
1351         fs_state.options.fs_state_restore = 0;
1352     if (cmd_OptionAsString(opts, OPT_fs_state_verify, &optstring) == 0) {
1353         if (strcmp(optstring, "none") == 0) {
1354             fs_state.options.fs_state_verify_before_save = 0;
1355             fs_state.options.fs_state_verify_after_restore = 0;
1356         } else if (strcmp(optstring, "save") == 0) {
1357             fs_state.options.fs_state_verify_after_restore = 0;
1358         } else if (strcmp(optstring, "restore") == 0) {
1359             fs_state.options.fs_state_verify_before_save = 0;
1360         } else if (strcmp(optstring, "both") == 0) {
1361             /* default */
1362         } else {
1363             fprintf(stderr, "invalid argument for -fs-state-verify\n");
1364             return -1;
1365         }
1366     }
1367     if (cmd_OptionAsInt(opts, OPT_vhashsize, &optval) == 0) {
1368         if (VSetVolHashSize(optval)) {
1369             fprintf(stderr, "specified -vhashsize (%d) is invalid or out "
1370                             "of range\n", optval);
1371             return -1;
1372         }
1373     }
1374     if (cmd_OptionPresent(opts, OPT_vlrudisable))
1375         VLRU_SetOptions(VLRU_SET_ENABLED, 0);
1376     if (cmd_OptionAsInt(opts, OPT_vlruthresh, &optval) == 0)
1377         VLRU_SetOptions(VLRU_SET_THRESH, 60*optval);
1378     if (cmd_OptionAsInt(opts, OPT_vlruinterval, &optval) == 0)
1379         VLRU_SetOptions(VLRU_SET_INTERVAL, optval);
1380     if (cmd_OptionAsInt(opts, OPT_vlrumax, &optval) == 0)
1381         VLRU_SetOptions(VLRU_SET_MAX, optval);
1382     cmd_OptionAsFlag(opts, OPT_unsafe_nosalvage, &unsafe_attach);
1383 #endif /* AFS_DEMAND_ATTACH_FS */
1384
1385     cmd_OptionAsInt(opts, OPT_stack, &stack);
1386     cmd_OptionAsInt(opts, OPT_cbwait, &fiveminutes);
1387     cmd_OptionAsFlag(opts, OPT_novbc, &novbc);
1388
1389     /* general server options */
1390     cmd_OptionAsString(opts, OPT_auditlog, &auditFileName);
1391
1392     if (cmd_OptionAsString(opts, OPT_auditiface, &optstring) == 0) {
1393         if (osi_audit_interface(optstring)) {
1394             printf("Invalid audit interface '%s'\n", optstring);
1395             return -1;
1396         }
1397         free(optstring);
1398         optstring = NULL;
1399     }
1400
1401     /* XXX - cmd_OptionAsString(opts, OPT_config, &configDir); */
1402     cmd_OptionAsInt(opts, OPT_debug, &LogLevel);
1403     /* XXX - cmd_OptionAsString(opts, OPT_logfile, &logFile); */
1404     cmd_OptionAsFlag(opts, OPT_mrafslogs, &mrafsStyleLogs);
1405
1406     if (cmd_OptionAsInt(opts, OPT_threads, &lwps) == 0) {
1407         lwps_max = max_fileserver_thread() - FILESERVER_HELPER_THREADS;
1408         if (lwps > lwps_max)
1409             lwps = lwps_max;
1410         else if (lwps <6)
1411             lwps = 6;
1412     }
1413
1414 #ifndef AFS_NT40_ENV
1415     if (cmd_OptionPresent(opts, OPT_syslog)) {
1416         serverLogSyslog = 1;
1417         cmd_OptionAsInt(opts, OPT_syslog, &serverLogSyslogFacility);
1418     }
1419 #endif
1420
1421     if (cmd_OptionPresent(opts, OPT_peer))
1422         rx_enablePeerRPCStats();
1423     if (cmd_OptionPresent(opts, OPT_process))
1424         rx_enableProcessRPCStats();
1425     if (cmd_OptionPresent(opts, OPT_nojumbo))
1426         rxJumbograms = 0;
1427     if (cmd_OptionPresent(opts, OPT_jumbo))
1428         rxJumbograms = 1;
1429     cmd_OptionAsFlag(opts, OPT_rxbind, &rxBind);
1430     cmd_OptionAsFlag(opts, OPT_rxdbg, &rxlog);
1431     cmd_OptionAsFlag(opts, OPT_rxdbge, &eventlog);
1432     cmd_OptionAsInt(opts, OPT_rxpck, &rxpackets);
1433
1434     if (cmd_OptionAsInt(opts, OPT_rxmaxmtu, &rxMaxMTU) == 0) {
1435         if ((rxMaxMTU < RX_MIN_PACKET_SIZE) ||
1436             (rxMaxMTU > RX_MAX_PACKET_DATA_SIZE)) {
1437             printf("rxMaxMTU %d invalid; must be between %d-%" AFS_SIZET_FMT "\n",
1438                    rxMaxMTU, RX_MIN_PACKET_SIZE,
1439                    RX_MAX_PACKET_DATA_SIZE);
1440             return(-1);
1441         }
1442     }
1443
1444     if (cmd_OptionAsInt(opts, OPT_udpsize, &optval) == 0) {
1445         if (optval < rx_GetMinUdpBufSize()) {
1446             printf("Warning:udpsize %d is less than minimum %d; ignoring\n",
1447                    optval, rx_GetMinUdpBufSize());
1448         } else
1449             udpBufSize = optval;
1450     }
1451
1452     /* rxkad options */
1453     cmd_OptionAsFlag(opts, OPT_dotted, &rxkadDisableDotCheck);
1454     if (cmd_OptionAsList(opts, OPT_realm, &optlist) == 0) {
1455         extern char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
1456         extern int num_lrealms;
1457
1458         for (; optlist != NULL; optlist=optlist->next) {
1459             if (strlen(optlist->data) >= AFS_REALM_SZ) {
1460                 printf("-realm argument must contain fewer than %d "
1461                        "characters.\n", AFS_REALM_SZ);
1462                 return -1;
1463             }
1464
1465             if (num_lrealms == -1)
1466                 num_lrealms = 0;
1467             if (num_lrealms >= AFS_NUM_LREALMS) {
1468                 printf("a maximum of %d -realm arguments can be "
1469                        "specified.\n", AFS_NUM_LREALMS);
1470                 return -1;
1471             }
1472
1473             strncpy(local_realms[num_lrealms++], optlist->data, AFS_REALM_SZ);
1474             optlist = optlist->next;
1475         }
1476     }
1477
1478     /* anything setting rxpackets must come before this */
1479     if (cmd_OptionAsInt(opts, OPT_busyat, &optval) == 0) {
1480         if (optval < 10) {
1481             printf("Busy threshold %d is too low, will use default.\n",
1482                    busy_threshold);
1483             busy_threshold = 3 * rxpackets / 2;
1484         } else {
1485             busy_threshold = optval;
1486         }
1487     } else {
1488         busy_threshold = 3 * rxpackets / 2;
1489     }
1490
1491     if (auditFileName)
1492         osi_audit_file(auditFileName);
1493
1494     return (0);
1495 }                               /*ParseArgs */
1496
1497 /* Once upon a time, in a galaxy far far away, IBM AFS supported the use of
1498  * a file /vice/file/parms, the contents of which would override any command
1499  * line parameters. We no longer support the use of such a file, but we warn
1500  * if we encounter its presence from an older release
1501  */
1502 static void
1503 CheckParms(void)
1504 {
1505     struct afs_stat sbuf;
1506
1507     if (afs_stat("/vice/file/parms", &sbuf) == 0) {
1508         ViceLog(0, ("Using /vice/file/parms to override command line "
1509                     "options is no longer supported"));
1510     }
1511 }
1512
1513 /* Miscellaneous routines */
1514 void
1515 Die(const char *msg)
1516 {
1517
1518     ViceLogThenPanic(0, ("%s\n", msg));
1519 }                               /*Die */
1520
1521
1522 afs_int32
1523 InitPR(void)
1524 {
1525     int code;
1526
1527     /*
1528      * If this fails, it's because something major is wrong, and is not
1529      * likely to be time dependent.
1530      */
1531     code = pr_Initialize(2, AFSDIR_SERVER_ETC_DIRPATH, 0);
1532     if (code != 0) {
1533         ViceLog(0,
1534                 ("Couldn't initialize protection library; code=%d.\n", code));
1535         return code;
1536     }
1537
1538 #ifdef AFS_PTHREAD_ENV
1539     osi_Assert(pthread_key_create(&viced_uclient_key, NULL) == 0);
1540 #endif
1541
1542     SystemId = SYSADMINID;
1543     SystemAnyUser = ANYUSERID;
1544     SystemAnyUserCPS.prlist_len = 0;
1545     SystemAnyUserCPS.prlist_val = NULL;
1546     AnonCPS.prlist_len = 0;
1547     AnonCPS.prlist_val = NULL;
1548     while (1) {
1549         code = pr_GetCPS(SystemAnyUser, &SystemAnyUserCPS);
1550         if (code != 0) {
1551             ViceLog(0,
1552                     ("Couldn't get CPS for AnyUser, will try again in 30 seconds; code=%d.\n",
1553                      code));
1554             goto sleep;
1555         }
1556         code = pr_GetCPS(ANONYMOUSID, &AnonCPS);
1557         if (code != 0) {
1558             ViceLog(0,
1559                     ("Couldn't get Anonymous CPS, exiting; code=%d.\n",
1560                      code));
1561             return -1;
1562         }
1563         AnonymousID = ANONYMOUSID;
1564         return 0;
1565       sleep:
1566 #ifdef AFS_PTHREAD_ENV
1567         sleep(30);
1568 #else /* AFS_PTHREAD_ENV */
1569         IOMGR_Sleep(30);
1570 #endif /* AFS_PTHREAD_ENV */
1571     }
1572 }                               /*InitPR */
1573
1574 struct rx_connection *serverconns[MAXSERVERS];
1575 struct ubik_client *cstruct;
1576
1577 afs_int32
1578 vl_Initialize(const char *confDir)
1579 {
1580     afs_int32 code, i;
1581     afs_int32 scIndex = RX_SECIDX_NULL;
1582     struct afsconf_dir *tdir;
1583     struct rx_securityClass *sc;
1584     struct afsconf_cell info;
1585
1586     tdir = afsconf_Open(confDir);
1587     if (!tdir) {
1588         ViceLog(0,
1589                 ("Could not open configuration directory (%s).\n", confDir));
1590         exit(1);
1591     }
1592     code = afsconf_ClientAuth(tdir, &sc, &scIndex);
1593     if (code) {
1594         ViceLog(0, ("Could not get security object for localAuth\n"));
1595         exit(1);
1596     }
1597     code = afsconf_GetCellInfo(tdir, NULL, AFSCONF_VLDBSERVICE, &info);
1598     if (info.numServers > MAXSERVERS) {
1599         ViceLog(0,
1600                 ("vl_Initialize: info.numServers=%d (> MAXSERVERS=%d)\n",
1601                  info.numServers, MAXSERVERS));
1602         exit(1);
1603     }
1604     for (i = 0; i < info.numServers; i++)
1605         serverconns[i] =
1606             rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
1607                              info.hostAddr[i].sin_port, USER_SERVICE_ID, sc,
1608                              scIndex);
1609     code = ubik_ClientInit(serverconns, &cstruct);
1610     afsconf_Close(tdir);
1611     if (code) {
1612         ViceLog(0, ("vl_Initialize: ubik client init failed.\n"));
1613         return code;
1614     }
1615     return 0;
1616 }
1617
1618 #define SYSIDMAGIC      0x88aabbcc
1619 #define SYSIDVERSION    1
1620
1621 afs_int32
1622 ReadSysIdFile(void)
1623 {
1624     afs_int32 fd, nentries, i;
1625     struct versionStamp vsn;
1626     struct afs_stat status;
1627     afsUUID uuid;
1628
1629     if ((afs_stat(AFSDIR_SERVER_SYSID_FILEPATH, &status))
1630         || (status.st_size <= 0)) {
1631         ViceLog(0, ("%s: doesn't exist\n", AFSDIR_SERVER_SYSID_FILEPATH));
1632         return ENOENT;
1633     }
1634     if (!(fd = afs_open(AFSDIR_SERVER_SYSID_FILEPATH, O_RDONLY, 0))) {
1635         ViceLog(0,
1636                 ("%s: can't open (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH,
1637                  errno));
1638         return EIO;
1639     }
1640     if (read(fd, (char *)&vsn, sizeof(vsn)) != sizeof(vsn)) {
1641         ViceLog(0,
1642                 ("%s: Read failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH,
1643                  errno));
1644         return EIO;
1645     }
1646     if (vsn.magic != SYSIDMAGIC) {
1647         ViceLog(0,
1648                 ("%s: wrong magic %x (we support %x)\n",
1649                  AFSDIR_SERVER_SYSID_FILEPATH, vsn.magic, SYSIDMAGIC));
1650         return EIO;
1651     }
1652     if (vsn.version != SYSIDVERSION) {
1653         ViceLog(0,
1654                 ("%s: wrong version %d (we support %d)\n",
1655                  AFSDIR_SERVER_SYSID_FILEPATH, vsn.version, SYSIDVERSION));
1656         return EIO;
1657     }
1658     if (read(fd, (char *)&uuid, sizeof(struct afsUUID))
1659             != sizeof(struct afsUUID)) {
1660         ViceLog(0,
1661                 ("%s: read of uuid failed (%d)\n",
1662                  AFSDIR_SERVER_SYSID_FILEPATH, errno));
1663         return EIO;
1664     }
1665     afs_ntohuuid(&uuid);
1666     FS_HostUUID = uuid;
1667     if (read(fd, (char *)&nentries, sizeof(afs_int32)) != sizeof(afs_int32)) {
1668         ViceLog(0,
1669                 ("%s: Read of entries failed (%d)\n",
1670                  AFSDIR_SERVER_SYSID_FILEPATH, errno));
1671         return EIO;
1672     }
1673     if (nentries <= 0 || nentries > ADDRSPERSITE) {
1674         ViceLog(0,
1675                 ("%s: invalid num of interfaces: %d\n",
1676                  AFSDIR_SERVER_SYSID_FILEPATH, nentries));
1677         return EIO;
1678     }
1679     if (FS_HostAddr_cnt == 0) {
1680         FS_HostAddr_cnt = nentries;
1681         for (i = 0; i < nentries; i++) {
1682             if (read(fd, (char *)&FS_HostAddrs[i], sizeof(afs_int32)) !=
1683                 sizeof(afs_int32)) {
1684                 ViceLog(0,
1685                         ("%s: Read of addresses failed (%d)\n",
1686                          AFSDIR_SERVER_SYSID_FILEPATH, errno));
1687                 FS_HostAddr_cnt = 0;    /* reset it */
1688                 return EIO;
1689             }
1690         }
1691     } else {
1692         ViceLog(1,
1693                 ("%s: address list ignored (NetInfo/NetRestrict override)\n",
1694                  AFSDIR_SERVER_SYSID_FILEPATH));
1695     }
1696     close(fd);
1697     return 0;
1698 }
1699
1700 afs_int32
1701 WriteSysIdFile(void)
1702 {
1703     afs_int32 fd, i;
1704     struct versionStamp vsn;
1705     struct afs_stat status;
1706     afsUUID uuid;
1707
1708     if (!afs_stat(AFSDIR_SERVER_SYSID_FILEPATH, &status)) {
1709         /*
1710          * File exists; keep the old one around
1711          */
1712         renamefile(AFSDIR_SERVER_SYSID_FILEPATH,
1713                    AFSDIR_SERVER_OLDSYSID_FILEPATH);
1714     }
1715     fd = afs_open(AFSDIR_SERVER_SYSID_FILEPATH, O_WRONLY | O_TRUNC | O_CREAT,
1716                   0666);
1717     if (fd < 1) {
1718         ViceLog(0,
1719                 ("%s: can't create (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH,
1720                  errno));
1721         return EIO;
1722     }
1723     vsn.magic = SYSIDMAGIC;
1724     vsn.version = 1;
1725     if ((i = write(fd, (char *)&vsn, sizeof(vsn))) != sizeof(vsn)) {
1726         ViceLog(0,
1727                 ("%s: write failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH,
1728                  errno));
1729         return EIO;
1730     }
1731     uuid = FS_HostUUID;
1732     afs_htonuuid(&uuid);
1733     if ((i =
1734          write(fd, (char *)&uuid,
1735                sizeof(struct afsUUID))) != sizeof(struct afsUUID)) {
1736         ViceLog(0,
1737                 ("%s: write of uuid failed (%d)\n",
1738                  AFSDIR_SERVER_SYSID_FILEPATH, errno));
1739         return EIO;
1740     }
1741     if ((i =
1742          write(fd, (char *)&FS_HostAddr_cnt,
1743                sizeof(afs_int32))) != sizeof(afs_int32)) {
1744         ViceLog(0,
1745                 ("%s: write of # of entries failed (%d)\n",
1746                  AFSDIR_SERVER_SYSID_FILEPATH, errno));
1747         return EIO;
1748     }
1749     for (i = 0; i < FS_HostAddr_cnt; i++) {
1750         if (write(fd, (char *)&FS_HostAddrs[i], sizeof(afs_int32)) !=
1751             sizeof(afs_int32)) {
1752             ViceLog(0,
1753                     ("%s: write of addresses failed (%d)\n",
1754                      AFSDIR_SERVER_SYSID_FILEPATH, errno));
1755             return EIO;
1756         }
1757     }
1758     close(fd);
1759     return 0;
1760 }
1761
1762 /*
1763  * defect 10966
1764  * This routine sets up the buffers for the VL_RegisterAddrs RPC. All addresses
1765  * in FS_HostAddrs[] are in NBO, while the RPC treats them as a "blob" of data
1766  * and so we need to convert each of them into HBO which is what the extra
1767  * array called FS_HostAddrs_HBO is used here.
1768  */
1769 static afs_int32
1770 Do_VLRegisterRPC(void)
1771 {
1772     int code;
1773     bulkaddrs addrs;
1774     afs_uint32 FS_HostAddrs_HBO[ADDRSPERSITE];
1775     int i = 0;
1776
1777     for (i = 0; i < FS_HostAddr_cnt; i++)
1778         FS_HostAddrs_HBO[i] = ntohl(FS_HostAddrs[i]);
1779     addrs.bulkaddrs_len = FS_HostAddr_cnt;
1780     addrs.bulkaddrs_val = (afs_uint32 *) FS_HostAddrs_HBO;
1781     code = ubik_VL_RegisterAddrs(cstruct, 0, &FS_HostUUID, 0, &addrs);
1782     if (code) {
1783         if (code == VL_MULTIPADDR) {
1784             ViceLog(0,
1785                     ("VL_RegisterAddrs rpc failed; The IP address exists on a different server; repair it\n"));
1786             ViceLog(0,
1787                     ("VL_RegisterAddrs rpc failed; See VLLog for details\n"));
1788             return code;
1789         } else if (code == RXGEN_OPCODE) {
1790             ViceLog(0,
1791                     ("vlserver doesn't support VL_RegisterAddrs rpc; ignored\n"));
1792             FS_registered = 2;  /* So we don't have to retry in the gc daemon */
1793         } else {
1794             ViceLog(0,
1795                     ("VL_RegisterAddrs rpc failed; will retry periodically (code=%d, err=%d)\n",
1796                      code, errno));
1797             FS_registered = 1;  /* Retry in the gc daemon */
1798         }
1799     } else {
1800         FS_registered = 2;      /* So we don't have to retry in the gc daemon */
1801         WriteSysIdFile();
1802     }
1803
1804     return 0;
1805 }
1806
1807 afs_int32
1808 SetupVL(void)
1809 {
1810     afs_int32 code;
1811
1812     if (AFSDIR_SERVER_NETRESTRICT_FILEPATH || AFSDIR_SERVER_NETINFO_FILEPATH) {
1813         /*
1814          * Find addresses we are supposed to register as per the netrestrict
1815          * and netinfo files (/usr/afs/local/NetInfo and
1816          * /usr/afs/local/NetRestict)
1817          */
1818         char reason[1024];
1819         afs_int32 code = parseNetFiles(FS_HostAddrs, NULL, NULL,
1820                                        ADDRSPERSITE, reason,
1821                                        AFSDIR_SERVER_NETINFO_FILEPATH,
1822                                        AFSDIR_SERVER_NETRESTRICT_FILEPATH);
1823         if (code < 0) {
1824             ViceLog(0, ("Can't register any valid addresses: %s\n", reason));
1825             exit(1);
1826         }
1827         FS_HostAddr_cnt = (afs_uint32) code;
1828     } else
1829     {
1830         FS_HostAddr_cnt = rx_getAllAddr(FS_HostAddrs, ADDRSPERSITE);
1831     }
1832
1833     if (FS_HostAddr_cnt == 1 && rxBind == 1)
1834         code = FS_HostAddrs[0];
1835     else
1836         code = htonl(INADDR_ANY);
1837     return code;
1838 }
1839
1840 afs_int32
1841 InitVL(void)
1842 {
1843     afs_int32 code;
1844
1845     /*
1846      * If this fails, it's because something major is wrong, and is not
1847      * likely to be time dependent.
1848      */
1849     code = vl_Initialize(AFSDIR_SERVER_ETC_DIRPATH);
1850     if (code != 0) {
1851         ViceLog(0,
1852                 ("Couldn't initialize protection library; code=%d.\n", code));
1853         return code;
1854     }
1855
1856     /* Read or create the sysid file and register the fileserver's
1857      * IP addresses with the vlserver.
1858      */
1859     code = ReadSysIdFile();
1860     if (code) {
1861         /* Need to create the file */
1862         ViceLog(0, ("Creating new SysID file\n"));
1863         if ((code = afs_uuid_create(&FS_HostUUID))) {
1864             ViceLog(0, ("Failed to create new uuid: %d\n", code));
1865             exit(1);
1866         }
1867     }
1868     /* A good sysid file exists; inform the vlserver. If any conflicts,
1869      * we always use the latest interface available as the real truth.
1870      */
1871
1872     code = Do_VLRegisterRPC();
1873     return code;
1874 }
1875
1876 int
1877 main(int argc, char *argv[])
1878 {
1879     afs_int32 code;
1880     char tbuffer[32];
1881     struct rx_securityClass **securityClasses;
1882     afs_int32 numClasses;
1883     struct rx_service *tservice;
1884 #ifdef AFS_PTHREAD_ENV
1885     pthread_t serverPid;
1886     pthread_attr_t tattr;
1887 #else /* AFS_PTHREAD_ENV */
1888     PROCESS parentPid, serverPid;
1889 #endif /* AFS_PTHREAD_ENV */
1890     struct hostent *he;
1891     int minVnodesRequired;      /* min size of vnode cache */
1892 #ifndef AFS_NT40_ENV
1893     struct rlimit rlim;         /* max number of open file descriptors */
1894 #endif
1895     int curLimit;
1896     time_t t;
1897     struct tm tm;
1898     afs_uint32 rx_bindhost;
1899     VolumePackageOptions opts;
1900
1901 #ifdef  AFS_AIX32_ENV
1902     struct sigaction nsa;
1903
1904     sigemptyset(&nsa.sa_mask);
1905     nsa.sa_handler = SIG_DFL;
1906     nsa.sa_flags = SA_FULLDUMP;
1907     sigaction(SIGABRT, &nsa, NULL);
1908     sigaction(SIGSEGV, &nsa, NULL);
1909 #endif
1910     osi_audit_init();
1911
1912     /* Initialize dirpaths */
1913     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
1914 #ifdef AFS_NT40_ENV
1915         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
1916 #endif
1917         fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
1918                 argv[0]);
1919         exit(2);
1920     }
1921     /* set ihandle package defaults prior to parsing args */
1922     ih_PkgDefaults();
1923
1924     /* check for the parameter file */
1925     CheckParms();
1926
1927     if (ParseArgs(argc, argv)) {
1928         exit(-1);
1929     }
1930 #ifdef AFS_PTHREAD_ENV
1931     MUTEX_INIT(&fileproc_glock_mutex, "fileproc", MUTEX_DEFAULT, 0);
1932 #endif /* AFS_PTHREAD_ENV */
1933
1934 #ifdef AFS_SGI_VNODE_GLUE
1935     if (afs_init_kernel_config(-1) < 0) {
1936         printf
1937             ("Can't determine NUMA configuration, not starting fileserver.\n");
1938         exit(1);
1939     }
1940 #endif
1941     confDir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
1942     if (!confDir) {
1943         fprintf(stderr, "Unable to open config directory %s\n",
1944                 AFSDIR_SERVER_ETC_DIRPATH);
1945         exit(-1);
1946     }
1947
1948     /* Open FileLog on stdout, stderr, fd 1 and fd2 (for perror), sigh. */
1949 #ifndef AFS_NT40_ENV
1950     serverLogSyslogTag = "fileserver";
1951 #endif
1952     OpenLog(AFSDIR_SERVER_FILELOG_FILEPATH);
1953     SetupLogSignals();
1954
1955     LogCommandLine(argc, argv, "starting", "", "File server", FSLog);
1956
1957 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
1958     /* initialize the pthread soft signal handler thread */
1959     softsig_init();
1960 #endif
1961
1962     /* install signal handlers for controlling the fileserver process */
1963     ResetCheckSignal();         /* set CheckSignal_Signal() sig handler */
1964     ResetCheckDescriptors();    /* set CheckDescriptors_Signal() sig handler */
1965
1966 #if defined(AFS_SGI_ENV)
1967     /* give this guy a non-degrading priority so help busy servers */
1968     schedctl(NDPRI, 0, NDPNORMMAX);
1969     if (SawLock)
1970         plock(PROCLOCK);
1971 #elif !defined(AFS_NT40_ENV)
1972     nice(-5);                   /* TODO: */
1973 #endif
1974     DInit(buffs);
1975 #ifdef AFS_DEMAND_ATTACH_FS
1976     FS_STATE_INIT;
1977 #endif
1978
1979 #ifdef AFS_NT40_ENV
1980     if (afs_winsockInit() < 0) {
1981         ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
1982         ViceLog(0, ("File server failed to intialize winsock.\n"));
1983         exit(1);
1984     }
1985 #endif
1986     CheckAdminName();
1987
1988     /* if we support more than 16 threads, then we better have the ability
1989      ** to keep open a large number of files simultaneously
1990      */
1991 #if     defined(AFS_AIX_ENV) && !defined(AFS_AIX42_ENV)
1992     curLimit = OPEN_MAX;        /* for pre AIX 4.2 systems */
1993 #elif defined(AFS_NT40_ENV)
1994     curLimit = NT_OPEN_MAX;     /* open file descriptor limit on NT */
1995 #else
1996
1997     curLimit = 0;               /* the number of open file descriptors */
1998     code = getrlimit(RLIMIT_NOFILE, &rlim);
1999     if (code == 0) {
2000         curLimit = rlim.rlim_cur;
2001         rlim.rlim_cur = rlim.rlim_max;
2002         code = setrlimit(RLIMIT_NOFILE, &rlim);
2003         if (code == 0)
2004             curLimit = rlim.rlim_max;
2005     }
2006     if (code != 0)
2007         ViceLog(0, ("Failed to increase open file limit, using default\n"));
2008
2009 #endif /* defined(AFS_AIX_ENV) && !defined(AFS_AIX42_ENV) */
2010
2011     curLimit -= 32;             /* leave a slack of 32 file descriptors */
2012     if (lwps > curLimit) {
2013         if (curLimit > 0)
2014             lwps = curLimit;
2015         else if (lwps > 16)
2016             lwps = 16;          /* default to a maximum of 16 threads */
2017
2018         /* tune the ihandle fd cache accordingly */
2019         if (vol_io_params.fd_max_cachesize < curLimit)
2020             vol_io_params.fd_max_cachesize = curLimit + 1;
2021
2022         ViceLog(0,
2023                 ("The system supports a max of %d open files and we are starting %d threads (ihandle fd cache is %d)\n",
2024                  curLimit, lwps, vol_io_params.fd_max_cachesize));
2025     }
2026 #ifndef AFS_PTHREAD_ENV
2027     osi_Assert(LWP_InitializeProcessSupport(LWP_MAX_PRIORITY - 2, &parentPid) ==
2028            LWP_SUCCESS);
2029 #endif /* !AFS_PTHREAD_ENV */
2030
2031     /* Initialize volume support */
2032     if (!novbc) {
2033         V_BreakVolumeCallbacks = BreakVolumeCallBacksLater;
2034     }
2035
2036 #ifdef AFS_PTHREAD_ENV
2037     SetLogThreadNumProgram( rx_GetThreadNum );
2038 #endif
2039
2040     /* initialize libacl routines */
2041     acl_Initialize(ACL_VERSION);
2042
2043     /* initialize RX support */
2044 #ifndef AFS_NT40_ENV
2045     rxi_syscallp = viced_syscall;
2046 #endif
2047     rx_extraPackets = rxpackets;
2048     rx_extraQuota = 4;          /* for outgoing prserver calls from R threads */
2049     rx_SetBusyThreshold(busy_threshold, VBUSY);
2050     rx_SetCallAbortThreshold(abort_threshold);
2051     rx_SetConnAbortThreshold(abort_threshold);
2052 #ifdef AFS_XBSD_ENV
2053     stackSize = 128 * 1024;
2054 #else
2055     stackSize = lwps * 4000;
2056     if (stackSize < 32000)
2057         stackSize = 32000;
2058     else if (stackSize > 44000)
2059         stackSize = 44000;
2060 #endif
2061 #if defined(AFS_HPUX_ENV) || defined(AFS_SUN_ENV) || defined(AFS_SGI51_ENV) || defined(AFS_XBSD_ENV)
2062     rx_SetStackSize(1, stackSize);
2063 #endif
2064     if (udpBufSize)
2065         rx_SetUdpBufSize(udpBufSize);   /* set the UDP buffer size for receive */
2066     rx_bindhost = SetupVL();
2067
2068     if (rx_InitHost(rx_bindhost, (int)htons(7000)) < 0) {
2069         ViceLog(0, ("Cannot initialize RX\n"));
2070         exit(1);
2071     }
2072     if (!rxJumbograms) {
2073         /* Don't send and don't allow 3.4 clients to send jumbograms. */
2074         rx_SetNoJumbo();
2075     }
2076     if (rxMaxMTU != -1) {
2077         rx_SetMaxMTU(rxMaxMTU);
2078     }
2079     rx_GetIFInfo();
2080     rx_SetRxDeadTime(30);
2081     afsconf_SetSecurityFlags(confDir, AFSCONF_SECOPTS_ALWAYSENCRYPT);
2082     afsconf_BuildServerSecurityObjects(confDir, &securityClasses, &numClasses);
2083
2084     tservice = rx_NewServiceHost(rx_bindhost,  /* port */ 0, /* service id */
2085                                  1,     /*service name */
2086                                  "AFS",
2087                                  securityClasses, numClasses,
2088                                  RXAFS_ExecuteRequest);
2089     if (!tservice) {
2090         ViceLog(0,
2091                 ("Failed to initialize RX, probably two servers running.\n"));
2092         exit(-1);
2093     }
2094     if (rxkadDisableDotCheck) {
2095         rx_SetSecurityConfiguration(tservice, RXS_CONFIG_FLAGS,
2096                                     (void *)RXS_CONFIG_FLAGS_DISABLE_DOTCHECK);
2097     }
2098     rx_SetMinProcs(tservice, 3);
2099     rx_SetMaxProcs(tservice, lwps);
2100     rx_SetCheckReach(tservice, 1);
2101     rx_SetServerIdleDeadErr(tservice, VNOSERVICE);
2102
2103     tservice =
2104         rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats", securityClasses,
2105                       numClasses, RXSTATS_ExecuteRequest);
2106     if (!tservice) {
2107         ViceLog(0, ("Failed to initialize rpc stat service.\n"));
2108         exit(-1);
2109     }
2110     rx_SetMinProcs(tservice, 2);
2111     rx_SetMaxProcs(tservice, 4);
2112
2113     /*
2114      * Enable RX hot threads, which allows the listener thread to trade
2115      * places with an idle thread and moves the context switch from listener
2116      * to worker out of the critical path.
2117      */
2118     rx_EnableHotThread();
2119
2120     /* Some rx debugging */
2121     if (rxlog || eventlog) {
2122         debugFile = afs_fopen("rx_dbg", "w");
2123         if (rxlog)
2124             rx_debugFile = debugFile;
2125         if (eventlog)
2126             rxevent_debugFile = debugFile;
2127     }
2128
2129     init_sys_error_to_et();     /* Set up error table translation */
2130     h_InitHostPackage();        /* set up local cellname and realmname */
2131     InitCallBack(numberofcbs);
2132     ClearXStatValues();
2133
2134     code = InitVL();
2135     if (code && code != VL_MULTIPADDR) {
2136         ViceLog(0, ("Fatal error in library initialization, exiting!!\n"));
2137         exit(1);
2138     }
2139
2140     code = InitPR();
2141     if (code && code != -1) {
2142         ViceLog(0, ("Fatal error in protection initialization, exiting!!\n"));
2143         exit(1);
2144     }
2145
2146     /* allow super users to manage RX statistics */
2147     rx_SetRxStatUserOk(fs_rxstat_userok);
2148
2149     CV_INIT(&fsync_cond, "fsync", CV_DEFAULT, 0);
2150     MUTEX_INIT(&fsync_glock_mutex, "fsync", MUTEX_DEFAULT, 0);
2151
2152 #if !defined(AFS_DEMAND_ATTACH_FS)
2153     /*
2154      * For DAFS, we do not start the Rx server threads until after
2155      * the volume package is initialized, and fileserver state is
2156      * restored.  This is necessary in order to keep host and callback
2157      * package state pristine until we have a chance to restore state.
2158      *
2159      * Furthermore, startup latency is much lower with dafs, so this
2160      * shouldn't pose a serious problem.
2161      */
2162     rx_StartServer(0);          /* now start handling requests */
2163 #endif
2164
2165     /* we ensure that there is enough space in the vnode buffer to satisfy
2166      ** requests from all concurrent threads.
2167      ** the maximum number of vnodes used by a single thread at any one time
2168      ** is three ( "link" uses three vnodes simultaneously, one vLarge and
2169      ** two vSmall for linking files and two vLarge and one vSmall for linking
2170      ** files  ) : dhruba
2171      */
2172     minVnodesRequired = 2 * lwps + 1;
2173     if (minVnodesRequired > nSmallVns) {
2174         nSmallVns = minVnodesRequired;
2175         ViceLog(0,
2176                 ("Overriding -s command line parameter with %d\n",
2177                  nSmallVns));
2178     }
2179     if (minVnodesRequired > large) {
2180         large = minVnodesRequired;
2181         ViceLog(0, ("Overriding -l command line parameter with %d\n", large));
2182     }
2183
2184     /* We now do this after getting the listener up and running, so that client
2185      * connections don't timeout (maybe) if a file server is restarted, since it
2186      * will be available "real soon now".  Worry about whether we can satisfy the
2187      * calls in the volume package itself.
2188      */
2189     VOptDefaults(fileServer, &opts);
2190     opts.nLargeVnodes = large;
2191     opts.nSmallVnodes = nSmallVns;
2192     opts.volcache = volcache;
2193     opts.unsafe_attach = unsafe_attach;
2194     if (offline_timeout != -1) {
2195         opts.interrupt_rxcall = rx_InterruptCall;
2196         opts.offline_timeout = offline_timeout;
2197     }
2198     if (offline_shutdown_timeout == -1) {
2199         /* default to -offline-timeout, if shutdown-specific timeout is not
2200          * specified */
2201         opts.offline_shutdown_timeout = offline_timeout;
2202     } else {
2203         opts.interrupt_rxcall = rx_InterruptCall;
2204         opts.offline_shutdown_timeout = offline_shutdown_timeout;
2205     }
2206
2207     if (VInitVolumePackage2(fileServer, &opts)) {
2208         ViceLog(0,
2209                 ("Shutting down: errors encountered initializing volume package\n"));
2210         VShutdown();
2211         exit(1);
2212     }
2213
2214     /* Install handler to catch the shutdown signal;
2215      * bosserver assumes SIGQUIT shutdown
2216      */
2217 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
2218     softsig_signal(SIGQUIT, ShutDown_Signal);
2219 #else
2220     (void)signal(SIGQUIT, ShutDown_Signal);
2221 #endif
2222
2223     if (VInitAttachVolumes(fileServer)) {
2224         ViceLog(0,
2225                 ("Shutting down: errors encountered initializing volume package\n"));
2226         VShutdown();
2227         exit(1);
2228     }
2229
2230 #ifdef AFS_DEMAND_ATTACH_FS
2231     if (fs_state.options.fs_state_restore) {
2232         /*
2233          * demand attach fs
2234          * restore fileserver state */
2235         fs_stateRestore();
2236     }
2237     rx_StartServer(0);  /* now start handling requests */
2238 #endif /* AFS_DEMAND_ATTACH_FS */
2239
2240     /*
2241      * We are done calling fopen/fdopen. It is safe to use a large
2242      * of the file descriptor cache.
2243      */
2244     ih_UseLargeCache();
2245
2246 #ifdef AFS_PTHREAD_ENV
2247     ViceLog(5, ("Starting pthreads\n"));
2248     osi_Assert(pthread_attr_init(&tattr) == 0);
2249     osi_Assert(pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) == 0);
2250
2251     osi_Assert(pthread_create
2252            (&serverPid, &tattr, FiveMinuteCheckLWP,
2253             &fiveminutes) == 0);
2254     osi_Assert(pthread_create
2255            (&serverPid, &tattr, HostCheckLWP, &fiveminutes) == 0);
2256     osi_Assert(pthread_create
2257            (&serverPid, &tattr, FsyncCheckLWP, &fiveminutes) == 0);
2258 #else /* AFS_PTHREAD_ENV */
2259     ViceLog(5, ("Starting LWP\n"));
2260     osi_Assert(LWP_CreateProcess
2261            (FiveMinuteCheckLWP, stack * 1024, LWP_MAX_PRIORITY - 2,
2262             (void *)&fiveminutes, "FiveMinuteChecks",
2263             &serverPid) == LWP_SUCCESS);
2264
2265     osi_Assert(LWP_CreateProcess
2266            (HostCheckLWP, stack * 1024, LWP_MAX_PRIORITY - 2,
2267             (void *)&fiveminutes, "HostCheck", &serverPid) == LWP_SUCCESS);
2268     osi_Assert(LWP_CreateProcess
2269            (FsyncCheckLWP, stack * 1024, LWP_MAX_PRIORITY - 2,
2270             (void *)&fiveminutes, "FsyncCheck", &serverPid) == LWP_SUCCESS);
2271 #endif /* AFS_PTHREAD_ENV */
2272
2273     FT_GetTimeOfDay(&tp, 0);
2274
2275     /*
2276      * Figure out the FileServer's name and primary address.
2277      */
2278     ViceLog(0, ("Getting FileServer name...\n"));
2279     code = gethostname(FS_HostName, 64);
2280     if (code) {
2281         ViceLog(0, ("gethostname() failed\n"));
2282     }
2283     ViceLog(0, ("FileServer host name is '%s'\n", FS_HostName));
2284
2285     ViceLog(0, ("Getting FileServer address...\n"));
2286     he = gethostbyname(FS_HostName);
2287     if (!he) {
2288         ViceLog(0, ("Can't find address for FileServer '%s'\n", FS_HostName));
2289     } else {
2290         char hoststr[16];
2291         memcpy(&FS_HostAddr_NBO, he->h_addr, 4);
2292         (void)afs_inet_ntoa_r(FS_HostAddr_NBO, hoststr);
2293         FS_HostAddr_HBO = ntohl(FS_HostAddr_NBO);
2294         ViceLog(0,
2295                 ("FileServer %s has address %s (0x%x or 0x%x in host byte order)\n",
2296                  FS_HostName, hoststr, FS_HostAddr_NBO, FS_HostAddr_HBO));
2297     }
2298
2299     t = tp.tv_sec;
2300     strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2301              localtime_r(&t, &tm));
2302     ViceLog(0, ("File Server started %s\n", tbuffer));
2303 #if FS_STATS_DETAILED
2304     afs_FullPerfStats.det.epoch.tv_sec = StartTime = tp.tv_sec;
2305 #endif
2306 #ifdef AFS_PTHREAD_ENV
2307     while (1) {
2308         sleep(1000);            /* long time */
2309     }
2310 #else /* AFS_PTHREAD_ENV */
2311     osi_Assert(LWP_WaitProcess(&parentPid) == LWP_SUCCESS);
2312 #endif /* AFS_PTHREAD_ENV */
2313     return 0;
2314 }