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