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