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