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