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