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