viced: Catch GetCellInfo failure
[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
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     opr_cv_init(&fs_state.worker_done_cv, "worker done");
232     opr_Verify(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 = time(NULL);
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     opr_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     opr_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 = opr_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     opr_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     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         opr_Verify(pthread_attr_init(&tattr) == 0);
733         opr_Verify(pthread_create(&watchdogPid, &tattr,
734                                   ShutdownWatchdogLWP, NULL) == 0);
735     }
736
737     /* do not allows new reqests to be served from now on, all new requests
738      * are returned with an error code of RX_RESTARTING ( transient failure ) */
739     rx_SetRxTranquil();         /* dhruba */
740
741     VSetTranquil();
742
743 #ifdef AFS_DEMAND_ATTACH_FS
744     FS_STATE_WRLOCK;
745     if (fs_state.mode == FS_MODE_SHUTDOWN) {
746         /* it is possible for at least fs_stateSave() (called below) to call
747          * ShutDownAndCore if there's host list corruption; prevent
748          * deinitializing some stuff twice */
749         ViceLog(0, ("ShutDownAndCore called during shutdown? Skipping volume "
750                     "and host package shutdown\n"));
751         FS_STATE_UNLOCK;
752         goto done_vol_host;
753     }
754     fs_state.mode = FS_MODE_SHUTDOWN;
755     FS_STATE_UNLOCK;
756 #endif
757
758     strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
759              localtime_r(&now, &tm));
760     ViceLog(0, ("Shutting down file server at %s\n", tbuffer));
761     if (dopanic)
762         ViceLog(0, ("ABNORMAL SHUTDOWN, see core file.\n"));
763     DFlush();
764     if (!dopanic)
765         PrintCounters();
766
767     /* shut down volume package */
768     VShutdown();
769
770 #ifdef AFS_DEMAND_ATTACH_FS
771     if (fs_state.options.fs_state_save) {
772         /*
773          * demand attach fs
774          * save fileserver state to disk */
775
776         if (dopanic) {
777             ViceLog(0, ("Not saving fileserver state; abnormal shutdown\n"));
778
779         } else {
780             /* make sure background threads have finished all of their asynchronous
781              * work on host and callback structures */
782             FS_STATE_RDLOCK;
783             while (!fs_state.FiveMinuteLWP_tranquil ||
784                    !fs_state.HostCheckLWP_tranquil ||
785                    !fs_state.FsyncCheckLWP_tranquil) {
786                 FS_LOCK;
787                 FS_STATE_UNLOCK;
788                 ViceLog(0, ("waiting for background host/callback threads to quiesce before saving fileserver state...\n"));
789                 opr_cv_wait(&fs_state.worker_done_cv, &fileproc_glock_mutex);
790                 FS_UNLOCK;
791                 FS_STATE_RDLOCK;
792             }
793             FS_STATE_UNLOCK;
794
795             /* ok. it should now be fairly safe. let's do the state dump */
796             fs_stateSave();
797         }
798     }
799  done_vol_host:
800
801 #endif /* AFS_DEMAND_ATTACH_FS */
802
803     if (debugFile) {
804         rx_PrintStats(debugFile);
805         fflush(debugFile);
806     }
807     now = time(0);
808     strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
809              localtime_r(&now, &tm));
810     if (dopanic) {
811       ViceLog(0, ("File server has terminated abnormally at %s\n", tbuffer));
812     } else {
813       ViceLog(0, ("File server has terminated normally at %s\n", tbuffer));
814     }
815
816     if (dopanic) /* XXX pass in file and line? */
817         osi_Panic("Panic requested\n");
818
819     exit(0);
820 }
821
822 void *
823 ShutDown(void *unused)
824 {                               /* backward compatibility */
825     ShutDownAndCore(DONTPANIC);
826     return 0;
827 }
828
829 static afs_int32
830 ParseRights(char *arights)
831 {
832     afs_int32 mode = 0;
833     int i, len;
834     char tc;
835
836     if (!arights || !strcmp(arights, "")) {
837         printf("Missing list of mode bits on -implicit option\n");
838         return -1;
839     }
840     if (!strcmp(arights, "none"))
841         mode = 0;
842     else if (!strcmp(arights, "read"))
843         mode = PRSFS_READ | PRSFS_LOOKUP;
844     else if (!strcmp(arights, "write"))
845         mode =
846             PRSFS_READ | PRSFS_LOOKUP | PRSFS_INSERT | PRSFS_DELETE |
847             PRSFS_WRITE | PRSFS_LOCK;
848     else if (!strcmp(arights, "all"))
849         mode =
850             PRSFS_READ | PRSFS_LOOKUP | PRSFS_INSERT | PRSFS_DELETE |
851             PRSFS_WRITE | PRSFS_LOCK | PRSFS_ADMINISTER;
852     else {
853         len = strlen(arights);
854         for (i = 0; i < len; i++) {
855             tc = *arights++;
856             if (tc == 'r')
857                 mode |= PRSFS_READ;
858             else if (tc == 'l')
859                 mode |= PRSFS_LOOKUP;
860             else if (tc == 'i')
861                 mode |= PRSFS_INSERT;
862             else if (tc == 'd')
863                 mode |= PRSFS_DELETE;
864             else if (tc == 'w')
865                 mode |= PRSFS_WRITE;
866             else if (tc == 'k')
867                 mode |= PRSFS_LOCK;
868             else if (tc == 'a')
869                 mode |= PRSFS_ADMINISTER;
870             else if (tc == 'A')
871                 mode |= PRSFS_USR0;
872             else if (tc == 'B')
873                 mode |= PRSFS_USR1;
874             else if (tc == 'C')
875                 mode |= PRSFS_USR2;
876             else if (tc == 'D')
877                 mode |= PRSFS_USR3;
878             else if (tc == 'E')
879                 mode |= PRSFS_USR4;
880             else if (tc == 'F')
881                 mode |= PRSFS_USR5;
882             else if (tc == 'G')
883                 mode |= PRSFS_USR6;
884             else if (tc == 'H')
885                 mode |= PRSFS_USR7;
886             else {
887                 printf("Illegal -implicit rights character '%c'.\n", tc);
888                 return -1;
889             }
890         }
891     }
892     return mode;
893 }
894
895 /*
896  * Limit MAX_FILESERVER_THREAD by the system limit on the number of
897  * pthreads (sysconf(_SC_THREAD_THREADS_MAX)), if applicable and
898  * available.
899  *
900  * AIX:         sysconf() limit is real
901  * HP-UX:       sysconf() limit is real
902  * IRIX:        sysconf() limit is apparently NOT real -- too small
903  * DUX:         sysconf() limit is apparently NOT real -- too big
904  * Linux:       sysconf() limit is apparently NOT real -- too big
905  * Solaris:     no sysconf() limit
906  */
907 static int
908 max_fileserver_thread(void)
909 {
910 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV)
911     long ans;
912
913     ans = sysconf(_SC_THREAD_THREADS_MAX);
914     if (0 < ans && ans < MAX_FILESERVER_THREAD)
915         return (int)ans;
916 #endif
917     return MAX_FILESERVER_THREAD;
918 }
919
920 /* from ihandle.c */
921 extern ih_init_params vol_io_params;
922
923 enum optionsList {
924     OPT_large,
925     OPT_small,
926     OPT_banner,
927     OPT_implicit,
928     OPT_lock,
929     OPT_readonly,
930     OPT_saneacls,
931     OPT_buffers,
932     OPT_callbacks,
933     OPT_vcsize,
934     OPT_lvnodes,
935     OPT_svnodes,
936     OPT_sendsize,
937     OPT_minspare,
938     OPT_spare,
939     OPT_pctspare,
940     OPT_hostcpsrefresh,
941     OPT_vattachthreads,
942     OPT_abortthreshold,
943     OPT_busyat,
944     OPT_nobusy,
945     OPT_offline_timeout,
946     OPT_offline_shutdown_timeout,
947     OPT_vhandle_setaside,
948     OPT_vhandle_max_cachesize,
949     OPT_vhandle_initial_cachesize,
950     OPT_fs_state_dont_save,
951     OPT_fs_state_dont_restore,
952     OPT_fs_state_verify,
953     OPT_vhashsize,
954     OPT_vlrudisable,
955     OPT_vlruthresh,
956     OPT_vlruinterval,
957     OPT_vlrumax,
958     OPT_unsafe_nosalvage,
959     OPT_stack,
960     OPT_cbwait,
961     OPT_novbc,
962     OPT_auditlog,
963     OPT_auditiface,
964     OPT_config,
965     OPT_debug,
966     OPT_logfile,
967     OPT_mrafslogs,
968     OPT_threads,
969     OPT_syslog,
970     OPT_peer,
971     OPT_process,
972     OPT_nojumbo,
973     OPT_jumbo,
974     OPT_rxbind,
975     OPT_rxdbg,
976     OPT_rxdbge,
977     OPT_rxpck,
978     OPT_rxmaxmtu,
979     OPT_udpsize,
980     OPT_dotted,
981     OPT_realm
982 };
983
984 static int
985 ParseArgs(int argc, char *argv[])
986 {
987     int code;
988     int optval;
989     char *optstring = NULL;
990     struct cmd_item *optlist;
991     struct cmd_syndesc *opts;
992
993     int lwps_max;
994     char *auditFileName = NULL;
995
996 #if defined(AFS_AIX32_ENV)
997     extern int aixlow_water;
998 #endif
999
1000     opts = cmd_CreateSyntax(NULL, NULL, NULL, NULL);
1001
1002     /* fileserver options */
1003     cmd_AddParmAtOffset(opts, OPT_large, "-L", CMD_FLAG,
1004                         CMD_OPTIONAL, "defaults for a 'large' server");
1005     cmd_AddParmAtOffset(opts, OPT_small, "-S", CMD_FLAG,
1006                         CMD_OPTIONAL, "defaults for a 'small' server");
1007
1008     cmd_AddParmAtOffset(opts, OPT_banner, "-banner", CMD_FLAG,
1009                         CMD_OPTIONAL, "print regular banners to log");
1010     cmd_AddParmAtOffset(opts, OPT_implicit, "-implicit", CMD_SINGLE,
1011                         CMD_OPTIONAL, "implicit admin access bits");
1012
1013 #if defined(AFS_SGI_ENV)
1014     cmd_AddParmAtOffset(opts, OPT_lock, "-lock", CMD_FLAG,
1015                         CMD_OPTIONAL, "lock filserver binary in memory");
1016 #endif
1017     cmd_AddParmAtOffset(opts, OPT_readonly, "-readonly", CMD_FLAG,
1018                         CMD_OPTIONAL, "be a readonly fileserver");
1019     cmd_AddParmAtOffset(opts, OPT_saneacls, "-saneacls", CMD_FLAG,
1020                         CMD_OPTIONAL, "set the saneacls capability bit");
1021
1022     cmd_AddParmAtOffset(opts, OPT_buffers, "-b", CMD_SINGLE,
1023                         CMD_OPTIONAL, "buffers");
1024     cmd_AddParmAtOffset(opts, OPT_callbacks, "-cb", CMD_SINGLE,
1025                         CMD_OPTIONAL, "number of callbacks");
1026     cmd_AddParmAtOffset(opts, OPT_vcsize, "-vc", CMD_SINGLE,
1027                         CMD_OPTIONAL, "volume cachesize");
1028     cmd_AddParmAtOffset(opts, OPT_lvnodes, "-l", CMD_SINGLE,
1029                         CMD_OPTIONAL, "large vnodes");
1030     cmd_AddParmAtOffset(opts, OPT_svnodes, "-s", CMD_SINGLE,
1031                         CMD_OPTIONAL, "small vnodes");
1032     cmd_AddParmAtOffset(opts, OPT_sendsize, "-sendsize", CMD_SINGLE,
1033                         CMD_OPTIONAL, "size of send buffer in bytes");
1034
1035 #if defined(AFS_AIX32_ENV)
1036     cmd_AddParmAtOffset(opts, OPT_minspare, "-m", CMD_SINGLE,
1037                         CMD_OPTIONAL, "minimum percentage spare in partition");
1038 #endif
1039
1040     cmd_AddParmAtOffset(opts, OPT_spare, "-spare", CMD_SINGLE,
1041                         CMD_OPTIONAL, "kB overage on volume quota");
1042     cmd_AddParmAtOffset(opts, OPT_pctspare, "pctspare", CMD_SINGLE,
1043                         CMD_OPTIONAL, "percentage overage on volume quota");
1044
1045     cmd_AddParmAtOffset(opts, OPT_hostcpsrefresh, "-hr", CMD_SINGLE,
1046                         CMD_OPTIONAL, "hours between host CPS refreshes");
1047
1048     cmd_AddParmAtOffset(opts, OPT_vattachthreads, "-vattachpar", CMD_SINGLE,
1049                         CMD_OPTIONAL, "# of volume attachment threads");
1050
1051     cmd_AddParmAtOffset(opts, OPT_abortthreshold, "-abortthreshold",
1052                         CMD_SINGLE, CMD_OPTIONAL,
1053                         "abort threshold");
1054     cmd_AddParmAtOffset(opts, OPT_busyat, "-busyat", CMD_SINGLE, CMD_OPTIONAL,
1055                         "# of queued entries after which server is busy");
1056     cmd_AddParmAtOffset(opts, OPT_nobusy, "-nobusy", CMD_FLAG, CMD_OPTIONAL,
1057                         "send VRESTARTING while restarting the server");
1058
1059     cmd_AddParmAtOffset(opts, OPT_offline_timeout, "-offline-timeout",
1060                         CMD_SINGLE, CMD_OPTIONAL,
1061                         "timeout for offlining volumes");
1062     cmd_AddParmAtOffset(opts, OPT_offline_shutdown_timeout,
1063                         "-offline-shutdown-timeout", CMD_SINGLE, CMD_OPTIONAL,
1064                         "timeout offlining volumes during shutdown");
1065
1066     cmd_AddParmAtOffset(opts, OPT_vhandle_setaside, "-vhandle-setaside",
1067                         CMD_SINGLE, CMD_OPTIONAL,
1068                         "# fds reserved for non-cache IO");
1069     cmd_AddParmAtOffset(opts, OPT_vhandle_max_cachesize, 
1070                         "-vhandle-max-cachesize", CMD_SINGLE, CMD_OPTIONAL,
1071                         "max open files");
1072     cmd_AddParmAtOffset(opts, OPT_vhandle_initial_cachesize,
1073                         "-vhandle-initial-cachesize", CMD_SINGLE,
1074                         CMD_OPTIONAL, "# fds reserved for cache IO");
1075
1076 #ifdef AFS_DEMAND_ATTACH_FS
1077     /* dafs options */
1078     cmd_AddParmAtOffset(opts, OPT_fs_state_dont_save,
1079                         "-fs-state-dont-save", CMD_FLAG, CMD_OPTIONAL,
1080                         "disable state save during shutdown");
1081     cmd_AddParmAtOffset(opts, OPT_fs_state_dont_restore,
1082                         "-fs-state-dont-restore", CMD_FLAG, CMD_OPTIONAL,
1083                         "disable state restore during startup");
1084     cmd_AddParmAtOffset(opts, OPT_fs_state_verify, "-fs-state-verify",
1085                         CMD_SINGLE, CMD_OPTIONAL, "none|save|restore|both");
1086     cmd_AddParmAtOffset(opts, OPT_vhashsize, "-vhashsize",
1087                         CMD_SINGLE, CMD_OPTIONAL,
1088                         "log(2) of # of volume hash buckets");
1089     cmd_AddParmAtOffset(opts, OPT_vlrudisable, "-vlrudisable",
1090                         CMD_FLAG, CMD_OPTIONAL, "disable VLRU functionality");
1091     cmd_AddParmAtOffset(opts, OPT_vlruthresh, "-vlruthresh",
1092                         CMD_FLAG, CMD_OPTIONAL,
1093                         "mins before unused vols become eligible for detach");
1094     cmd_AddParmAtOffset(opts, OPT_vlruinterval, "-vlruinterval",
1095                         CMD_FLAG, CMD_OPTIONAL, "secs between VLRU scans");
1096     cmd_AddParmAtOffset(opts, OPT_vlrumax, "-vlrumax", CMD_FLAG, CMD_OPTIONAL,
1097                         "max volumes to detach in one scan");
1098     cmd_AddParmAtOffset(opts, OPT_unsafe_nosalvage, "-unsafe-nosalvage",
1099                         CMD_FLAG, CMD_OPTIONAL,
1100                         "bybass safety checks on volume attach");
1101 #endif
1102
1103     /* unrecommend options - should perhaps be CMD_HIDE */
1104     cmd_AddParmAtOffset(opts, OPT_stack, "-k", CMD_SINGLE, CMD_OPTIONAL,
1105                         "stack size");
1106     cmd_AddParmAtOffset(opts, OPT_cbwait, "-w", CMD_SINGLE, CMD_OPTIONAL,
1107                         "callback wait interval");
1108     cmd_AddParmAtOffset(opts, OPT_novbc, "-novbc", CMD_SINGLE, CMD_FLAG,
1109                         "disable callback breaks on reattach");
1110
1111     /* general options */
1112     cmd_AddParmAtOffset(opts, OPT_auditlog, "-auditlog", CMD_SINGLE,
1113                         CMD_OPTIONAL, "location of audit log");
1114     cmd_AddParmAtOffset(opts, OPT_auditiface, "-audit-interface", CMD_SINGLE,
1115                         CMD_OPTIONAL, "interface to use for audit logging");
1116     cmd_AddParmAtOffset(opts, OPT_config, "-config", CMD_SINGLE, CMD_OPTIONAL,
1117                         "configuration location");
1118     cmd_AddParmAtOffset(opts, OPT_debug, "-d", CMD_SINGLE, CMD_OPTIONAL,
1119                         "debug level");
1120     cmd_AddParmAtOffset(opts, OPT_logfile, "-logfile", CMD_SINGLE,
1121                         CMD_OPTIONAL, "location of logfile");
1122     cmd_AddParmAtOffset(opts, OPT_mrafslogs, "-mrafslogs", CMD_FLAG,
1123                         CMD_OPTIONAL, "enable MRAFS style logging");
1124     cmd_AddParmAtOffset(opts, OPT_threads, "-p", CMD_SINGLE, CMD_OPTIONAL,
1125                         "number of threads");
1126 #if !defined(AFS_NT40_ENV)
1127     cmd_AddParmAtOffset(opts, OPT_syslog, "-syslog", CMD_SINGLE_OR_FLAG,
1128                         CMD_OPTIONAL, "log to syslog");
1129 #endif
1130
1131     /* rx options */
1132     cmd_AddParmAtOffset(opts, OPT_peer, "-enable_peer_stats", CMD_FLAG,
1133                         CMD_OPTIONAL, "enable RX transport statistics");
1134     cmd_AddParmAtOffset(opts, OPT_process, "-enable_process_stats", CMD_FLAG,
1135                         CMD_OPTIONAL, "enable RX RPC statistics");
1136     cmd_AddParmAtOffset(opts, OPT_nojumbo, "-nojumbo", CMD_FLAG,
1137                         CMD_OPTIONAL, "disable jumbograms");
1138     cmd_AddParmAtOffset(opts, OPT_jumbo, "-jumbo", CMD_FLAG, CMD_OPTIONAL,
1139                         "enable jumbograms");
1140     cmd_AddParmAtOffset(opts, OPT_rxbind, "-rxbind", CMD_FLAG, CMD_OPTIONAL,
1141                         "bind only to the primary interface");
1142     cmd_AddParmAtOffset(opts, OPT_rxdbg, "-rxdbg", CMD_FLAG, CMD_OPTIONAL,
1143                         "enable rx debugging");
1144     cmd_AddParmAtOffset(opts, OPT_rxdbge, "-rxdbge", CMD_FLAG, CMD_OPTIONAL,
1145                         "enable rx event debugging");
1146     cmd_AddParmAtOffset(opts, OPT_rxpck, "-rxpck", CMD_SINGLE, CMD_OPTIONAL,
1147                         "# of extra rx packets");
1148     cmd_AddParmAtOffset(opts, OPT_rxmaxmtu, "-rxmaxmtu", CMD_SINGLE,
1149                         CMD_OPTIONAL, "maximum MTU for RX");
1150     cmd_AddParmAtOffset(opts, OPT_udpsize, "-udpsize", CMD_SINGLE,
1151                         CMD_OPTIONAL, "size of socket buffer in bytes");
1152
1153     /* rxkad options */
1154     cmd_AddParmAtOffset(opts, OPT_dotted, "-allow-dotted-principals",
1155                         CMD_FLAG, CMD_OPTIONAL,
1156                         "permit Kerberos 5 principals with dots");
1157     cmd_AddParmAtOffset(opts, OPT_realm, "-realm",
1158                         CMD_LIST, CMD_OPTIONAL, "local realm");
1159
1160     code = cmd_Parse(argc, argv, &opts);
1161     if (code)
1162         return -1;
1163
1164     /* XXX - cmd_OptionAsString(opts, OPT_config, &configDir); */
1165
1166     cmd_OpenConfigFile(AFSDIR_SERVER_CONFIG_FILE_FILEPATH);
1167     cmd_SetCommandName("fileserver");
1168
1169     if (cmd_OptionPresent(opts, OPT_large)
1170         && cmd_OptionPresent(opts, OPT_small)) {
1171         printf("Only one of -L or -S must be specified\n");
1172         return -1;
1173     }
1174
1175     if (cmd_OptionPresent(opts, OPT_spare)
1176         && cmd_OptionPresent(opts, OPT_pctspare)) {
1177         printf("Both -spare and -pctspare specified, exiting.\n");
1178         return -1;
1179     }
1180
1181     if (cmd_OptionPresent(opts, OPT_large)) {
1182         rxpackets = 200;
1183         nSmallVns = 600;
1184         large = 600;
1185         numberofcbs = 64000;
1186         lwps = 128;
1187         buffs = 120;
1188         volcache = 600;
1189     }
1190
1191     if (cmd_OptionPresent(opts, OPT_small)) {
1192         rxpackets = 100;
1193         nSmallVns = 200;
1194         large = 200;
1195         numberofcbs = 20000;
1196         lwps = 6;
1197         buffs = 70;
1198         volcache = 200;
1199     }
1200
1201     cmd_OptionAsFlag(opts, OPT_banner, &printBanner);
1202
1203     if (cmd_OptionAsString(opts, OPT_implicit, &optstring) == 0) {
1204         implicitAdminRights = ParseRights(optstring);
1205         free(optstring);
1206         optstring = NULL;
1207         if (implicitAdminRights < 0)
1208             return implicitAdminRights;
1209     }
1210
1211 #if defined(AFS_SGI_ENV)
1212     cmd_OptionAsFlag(opts, OPT_lock, &SawLock);
1213 #endif
1214     cmd_OptionAsFlag(opts, OPT_readonly, &readonlyServer);
1215     cmd_OptionAsFlag(opts, OPT_saneacls, &saneacls);
1216     cmd_OptionAsInt(opts, OPT_buffers, &buffs);
1217
1218     if (cmd_OptionAsInt(opts, OPT_callbacks, &numberofcbs) == 0) {
1219         if ((numberofcbs < 10000) || (numberofcbs > 2147483647)) {
1220             printf("number of cbs %d invalid; "
1221                    "must be between 10000 and 2147483647\n", numberofcbs);
1222             return -1;
1223         }
1224     }
1225
1226     cmd_OptionAsInt(opts, OPT_vcsize, &volcache);
1227     cmd_OptionAsInt(opts, OPT_lvnodes, &large);
1228     cmd_OptionAsInt(opts, OPT_svnodes, &nSmallVns);
1229     if (cmd_OptionAsInt(opts, OPT_sendsize, &optval) == 0) {
1230         if (optval < 16384) {
1231             printf("Warning:sendsize %d is less than minimum %d; ignoring\n",
1232                    optval, 16384);
1233         } else
1234             sendBufSize = optval;
1235     }
1236
1237 #if defined(AFS_AIX32_ENV)
1238     if (cmd_OptionAsInt(opts, OPT_minspare, &aixlow_water) == 0) {
1239         if ((aixlow_water < 0) || (aixlow_water > 30)) {
1240             printf("space reserved %d%% invalid; must be between 0-30%\n",
1241                    aixlow_water);
1242             return -1;
1243         }
1244     }
1245 #endif
1246
1247     cmd_OptionAsInt(opts, OPT_spare, &BlocksSpare);
1248     if (cmd_OptionAsInt(opts, OPT_pctspare, &PctSpare) == 0) {
1249         BlocksSpare = 0;
1250     }
1251
1252     if (cmd_OptionAsInt(opts, OPT_hostcpsrefresh, &optval) == 0) {
1253         if ((optval < 1) || (optval > 36)) {
1254             printf("host acl refresh interval of %d hours is invalid; "
1255                    "hours must be between 1 and 36\n\n", optval);
1256             return -1;
1257         }
1258         hostaclRefresh = optval * 60 * 60;
1259     }
1260
1261     cmd_OptionAsInt(opts, OPT_vattachthreads, &vol_attach_threads);
1262
1263     cmd_OptionAsInt(opts, OPT_abortthreshold, &abort_threshold);
1264
1265     /* busyat is at the end, as rxpackets has to be set before we can use it */
1266     if (cmd_OptionPresent(opts, OPT_nobusy))
1267         busyonrst = 0;
1268
1269     if (cmd_OptionAsInt(opts, OPT_offline_timeout, &offline_timeout) == 0) {
1270         if (offline_timeout < -1) {
1271             printf("Invalid -offline-timeout value %d; the only valid "
1272                    "negative value is -1\n", offline_timeout);
1273             return -1;
1274         }
1275     }
1276
1277     if (cmd_OptionAsInt(opts, OPT_offline_shutdown_timeout,
1278                         &offline_shutdown_timeout) == 0) {
1279         if (offline_shutdown_timeout < -1) {
1280             printf("Invalid -offline-timeout value %d; the only valid "
1281                    "negative value is -1\n", offline_shutdown_timeout);
1282             return -1;
1283         }
1284     }
1285
1286     cmd_OptionAsUint(opts, OPT_vhandle_setaside,
1287                     &vol_io_params.fd_handle_setaside);
1288     cmd_OptionAsUint(opts, OPT_vhandle_max_cachesize,
1289                     &vol_io_params.fd_max_cachesize);
1290     cmd_OptionAsUint(opts, OPT_vhandle_initial_cachesize,
1291                     &vol_io_params.fd_initial_cachesize);
1292
1293 #ifdef AFS_DEMAND_ATTACH_FS
1294     if (cmd_OptionPresent(opts, OPT_fs_state_dont_save))
1295         fs_state.options.fs_state_save = 0;
1296     if (cmd_OptionPresent(opts, OPT_fs_state_dont_restore))
1297         fs_state.options.fs_state_restore = 0;
1298     if (cmd_OptionAsString(opts, OPT_fs_state_verify, &optstring) == 0) {
1299         if (strcmp(optstring, "none") == 0) {
1300             fs_state.options.fs_state_verify_before_save = 0;
1301             fs_state.options.fs_state_verify_after_restore = 0;
1302         } else if (strcmp(optstring, "save") == 0) {
1303             fs_state.options.fs_state_verify_after_restore = 0;
1304         } else if (strcmp(optstring, "restore") == 0) {
1305             fs_state.options.fs_state_verify_before_save = 0;
1306         } else if (strcmp(optstring, "both") == 0) {
1307             /* default */
1308         } else {
1309             fprintf(stderr, "invalid argument for -fs-state-verify\n");
1310             return -1;
1311         }
1312     }
1313     if (cmd_OptionAsInt(opts, OPT_vhashsize, &optval) == 0) {
1314         if (VSetVolHashSize(optval)) {
1315             fprintf(stderr, "specified -vhashsize (%d) is invalid or out "
1316                             "of range\n", optval);
1317             return -1;
1318         }
1319     }
1320     if (cmd_OptionPresent(opts, OPT_vlrudisable))
1321         VLRU_SetOptions(VLRU_SET_ENABLED, 0);
1322     if (cmd_OptionAsInt(opts, OPT_vlruthresh, &optval) == 0)
1323         VLRU_SetOptions(VLRU_SET_THRESH, 60*optval);
1324     if (cmd_OptionAsInt(opts, OPT_vlruinterval, &optval) == 0)
1325         VLRU_SetOptions(VLRU_SET_INTERVAL, optval);
1326     if (cmd_OptionAsInt(opts, OPT_vlrumax, &optval) == 0)
1327         VLRU_SetOptions(VLRU_SET_MAX, optval);
1328     cmd_OptionAsFlag(opts, OPT_unsafe_nosalvage, &unsafe_attach);
1329 #endif /* AFS_DEMAND_ATTACH_FS */
1330
1331     cmd_OptionAsInt(opts, OPT_stack, &stack);
1332     cmd_OptionAsInt(opts, OPT_cbwait, &fiveminutes);
1333     cmd_OptionAsFlag(opts, OPT_novbc, &novbc);
1334
1335     /* general server options */
1336     cmd_OptionAsString(opts, OPT_auditlog, &auditFileName);
1337
1338     if (cmd_OptionAsString(opts, OPT_auditiface, &optstring) == 0) {
1339         if (osi_audit_interface(optstring)) {
1340             printf("Invalid audit interface '%s'\n", optstring);
1341             return -1;
1342         }
1343         free(optstring);
1344         optstring = NULL;
1345     }
1346
1347     cmd_OptionAsInt(opts, OPT_debug, &LogLevel);
1348     /* XXX - cmd_OptionAsString(opts, OPT_logfile, &logFile); */
1349     cmd_OptionAsFlag(opts, OPT_mrafslogs, &mrafsStyleLogs);
1350
1351     if (cmd_OptionAsInt(opts, OPT_threads, &lwps) == 0) {
1352         lwps_max = max_fileserver_thread() - FILESERVER_HELPER_THREADS;
1353         if (lwps > lwps_max)
1354             lwps = lwps_max;
1355         else if (lwps <6)
1356             lwps = 6;
1357     }
1358
1359 #ifndef AFS_NT40_ENV
1360     if (cmd_OptionPresent(opts, OPT_syslog)) {
1361         serverLogSyslog = 1;
1362         cmd_OptionAsInt(opts, OPT_syslog, &serverLogSyslogFacility);
1363     }
1364 #endif
1365
1366     if (cmd_OptionPresent(opts, OPT_peer))
1367         rx_enablePeerRPCStats();
1368     if (cmd_OptionPresent(opts, OPT_process))
1369         rx_enableProcessRPCStats();
1370     if (cmd_OptionPresent(opts, OPT_nojumbo))
1371         rxJumbograms = 0;
1372     if (cmd_OptionPresent(opts, OPT_jumbo))
1373         rxJumbograms = 1;
1374     cmd_OptionAsFlag(opts, OPT_rxbind, &rxBind);
1375     cmd_OptionAsFlag(opts, OPT_rxdbg, &rxlog);
1376     cmd_OptionAsFlag(opts, OPT_rxdbge, &eventlog);
1377     cmd_OptionAsInt(opts, OPT_rxpck, &rxpackets);
1378
1379     cmd_OptionAsInt(opts, OPT_rxmaxmtu, &rxMaxMTU);
1380
1381     if (cmd_OptionAsInt(opts, OPT_udpsize, &optval) == 0) {
1382         if (optval < rx_GetMinUdpBufSize()) {
1383             printf("Warning:udpsize %d is less than minimum %d; ignoring\n",
1384                    optval, rx_GetMinUdpBufSize());
1385         } else
1386             udpBufSize = optval;
1387     }
1388
1389     /* rxkad options */
1390     cmd_OptionAsFlag(opts, OPT_dotted, &rxkadDisableDotCheck);
1391     if (cmd_OptionAsList(opts, OPT_realm, &optlist) == 0) {
1392
1393         for (; optlist != NULL; optlist=optlist->next) {
1394             if (strlen(optlist->data) >= AFS_REALM_SZ) {
1395                 printf("-realm argument must contain fewer than %d "
1396                        "characters.\n", AFS_REALM_SZ);
1397                 return -1;
1398             }
1399             afsconf_SetLocalRealm(optlist->data); /* overrides krb.conf file, if one */
1400         }
1401     }
1402
1403     /* anything setting rxpackets must come before this */
1404     if (cmd_OptionAsInt(opts, OPT_busyat, &optval) == 0) {
1405         if (optval < 10) {
1406             printf("Busy threshold %d is too low, will use default.\n",
1407                    busy_threshold);
1408             busy_threshold = 3 * rxpackets / 2;
1409         } else {
1410             busy_threshold = optval;
1411         }
1412     } else {
1413         busy_threshold = 3 * rxpackets / 2;
1414     }
1415
1416     if (auditFileName)
1417         osi_audit_file(auditFileName);
1418
1419     return (0);
1420 }                               /*ParseArgs */
1421
1422 /* Once upon a time, in a galaxy far far away, IBM AFS supported the use of
1423  * a file /vice/file/parms, the contents of which would override any command
1424  * line parameters. We no longer support the use of such a file, but we warn
1425  * if we encounter its presence from an older release
1426  */
1427 static void
1428 CheckParms(void)
1429 {
1430     struct afs_stat sbuf;
1431
1432     if (afs_stat("/vice/file/parms", &sbuf) == 0) {
1433         ViceLog(0, ("Using /vice/file/parms to override command line "
1434                     "options is no longer supported"));
1435     }
1436 }
1437
1438 /* Miscellaneous routines */
1439 void
1440 Die(const char *msg)
1441 {
1442
1443     ViceLogThenPanic(0, ("%s\n", msg));
1444 }                               /*Die */
1445
1446
1447 afs_int32
1448 InitPR(void)
1449 {
1450     int code;
1451
1452     /*
1453      * If this fails, it's because something major is wrong, and is not
1454      * likely to be time dependent.
1455      */
1456     code = pr_Initialize(2, AFSDIR_SERVER_ETC_DIRPATH, 0);
1457     if (code != 0) {
1458         ViceLog(0,
1459                 ("Couldn't initialize protection library; code=%d.\n", code));
1460         return code;
1461     }
1462
1463     opr_Verify(pthread_key_create(&viced_uclient_key, NULL) == 0);
1464
1465     SystemId = SYSADMINID;
1466     SystemAnyUser = ANYUSERID;
1467     SystemAnyUserCPS.prlist_len = 0;
1468     SystemAnyUserCPS.prlist_val = NULL;
1469     AnonCPS.prlist_len = 0;
1470     AnonCPS.prlist_val = NULL;
1471     while (1) {
1472         code = pr_GetCPS(SystemAnyUser, &SystemAnyUserCPS);
1473         if (code != 0) {
1474             ViceLog(0,
1475                     ("Couldn't get CPS for AnyUser, will try again in 30 seconds; code=%d.\n",
1476                      code));
1477             goto sleep;
1478         }
1479         code = pr_GetCPS(ANONYMOUSID, &AnonCPS);
1480         if (code != 0) {
1481             ViceLog(0,
1482                     ("Couldn't get Anonymous CPS, exiting; code=%d.\n",
1483                      code));
1484             return -1;
1485         }
1486         AnonymousID = ANONYMOUSID;
1487         return 0;
1488       sleep:
1489         sleep(30);
1490     }
1491 }                               /*InitPR */
1492
1493 static struct ubik_client *cstruct;
1494
1495 static afs_int32
1496 vl_Initialize(struct afsconf_dir *dir)
1497 {
1498     afs_int32 code, i;
1499     afs_int32 scIndex = RX_SECIDX_NULL;
1500     struct afsconf_cell info;
1501     struct rx_securityClass *sc;
1502     struct rx_connection *serverconns[MAXSERVERS];
1503
1504     memset(serverconns, 0, sizeof(serverconns));
1505     code = afsconf_ClientAuth(dir, &sc, &scIndex);
1506     if (code) {
1507         ViceLog(0, ("Could not get security object for localAuth\n"));
1508         exit(1);
1509     }
1510     code = afsconf_GetCellInfo(dir, NULL, AFSCONF_VLDBSERVICE, &info);
1511     if (code) {
1512         ViceLog(0,
1513                 ("vl_Initialize: Failed to get cell information\n"));
1514         exit(1);
1515     }
1516     if (info.numServers > MAXSERVERS) {
1517         ViceLog(0,
1518                 ("vl_Initialize: info.numServers=%d (> MAXSERVERS=%d)\n",
1519                  info.numServers, MAXSERVERS));
1520         exit(1);
1521     }
1522     for (i = 0; i < info.numServers; i++)
1523         serverconns[i] =
1524             rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
1525                              info.hostAddr[i].sin_port, USER_SERVICE_ID, sc,
1526                              scIndex);
1527     code = ubik_ClientInit(serverconns, &cstruct);
1528     if (code) {
1529         ViceLog(0, ("vl_Initialize: ubik client init failed.\n"));
1530         return code;
1531     }
1532     return 0;
1533 }
1534
1535 #define SYSIDMAGIC      0x88aabbcc
1536 #define SYSIDVERSION    1
1537
1538 afs_int32
1539 ReadSysIdFile(void)
1540 {
1541     afs_int32 fd, nentries, i;
1542     struct versionStamp vsn;
1543     struct afs_stat status;
1544     afsUUID uuid;
1545
1546     if ((afs_stat(AFSDIR_SERVER_SYSID_FILEPATH, &status))
1547         || (status.st_size <= 0)) {
1548         ViceLog(0, ("%s: doesn't exist\n", AFSDIR_SERVER_SYSID_FILEPATH));
1549         return ENOENT;
1550     }
1551     if (!(fd = afs_open(AFSDIR_SERVER_SYSID_FILEPATH, O_RDONLY, 0))) {
1552         ViceLog(0,
1553                 ("%s: can't open (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH,
1554                  errno));
1555         return EIO;
1556     }
1557     if (read(fd, (char *)&vsn, sizeof(vsn)) != sizeof(vsn)) {
1558         ViceLog(0,
1559                 ("%s: Read failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH,
1560                  errno));
1561         return EIO;
1562     }
1563     if (vsn.magic != SYSIDMAGIC) {
1564         ViceLog(0,
1565                 ("%s: wrong magic %x (we support %x)\n",
1566                  AFSDIR_SERVER_SYSID_FILEPATH, vsn.magic, SYSIDMAGIC));
1567         return EIO;
1568     }
1569     if (vsn.version != SYSIDVERSION) {
1570         ViceLog(0,
1571                 ("%s: wrong version %d (we support %d)\n",
1572                  AFSDIR_SERVER_SYSID_FILEPATH, vsn.version, SYSIDVERSION));
1573         return EIO;
1574     }
1575     if (read(fd, (char *)&uuid, sizeof(struct afsUUID))
1576             != sizeof(struct afsUUID)) {
1577         ViceLog(0,
1578                 ("%s: read of uuid failed (%d)\n",
1579                  AFSDIR_SERVER_SYSID_FILEPATH, errno));
1580         return EIO;
1581     }
1582     afs_ntohuuid(&uuid);
1583     FS_HostUUID = uuid;
1584     if (read(fd, (char *)&nentries, sizeof(afs_int32)) != sizeof(afs_int32)) {
1585         ViceLog(0,
1586                 ("%s: Read of entries failed (%d)\n",
1587                  AFSDIR_SERVER_SYSID_FILEPATH, errno));
1588         return EIO;
1589     }
1590     if (nentries <= 0 || nentries > ADDRSPERSITE) {
1591         ViceLog(0,
1592                 ("%s: invalid num of interfaces: %d\n",
1593                  AFSDIR_SERVER_SYSID_FILEPATH, nentries));
1594         return EIO;
1595     }
1596     if (FS_HostAddr_cnt == 0) {
1597         FS_HostAddr_cnt = nentries;
1598         for (i = 0; i < nentries; i++) {
1599             if (read(fd, (char *)&FS_HostAddrs[i], sizeof(afs_int32)) !=
1600                 sizeof(afs_int32)) {
1601                 ViceLog(0,
1602                         ("%s: Read of addresses failed (%d)\n",
1603                          AFSDIR_SERVER_SYSID_FILEPATH, errno));
1604                 FS_HostAddr_cnt = 0;    /* reset it */
1605                 return EIO;
1606             }
1607         }
1608     } else {
1609         ViceLog(1,
1610                 ("%s: address list ignored (NetInfo/NetRestrict override)\n",
1611                  AFSDIR_SERVER_SYSID_FILEPATH));
1612     }
1613     close(fd);
1614     return 0;
1615 }
1616
1617 afs_int32
1618 WriteSysIdFile(void)
1619 {
1620     afs_int32 fd, i;
1621     struct versionStamp vsn;
1622     struct afs_stat status;
1623     afsUUID uuid;
1624
1625     if (!afs_stat(AFSDIR_SERVER_SYSID_FILEPATH, &status)) {
1626         /*
1627          * File exists; keep the old one around
1628          */
1629         rk_rename(AFSDIR_SERVER_SYSID_FILEPATH,
1630                   AFSDIR_SERVER_OLDSYSID_FILEPATH);
1631     }
1632     fd = afs_open(AFSDIR_SERVER_SYSID_FILEPATH, O_WRONLY | O_TRUNC | O_CREAT,
1633                   0666);
1634     if (fd < 1) {
1635         ViceLog(0,
1636                 ("%s: can't create (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH,
1637                  errno));
1638         return EIO;
1639     }
1640     vsn.magic = SYSIDMAGIC;
1641     vsn.version = 1;
1642     if ((i = write(fd, (char *)&vsn, sizeof(vsn))) != sizeof(vsn)) {
1643         ViceLog(0,
1644                 ("%s: write failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH,
1645                  errno));
1646         return EIO;
1647     }
1648     uuid = FS_HostUUID;
1649     afs_htonuuid(&uuid);
1650     if ((i =
1651          write(fd, (char *)&uuid,
1652                sizeof(struct afsUUID))) != sizeof(struct afsUUID)) {
1653         ViceLog(0,
1654                 ("%s: write of uuid failed (%d)\n",
1655                  AFSDIR_SERVER_SYSID_FILEPATH, errno));
1656         return EIO;
1657     }
1658     if ((i =
1659          write(fd, (char *)&FS_HostAddr_cnt,
1660                sizeof(afs_int32))) != sizeof(afs_int32)) {
1661         ViceLog(0,
1662                 ("%s: write of # of entries failed (%d)\n",
1663                  AFSDIR_SERVER_SYSID_FILEPATH, errno));
1664         return EIO;
1665     }
1666     for (i = 0; i < FS_HostAddr_cnt; i++) {
1667         if (write(fd, (char *)&FS_HostAddrs[i], sizeof(afs_int32)) !=
1668             sizeof(afs_int32)) {
1669             ViceLog(0,
1670                     ("%s: write of addresses failed (%d)\n",
1671                      AFSDIR_SERVER_SYSID_FILEPATH, errno));
1672             return EIO;
1673         }
1674     }
1675     close(fd);
1676     return 0;
1677 }
1678
1679 /*
1680  * defect 10966
1681  * This routine sets up the buffers for the VL_RegisterAddrs RPC. All addresses
1682  * in FS_HostAddrs[] are in NBO, while the RPC treats them as a "blob" of data
1683  * and so we need to convert each of them into HBO which is what the extra
1684  * array called FS_HostAddrs_HBO is used here.
1685  */
1686 static afs_int32
1687 Do_VLRegisterRPC(void)
1688 {
1689     int code;
1690     bulkaddrs addrs;
1691     afs_uint32 FS_HostAddrs_HBO[ADDRSPERSITE];
1692     int i = 0;
1693
1694     for (i = 0; i < FS_HostAddr_cnt; i++)
1695         FS_HostAddrs_HBO[i] = ntohl(FS_HostAddrs[i]);
1696     addrs.bulkaddrs_len = FS_HostAddr_cnt;
1697     addrs.bulkaddrs_val = (afs_uint32 *) FS_HostAddrs_HBO;
1698     code = ubik_VL_RegisterAddrs(cstruct, 0, &FS_HostUUID, 0, &addrs);
1699     if (code) {
1700         if (code == VL_MULTIPADDR) {
1701             ViceLog(0,
1702                     ("VL_RegisterAddrs rpc failed; The IP address exists on a different server; repair it\n"));
1703             ViceLog(0,
1704                     ("VL_RegisterAddrs rpc failed; See VLLog for details\n"));
1705             return code;
1706         } else if (code == RXGEN_OPCODE) {
1707             ViceLog(0,
1708                     ("vlserver doesn't support VL_RegisterAddrs rpc; ignored\n"));
1709             FS_registered = 2;  /* So we don't have to retry in the gc daemon */
1710         } else {
1711             ViceLog(0,
1712                     ("VL_RegisterAddrs rpc failed; will retry periodically (code=%d, err=%d)\n",
1713                      code, errno));
1714             FS_registered = 1;  /* Retry in the gc daemon */
1715         }
1716     } else {
1717         FS_registered = 2;      /* So we don't have to retry in the gc daemon */
1718         WriteSysIdFile();
1719     }
1720
1721     return 0;
1722 }
1723
1724 afs_int32
1725 SetupVL(void)
1726 {
1727     afs_int32 code;
1728
1729     if (AFSDIR_SERVER_NETRESTRICT_FILEPATH || AFSDIR_SERVER_NETINFO_FILEPATH) {
1730         /*
1731          * Find addresses we are supposed to register as per the netrestrict
1732          * and netinfo files (/usr/afs/local/NetInfo and
1733          * /usr/afs/local/NetRestict)
1734          */
1735         char reason[1024];
1736         afs_int32 code;
1737
1738         code = afsconf_ParseNetFiles(FS_HostAddrs, NULL, NULL,
1739                                      ADDRSPERSITE, reason,
1740                                      AFSDIR_SERVER_NETINFO_FILEPATH,
1741                                      AFSDIR_SERVER_NETRESTRICT_FILEPATH);
1742         if (code < 0) {
1743             ViceLog(0, ("Can't register any valid addresses: %s\n", reason));
1744             exit(1);
1745         }
1746         FS_HostAddr_cnt = (afs_uint32) code;
1747     } else
1748     {
1749         FS_HostAddr_cnt = rx_getAllAddr(FS_HostAddrs, ADDRSPERSITE);
1750     }
1751
1752     if (FS_HostAddr_cnt == 1 && rxBind == 1)
1753         code = FS_HostAddrs[0];
1754     else
1755         code = htonl(INADDR_ANY);
1756     return code;
1757 }
1758
1759 afs_int32
1760 InitVL(struct afsconf_dir *dir)
1761 {
1762     afs_int32 code;
1763
1764     /*
1765      * If this fails, it's because something major is wrong, and is not
1766      * likely to be time dependent.
1767      */
1768     code = vl_Initialize(dir);
1769     if (code != 0) {
1770         ViceLog(0,
1771                 ("Couldn't initialize volume location library; code=%d.\n", code));
1772         return code;
1773     }
1774
1775     /* Read or create the sysid file and register the fileserver's
1776      * IP addresses with the vlserver.
1777      */
1778     code = ReadSysIdFile();
1779     if (code) {
1780         /* Need to create the file */
1781         ViceLog(0, ("Creating new SysID file\n"));
1782         if ((code = afs_uuid_create(&FS_HostUUID))) {
1783             ViceLog(0, ("Failed to create new uuid: %d\n", code));
1784             exit(1);
1785         }
1786     }
1787     /* A good sysid file exists; inform the vlserver. If any conflicts,
1788      * we always use the latest interface available as the real truth.
1789      */
1790
1791     code = Do_VLRegisterRPC();
1792     return code;
1793 }
1794
1795 int
1796 main(int argc, char *argv[])
1797 {
1798     afs_int32 code;
1799     char tbuffer[32];
1800     struct rx_securityClass **securityClasses;
1801     afs_int32 numClasses;
1802     struct rx_service *tservice;
1803     pthread_t serverPid;
1804     pthread_attr_t tattr;
1805     struct hostent *he;
1806     int minVnodesRequired;      /* min size of vnode cache */
1807 #ifndef AFS_NT40_ENV
1808     struct rlimit rlim;         /* max number of open file descriptors */
1809 #endif
1810     int curLimit;
1811     time_t t;
1812     struct tm tm;
1813     afs_uint32 rx_bindhost;
1814     VolumePackageOptions opts;
1815
1816 #ifdef  AFS_AIX32_ENV
1817     struct sigaction nsa;
1818
1819     sigemptyset(&nsa.sa_mask);
1820     nsa.sa_handler = SIG_DFL;
1821     nsa.sa_flags = SA_FULLDUMP;
1822     sigaction(SIGABRT, &nsa, NULL);
1823     sigaction(SIGSEGV, &nsa, NULL);
1824 #endif
1825     osi_audit_init();
1826
1827     /* Initialize dirpaths */
1828     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
1829 #ifdef AFS_NT40_ENV
1830         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
1831 #endif
1832         fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
1833                 argv[0]);
1834         exit(2);
1835     }
1836     /* set ihandle package defaults prior to parsing args */
1837     ih_PkgDefaults();
1838
1839     /* check for the parameter file */
1840     CheckParms();
1841
1842     if (ParseArgs(argc, argv)) {
1843         exit(-1);
1844     }
1845     opr_mutex_init(&fileproc_glock_mutex);
1846
1847 #ifdef AFS_SGI_VNODE_GLUE
1848     if (afs_init_kernel_config(-1) < 0) {
1849         printf
1850             ("Can't determine NUMA configuration, not starting fileserver.\n");
1851         exit(1);
1852     }
1853 #endif
1854     FS_configPath = strdup(AFSDIR_SERVER_ETC_DIRPATH);
1855
1856     confDir = afsconf_Open(FS_configPath);
1857     if (!confDir) {
1858         fprintf(stderr, "Unable to open config directory %s\n",
1859                 FS_configPath);
1860         exit(-1);
1861     }
1862
1863     /* initialize audit user check */
1864     osi_audit_set_user_check(confDir, fs_IsLocalRealmMatch);
1865
1866     /* Open FileLog on stdout, stderr, fd 1 and fd2 (for perror), sigh. */
1867 #ifndef AFS_NT40_ENV
1868     serverLogSyslogTag = "fileserver";
1869 #endif
1870     OpenLog(AFSDIR_SERVER_FILELOG_FILEPATH);
1871     SetupLogSignals();
1872
1873     LogCommandLine(argc, argv, "starting", "", "File server", FSLog);
1874
1875 #if !defined(AFS_NT40_ENV)
1876     /* initialize the pthread soft signal handler thread */
1877     softsig_init();
1878 #endif
1879
1880     /* install signal handlers for controlling the fileserver process */
1881     ResetCheckSignal();         /* set CheckSignal_Signal() sig handler */
1882     ResetCheckDescriptors();    /* set CheckDescriptors_Signal() sig handler */
1883
1884 #if defined(AFS_SGI_ENV)
1885     /* give this guy a non-degrading priority so help busy servers */
1886     schedctl(NDPRI, 0, NDPNORMMAX);
1887     if (SawLock)
1888         plock(PROCLOCK);
1889 #elif !defined(AFS_NT40_ENV)
1890     nice(-5);                   /* TODO: */
1891 #endif
1892     DInit(buffs);
1893 #ifdef AFS_DEMAND_ATTACH_FS
1894     FS_STATE_INIT;
1895 #endif
1896
1897 #ifdef AFS_NT40_ENV
1898     if (afs_winsockInit() < 0) {
1899         ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
1900         ViceLog(0, ("File server failed to intialize winsock.\n"));
1901         exit(1);
1902     }
1903 #endif
1904     CheckAdminName();
1905
1906     /* if we support more than 16 threads, then we better have the ability
1907      ** to keep open a large number of files simultaneously
1908      */
1909 #if     defined(AFS_AIX_ENV) && !defined(AFS_AIX42_ENV)
1910     curLimit = OPEN_MAX;        /* for pre AIX 4.2 systems */
1911 #elif defined(AFS_NT40_ENV)
1912     curLimit = NT_OPEN_MAX;     /* open file descriptor limit on NT */
1913 #else
1914
1915     curLimit = 0;               /* the number of open file descriptors */
1916     code = getrlimit(RLIMIT_NOFILE, &rlim);
1917     if (code == 0) {
1918         curLimit = rlim.rlim_cur;
1919         rlim.rlim_cur = rlim.rlim_max;
1920         code = setrlimit(RLIMIT_NOFILE, &rlim);
1921         if (code == 0)
1922             curLimit = rlim.rlim_max;
1923     }
1924     if (code != 0)
1925         ViceLog(0, ("Failed to increase open file limit, using default\n"));
1926
1927 #endif /* defined(AFS_AIX_ENV) && !defined(AFS_AIX42_ENV) */
1928
1929     curLimit -= 32;             /* leave a slack of 32 file descriptors */
1930     if (lwps > curLimit) {
1931         if (curLimit > 0)
1932             lwps = curLimit;
1933         else if (lwps > 16)
1934             lwps = 16;          /* default to a maximum of 16 threads */
1935
1936         /* tune the ihandle fd cache accordingly */
1937         if (vol_io_params.fd_max_cachesize < curLimit)
1938             vol_io_params.fd_max_cachesize = curLimit + 1;
1939
1940         ViceLog(0,
1941                 ("The system supports a max of %d open files and we are starting %d threads (ihandle fd cache is %d)\n",
1942                  curLimit, lwps, vol_io_params.fd_max_cachesize));
1943     }
1944
1945     /* Initialize volume support */
1946     if (!novbc) {
1947         V_BreakVolumeCallbacks = BreakVolumeCallBacksLater;
1948     }
1949
1950     SetLogThreadNumProgram( rx_GetThreadNum );
1951
1952     /* initialize libacl routines */
1953     acl_Initialize(ACL_VERSION);
1954
1955     /* initialize RX support */
1956 #ifndef AFS_NT40_ENV
1957     rxi_syscallp = viced_syscall;
1958 #endif
1959     rx_extraPackets = rxpackets;
1960     rx_extraQuota = 4;          /* for outgoing prserver calls from R threads */
1961     rx_SetBusyThreshold(busy_threshold, VBUSY);
1962     rx_SetCallAbortThreshold(abort_threshold);
1963     rx_SetConnAbortThreshold(abort_threshold);
1964 #ifdef AFS_XBSD_ENV
1965     stackSize = 128 * 1024;
1966 #else
1967     stackSize = lwps * 4000;
1968     if (stackSize < 32000)
1969         stackSize = 32000;
1970     else if (stackSize > 44000)
1971         stackSize = 44000;
1972 #endif
1973 #if defined(AFS_HPUX_ENV) || defined(AFS_SUN_ENV) || defined(AFS_SGI51_ENV) || defined(AFS_XBSD_ENV)
1974     rx_SetStackSize(1, stackSize);
1975 #endif
1976     if (udpBufSize)
1977         rx_SetUdpBufSize(udpBufSize);   /* set the UDP buffer size for receive */
1978     rx_bindhost = SetupVL();
1979
1980     if (rx_InitHost(rx_bindhost, (int)htons(7000)) < 0) {
1981         ViceLog(0, ("Cannot initialize RX\n"));
1982         exit(1);
1983     }
1984     if (!rxJumbograms) {
1985         /* Don't send and don't allow 3.4 clients to send jumbograms. */
1986         rx_SetNoJumbo();
1987     }
1988     if (rxMaxMTU != -1) {
1989         if (rx_SetMaxMTU(rxMaxMTU) != 0) {
1990             ViceLog(0, ("rxMaxMTU %d is invalid\n", rxMaxMTU));
1991             exit(1);
1992         }
1993     }
1994     rx_GetIFInfo();
1995     rx_SetRxDeadTime(30);
1996     afsconf_SetSecurityFlags(confDir, AFSCONF_SECOPTS_ALWAYSENCRYPT);
1997     afsconf_BuildServerSecurityObjects(confDir, &securityClasses, &numClasses);
1998
1999     tservice = rx_NewServiceHost(rx_bindhost,  /* port */ 0, /* service id */
2000                                  1,     /*service name */
2001                                  "AFS",
2002                                  securityClasses, numClasses,
2003                                  RXAFS_ExecuteRequest);
2004     if (!tservice) {
2005         ViceLog(0,
2006                 ("Failed to initialize RX, probably two servers running.\n"));
2007         exit(-1);
2008     }
2009     if (rxkadDisableDotCheck) {
2010         rx_SetSecurityConfiguration(tservice, RXS_CONFIG_FLAGS,
2011                                     (void *)RXS_CONFIG_FLAGS_DISABLE_DOTCHECK);
2012     }
2013     rx_SetMinProcs(tservice, 3);
2014     rx_SetMaxProcs(tservice, lwps);
2015     rx_SetCheckReach(tservice, 1);
2016     rx_SetServerIdleDeadErr(tservice, VNOSERVICE);
2017
2018     tservice =
2019         rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats", securityClasses,
2020                       numClasses, RXSTATS_ExecuteRequest);
2021     if (!tservice) {
2022         ViceLog(0, ("Failed to initialize rpc stat service.\n"));
2023         exit(-1);
2024     }
2025     rx_SetMinProcs(tservice, 2);
2026     rx_SetMaxProcs(tservice, 4);
2027
2028     /*
2029      * Enable RX hot threads, which allows the listener thread to trade
2030      * places with an idle thread and moves the context switch from listener
2031      * to worker out of the critical path.
2032      */
2033     rx_EnableHotThread();
2034
2035     /* Some rx debugging */
2036     if (rxlog || eventlog) {
2037         debugFile = afs_fopen("rx_dbg", "w");
2038         if (rxlog)
2039             rx_debugFile = debugFile;
2040         if (eventlog)
2041             rxevent_debugFile = debugFile;
2042     }
2043
2044     init_sys_error_to_et();     /* Set up error table translation */
2045     h_InitHostPackage();        /* set up local cellname and realmname */
2046     InitCallBack(numberofcbs);
2047     ClearXStatValues();
2048
2049     code = InitVL(confDir);
2050     if (code && code != VL_MULTIPADDR) {
2051         ViceLog(0, ("Fatal error in library initialization, exiting!!\n"));
2052         exit(1);
2053     }
2054
2055     code = InitPR();
2056     if (code && code != -1) {
2057         ViceLog(0, ("Fatal error in protection initialization, exiting!!\n"));
2058         exit(1);
2059     }
2060
2061     /* allow super users to manage RX statistics */
2062     rx_SetRxStatUserOk(viced_SuperUser);
2063
2064     opr_cv_init(&fsync_cond);
2065     opr_mutex_init(&fsync_glock_mutex);
2066
2067 #if !defined(AFS_DEMAND_ATTACH_FS)
2068     /*
2069      * For DAFS, we do not start the Rx server threads until after
2070      * the volume package is initialized, and fileserver state is
2071      * restored.  This is necessary in order to keep host and callback
2072      * package state pristine until we have a chance to restore state.
2073      *
2074      * Furthermore, startup latency is much lower with dafs, so this
2075      * shouldn't pose a serious problem.
2076      */
2077     rx_StartServer(0);          /* now start handling requests */
2078 #endif
2079
2080     /* we ensure that there is enough space in the vnode buffer to satisfy
2081      ** requests from all concurrent threads.
2082      ** the maximum number of vnodes used by a single thread at any one time
2083      ** is three ( "link" uses three vnodes simultaneously, one vLarge and
2084      ** two vSmall for linking files and two vLarge and one vSmall for linking
2085      ** files  ) : dhruba
2086      */
2087     minVnodesRequired = 2 * lwps + 1;
2088     if (minVnodesRequired > nSmallVns) {
2089         nSmallVns = minVnodesRequired;
2090         ViceLog(0,
2091                 ("Overriding -s command line parameter with %d\n",
2092                  nSmallVns));
2093     }
2094     if (minVnodesRequired > large) {
2095         large = minVnodesRequired;
2096         ViceLog(0, ("Overriding -l command line parameter with %d\n", large));
2097     }
2098
2099     /* We now do this after getting the listener up and running, so that client
2100      * connections don't timeout (maybe) if a file server is restarted, since it
2101      * will be available "real soon now".  Worry about whether we can satisfy the
2102      * calls in the volume package itself.
2103      */
2104     VOptDefaults(fileServer, &opts);
2105     opts.nLargeVnodes = large;
2106     opts.nSmallVnodes = nSmallVns;
2107     opts.volcache = volcache;
2108     opts.unsafe_attach = unsafe_attach;
2109     if (offline_timeout != -1) {
2110         opts.interrupt_rxcall = rx_InterruptCall;
2111         opts.offline_timeout = offline_timeout;
2112     }
2113     if (offline_shutdown_timeout == -1) {
2114         /* default to -offline-timeout, if shutdown-specific timeout is not
2115          * specified */
2116         opts.offline_shutdown_timeout = offline_timeout;
2117     } else {
2118         opts.interrupt_rxcall = rx_InterruptCall;
2119         opts.offline_shutdown_timeout = offline_shutdown_timeout;
2120     }
2121
2122     if (VInitVolumePackage2(fileServer, &opts)) {
2123         ViceLog(0,
2124                 ("Shutting down: errors encountered initializing volume package\n"));
2125         VShutdown();
2126         exit(1);
2127     }
2128
2129     /* Install handler to catch the shutdown signal;
2130      * bosserver assumes SIGQUIT shutdown
2131      */
2132 #if !defined(AFS_NT40_ENV)
2133     softsig_signal(SIGQUIT, ShutDown_Signal);
2134 #else
2135     (void)signal(SIGQUIT, ShutDown_Signal);
2136 #endif
2137
2138     if (VInitAttachVolumes(fileServer)) {
2139         ViceLog(0,
2140                 ("Shutting down: errors encountered initializing volume package\n"));
2141         VShutdown();
2142         exit(1);
2143     }
2144
2145 #ifdef AFS_DEMAND_ATTACH_FS
2146     if (fs_state.options.fs_state_restore) {
2147         /*
2148          * demand attach fs
2149          * restore fileserver state */
2150         fs_stateRestore();
2151     }
2152     rx_StartServer(0);  /* now start handling requests */
2153 #endif /* AFS_DEMAND_ATTACH_FS */
2154
2155     /*
2156      * We are done calling fopen/fdopen. It is safe to use a large
2157      * of the file descriptor cache.
2158      */
2159     ih_UseLargeCache();
2160
2161     ViceLog(5, ("Starting pthreads\n"));
2162     opr_Verify(pthread_attr_init(&tattr) == 0);
2163     opr_Verify(pthread_attr_setdetachstate(&tattr,
2164                                            PTHREAD_CREATE_DETACHED) == 0);
2165
2166     opr_Verify(pthread_create(&serverPid, &tattr, FiveMinuteCheckLWP,
2167                               &fiveminutes) == 0);
2168     opr_Verify(pthread_create(&serverPid, &tattr, HostCheckLWP,
2169                               &fiveminutes) == 0);
2170     opr_Verify(pthread_create(&serverPid, &tattr, FsyncCheckLWP,
2171                               &fiveminutes) == 0);
2172
2173     gettimeofday(&tp, 0);
2174
2175     /*
2176      * Figure out the FileServer's name and primary address.
2177      */
2178     ViceLog(0, ("Getting FileServer name...\n"));
2179     code = gethostname(FS_HostName, 64);
2180     if (code) {
2181         ViceLog(0, ("gethostname() failed\n"));
2182     }
2183     ViceLog(0, ("FileServer host name is '%s'\n", FS_HostName));
2184
2185     ViceLog(0, ("Getting FileServer address...\n"));
2186     he = gethostbyname(FS_HostName);
2187     if (!he) {
2188         ViceLog(0, ("Can't find address for FileServer '%s'\n", FS_HostName));
2189     } else {
2190         char hoststr[16];
2191         memcpy(&FS_HostAddr_NBO, he->h_addr, 4);
2192         (void)afs_inet_ntoa_r(FS_HostAddr_NBO, hoststr);
2193         FS_HostAddr_HBO = ntohl(FS_HostAddr_NBO);
2194         ViceLog(0,
2195                 ("FileServer %s has address %s (0x%x or 0x%x in host byte order)\n",
2196                  FS_HostName, hoststr, FS_HostAddr_NBO, FS_HostAddr_HBO));
2197     }
2198
2199     t = tp.tv_sec;
2200     strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2201              localtime_r(&t, &tm));
2202     ViceLog(0, ("File Server started %s\n", tbuffer));
2203     afs_FullPerfStats.det.epoch.tv_sec = StartTime = tp.tv_sec;
2204     while (1) {
2205         sleep(1000);            /* long time */
2206     }
2207     return 0;
2208 }