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