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