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