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