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