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