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