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