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