viced: Enforce lwps limit for -L
[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 #include <afs/procmgmt.h>
25 #include <roken.h>
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <errno.h>
30 #include <string.h>
31 #include <sys/types.h>
32 #include <afs/procmgmt.h>       /* signal(), kill(), wait(), etc. */
33 #include <sys/stat.h>
34 #include <fcntl.h>
35 #ifdef HAVE_STDINT_H
36 # include <stdint.h>
37 #endif
38 #ifdef AFS_NT40_ENV
39 #include <io.h>
40 #include <windows.h>
41 #include <WINNT/afsevent.h>
42 #else
43 #include <sys/file.h>
44 #include <netinet/in.h>
45 #include <netdb.h>
46 #include <unistd.h>             /* sysconf() */
47
48 #ifndef ITIMER_REAL
49 #include <sys/time.h>
50 #endif /* ITIMER_REAL */
51 #include <sys/resource.h>
52 #endif /* AFS_NT40_ENV */
53 #include <afs/stds.h>
54 #undef SHARED
55 #include <rx/xdr.h>
56 #include <afs/nfs.h>
57 #include <afs/afs_assert.h>
58 #include <lwp.h>
59 #include <lock.h>
60 #include <afs/ptclient.h>
61 #include <afs/afsint.h>
62 #include <afs/vldbint.h>
63 #include <afs/errors.h>
64 #include <afs/ihandle.h>
65 #include <afs/vnode.h>
66 #include <afs/volume.h>
67 #include <afs/auth.h>
68 #include <afs/cellconfig.h>
69 #include <afs/acl.h>
70 #include <afs/prs_fs.h>
71 #include <rx/rx.h>
72 #include <rx/rxstat.h>
73 #include <afs/keys.h>
74 #include <afs/afs_args.h>
75 #include <afs/vlserver.h>
76 #include <afs/afsutil.h>
77 #include <afs/fileutil.h>
78 #include <afs/ptuser.h>
79 #include <afs/audit.h>
80 #include <afs/partition.h>
81 #include <afs/dir.h>
82 #ifndef AFS_NT40_ENV
83 #include <afs/netutils.h>
84 #endif
85 #include "viced_prototypes.h"
86 #include "viced.h"
87 #include "host.h"
88 #ifdef AFS_PTHREAD_ENV
89 #include <afs/softsig.h>
90 #endif
91 #if defined(AFS_SGI_ENV)
92 #include "sys/schedctl.h"
93 #include "sys/lock.h"
94 #endif
95 #include <rx/rx_globals.h>
96
97 #ifdef O_LARGEFILE
98 #define afs_stat        stat64
99 #define afs_fstat       fstat64
100 #define afs_open        open64
101 #define afs_fopen       fopen64
102 #else /* !O_LARGEFILE */
103 #define afs_stat        stat
104 #define afs_fstat       fstat
105 #define afs_open        open
106 #define afs_fopen       fopen
107 #endif /* !O_LARGEFILE */
108
109 extern int etext;
110
111 void *ShutDown(void *);
112 static void ClearXStatValues(void);
113 static void NewParms(int);
114 static void PrintCounters(void);
115 static void ResetCheckDescriptors(void);
116 static void ResetCheckSignal(void);
117 static void *CheckSignal(void *);
118
119 static afs_int32 Do_VLRegisterRPC(void);
120
121 int eventlog = 0, rxlog = 0;
122 FILE *debugFile;
123
124 #ifdef AFS_PTHREAD_ENV
125 pthread_mutex_t fsync_glock_mutex;
126 pthread_cond_t fsync_cond;
127 #else
128 char fsync_wait[1];
129 #endif /* AFS_PTHREAD_ENV */
130
131 #ifdef AFS_NT40_ENV
132 #define NT_OPEN_MAX    1024     /* This is an arbitrary no. we came up with for
133                                  * now. We hope this will be replaced by a more
134                                  * intelligent estimate later. */
135 #endif
136
137 int SystemId;                   /* ViceID of "Administrators" */
138 int SystemAnyUser;              /* Viceid of "System:AnyUser" */
139 prlist SystemAnyUserCPS;        /* CPS for "system:AnyUser */
140 int AnonymousID = 0;            /* ViceId of "Anonymous" */
141 prlist AnonCPS;                 /* CPS for "Anonymous" */
142
143 struct afsconf_dir *confDir;    /* Configuration dir object */
144
145 int restartMode = RESTART_ORDINARY;
146
147 /*
148  * Home for the performance statistics.
149  */
150 struct afs_PerfStats afs_perfstats;
151
152 extern int LogLevel;
153 extern int Statistics;
154
155 int busyonrst = 1;
156 int timeout = 30;
157 int SawSpare;
158 int SawPctSpare;
159 int debuglevel = 0;
160 int printBanner = 0;
161 int rxJumbograms = 0;           /* default is to not send and receive jumbograms. */
162 int rxBind = 0;         /* don't bind */
163 int rxkadDisableDotCheck = 0;      /* disable check for dot in principal name */
164 int rxMaxMTU = -1;
165 afs_int32 implicitAdminRights = PRSFS_LOOKUP;   /* The ADMINISTER right is
166                                                  * already implied */
167 afs_int32 readonlyServer = 0;
168
169 int stack = 24;
170 int stackSize = 24000;
171 int fiveminutes = 300;          /* 5 minutes.  Change this for debugging only */
172 int CurrentConnections = 0;
173 int hostaclRefresh = 7200;      /* refresh host clients' acls every 2 hrs */
174 #if defined(AFS_SGI_ENV)
175 int SawLock;
176 #endif
177 time_t StartTime;
178
179 /**
180  * seconds to wait until forcing a panic during ShutDownAndCore(PANIC)
181  * in case we get stuck.
182  */
183 #ifdef AFS_DEMAND_ATTACH_FS
184 static int panic_timeout = 2 * 60;
185 #else
186 static int panic_timeout = 30 * 60;
187 #endif
188
189 int rxpackets = 150;            /* 100 */
190 int nSmallVns = 400;            /* 200 */
191 int large = 400;                /* 200 */
192 int volcache = 400;             /* 400 */
193 int numberofcbs = 60000;        /* 60000 */
194 int lwps = 9;                   /* 6 */
195 int buffs = 90;                 /* 70 */
196 int novbc = 0;                  /* Enable Volume Break calls */
197 int busy_threshold = 600;
198 int abort_threshold = 10;
199 int udpBufSize = 0;             /* UDP buffer size for receive */
200 int sendBufSize = 16384;        /* send buffer size */
201 int saneacls = 0;               /* Sane ACLs Flag */
202 static int unsafe_attach = 0;   /* avoid inUse check on vol attach? */
203 static int offline_timeout = -1; /* -offline-timeout option */
204 static int offline_shutdown_timeout = -1; /* -offline-shutdown-timeout option */
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     CV_INIT(&fs_state.worker_done_cv, "worker done", CV_DEFAULT, 0);
273     osi_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     CV_BROADCAST(&fs_state.worker_done_cv);
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     CV_BROADCAST(&fs_state.worker_done_cv);
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 = CV_TIMEDWAIT(&fsync_cond, &fsync_glock_mutex,
601                             &fsync_next);
602         if (code != 0 && code != ETIMEDOUT)
603             ViceLog(0, ("pthread_cond_timedwait returned %d\n", code));
604 #else /* AFS_PTHREAD_ENV */
605         if ((code = LWP_WaitProcess(fsync_wait)) != LWP_SUCCESS)
606             ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
607 #endif /* AFS_PTHREAD_ENV */
608         FSYNC_UNLOCK;
609
610 #ifdef AFS_DEMAND_ATTACH_FS
611         FS_STATE_WRLOCK;
612         if (fs_state.mode != FS_MODE_NORMAL) {
613             break;
614         }
615         fs_state.FsyncCheckLWP_tranquil = 0;
616         FS_STATE_UNLOCK;
617 #endif /* AFS_DEMAND_ATTACH_FS */
618
619         ViceLog(2, ("Checking for fsync events\n"));
620         do {
621             code = BreakLaterCallBacks();
622         } while (code != 0);
623 #ifdef AFS_DEMAND_ATTACH_FS
624         FS_STATE_WRLOCK;
625 #endif
626     }
627 #ifdef AFS_DEMAND_ATTACH_FS
628     fs_state.FsyncCheckLWP_tranquil = 1;
629     FS_LOCK;
630     CV_BROADCAST(&fs_state.worker_done_cv);
631     FS_UNLOCK;
632     FS_STATE_UNLOCK;
633 #endif /* AFS_DEMAND_ATTACH_FS */
634     return NULL;
635 }
636
637 /*------------------------------------------------------------------------
638  * PRIVATE ClearXStatValues
639  *
640  * Description:
641  *      Initialize all of the values collected via the xstat
642  *      interface.
643  *
644  * Arguments:
645  *      None.
646  *
647  * Returns:
648  *      Nothing.
649  *
650  * Environment:
651  *      Must be called during File Server initialization.
652  *
653  * Side Effects:
654  *      As advertised.
655  *------------------------------------------------------------------------*/
656
657 static void
658 ClearXStatValues(void)
659 {                               /*ClearXStatValues */
660
661     struct fs_stats_opTimingData *opTimeP;      /*Ptr to timing struct */
662     struct fs_stats_xferData *opXferP;  /*Ptr to xfer struct */
663     int i;                      /*Loop counter */
664
665     /*
666      * Zero all xstat-related structures.
667      */
668     memset((&afs_perfstats), 0, sizeof(struct afs_PerfStats));
669 #if FS_STATS_DETAILED
670     memset((&afs_FullPerfStats), 0,
671            sizeof(struct fs_stats_FullPerfStats));
672
673     /*
674      * That's not enough.  We have to set reasonable minima for
675      * time and xfer values in the detailed stats.
676      */
677     opTimeP = &(afs_FullPerfStats.det.rpcOpTimes[0]);
678     for (i = 0; i < FS_STATS_NUM_RPC_OPS; i++, opTimeP++)
679         opTimeP->minTime.tv_sec = 999999;
680
681     opXferP = &(afs_FullPerfStats.det.xferOpTimes[0]);
682     for (i = 0; i < FS_STATS_NUM_XFER_OPS; i++, opXferP++) {
683         opXferP->minTime.tv_sec = 999999;
684         opXferP->minBytes = 999999999;
685     }
686
687     /*
688      * There's more.  We have to set our unique system identifier, as
689      * declared in param.h.  If such a thing is not defined, we bitch
690      * and declare ourselves to be an unknown system type.
691      */
692 #ifdef SYS_NAME_ID
693     afs_perfstats.sysname_ID = SYS_NAME_ID;
694 #else
695 #ifndef AFS_NT40_ENV
696     ViceLog(0, ("Sys name ID constant not defined in param.h!!\n"));
697     ViceLog(0, ("[Choosing ``undefined'' sys name ID.\n"));
698 #endif
699     afs_perfstats.sysname_ID = SYS_NAME_ID_UNDEFINED;
700 #endif /* SYS_NAME_ID */
701 #endif
702
703 }                               /*ClearXStatValues */
704
705 int CopyOnWrite_calls = 0, CopyOnWrite_off0 = 0, CopyOnWrite_size0 = 0;
706 afs_fsize_t CopyOnWrite_maxsize = 0;
707
708 static void
709 PrintCounters(void)
710 {
711     int dirbuff, dircall, dirio;
712     struct timeval tpl;
713     int workstations, activeworkstations, delworkstations;
714     int processSize = 0;
715     char tbuffer[32];
716 #ifdef AFS_DEMAND_ATTACH_FS
717     int stats_flags = 0;
718 #endif
719
720     FT_GetTimeOfDay(&tpl, 0);
721     Statistics = 1;
722     ViceLog(0,
723             ("Vice was last started at %s\n",
724              afs_ctime(&StartTime, tbuffer, sizeof(tbuffer))));
725
726 #ifdef AFS_DEMAND_ATTACH_FS
727     if (LogLevel >= 125) {
728         stats_flags = VOL_STATS_PER_CHAIN2;
729     } else if (LogLevel >= 25) {
730         stats_flags = VOL_STATS_PER_CHAIN;
731     }
732     VPrintExtendedCacheStats(stats_flags);
733 #endif
734     VPrintCacheStats();
735     VPrintDiskStats();
736     DStat(&dirbuff, &dircall, &dirio);
737     ViceLog(0,
738             ("With %d directory buffers; %d reads resulted in %d read I/Os\n",
739              dirbuff, dircall, dirio));
740     rx_PrintStats(stderr);
741     audit_PrintStats(stderr);
742     h_PrintStats();
743     PrintCallBackStats();
744 #ifdef AFS_NT40_ENV
745     processSize = -1;           /* TODO: */
746 #else
747     processSize = (int)((long)sbrk(0) >> 10);
748 #endif
749     ViceLog(0,
750             ("There are %d connections, process size %d\n",
751              CurrentConnections, processSize));
752     h_GetWorkStats(&workstations, &activeworkstations, &delworkstations,
753                    tpl.tv_sec - 15 * 60);
754     ViceLog(0,
755             ("There are %d workstations, %d are active (req in < 15 mins), %d marked \"down\"\n",
756              workstations, activeworkstations, delworkstations));
757     ViceLog(0, ("CopyOnWrite: calls %d off0 %d size0 %d maxsize 0x%llx\n",
758                 CopyOnWrite_calls, CopyOnWrite_off0, CopyOnWrite_size0, CopyOnWrite_maxsize));
759
760     Statistics = 0;
761
762 }                               /*PrintCounters */
763
764
765
766 static void *
767 CheckSignal(void *unused)
768 {
769     if (FS_registered > 0) {
770         /*
771          * We have proper ip addresses; tell the vlserver what we got; the following
772          * routine will do the proper reporting for us
773          */
774         Do_VLRegisterRPC();
775     }
776     h_DumpHosts();
777     h_PrintClients();
778     DumpCallBackState();
779     PrintCounters();
780     ResetCheckSignal();
781     return 0;
782 }                               /*CheckSignal */
783
784 static void *
785 ShutdownWatchdogLWP(void *unused)
786 {
787     sleep(panic_timeout);
788     ViceLog(0, ("ShutdownWatchdogLWP: Failed to shutdown and panic "
789                 "within %d seconds; forcing panic\n", panic_timeout));
790     osi_Panic("ShutdownWatchdogLWP: Failed to shutdown and panic "
791               "within %d seconds; forcing panic\n", panic_timeout);
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         osi_Assert(pthread_attr_init(&tattr) == 0);
806         osi_Assert(pthread_create(&watchdogPid, &tattr, ShutdownWatchdogLWP, NULL) == 0);
807 #else
808         PROCESS watchdogPid;
809         osi_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                 CV_WAIT(&fs_state.worker_done_cv, &fileproc_glock_mutex);
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) /* XXX pass in file and line? */
897         osi_Panic("Panic requested\n");
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("[-offline-timeout <client RX timeout for offlining volumes>]", stdout);
974     fputs("[-offline-shutdown-timeout <RX timeout for offlining volumes during shutdown>]", stdout);
975 /*   fputs("[-enable_peer_stats] ", stdout); */
976 /*   fputs("[-enable_process_stats] ", stdout); */
977     fputs("[-help]\n", stdout);
978 /*
979     ViceLog(0, ("%s", buffer));
980 */
981
982     fflush(stdout);
983
984 }                               /*FlagMsg */
985
986
987 static afs_int32
988 ParseRights(char *arights)
989 {
990     afs_int32 mode = 0;
991     int i, len;
992     char tc;
993
994     if (!arights || !strcmp(arights, "")) {
995         printf("Missing list of mode bits on -implicit option\n");
996         return -1;
997     }
998     if (!strcmp(arights, "none"))
999         mode = 0;
1000     else if (!strcmp(arights, "read"))
1001         mode = PRSFS_READ | PRSFS_LOOKUP;
1002     else if (!strcmp(arights, "write"))
1003         mode =
1004             PRSFS_READ | PRSFS_LOOKUP | PRSFS_INSERT | PRSFS_DELETE |
1005             PRSFS_WRITE | PRSFS_LOCK;
1006     else if (!strcmp(arights, "all"))
1007         mode =
1008             PRSFS_READ | PRSFS_LOOKUP | PRSFS_INSERT | PRSFS_DELETE |
1009             PRSFS_WRITE | PRSFS_LOCK | PRSFS_ADMINISTER;
1010     else {
1011         len = strlen(arights);
1012         for (i = 0; i < len; i++) {
1013             tc = *arights++;
1014             if (tc == 'r')
1015                 mode |= PRSFS_READ;
1016             else if (tc == 'l')
1017                 mode |= PRSFS_LOOKUP;
1018             else if (tc == 'i')
1019                 mode |= PRSFS_INSERT;
1020             else if (tc == 'd')
1021                 mode |= PRSFS_DELETE;
1022             else if (tc == 'w')
1023                 mode |= PRSFS_WRITE;
1024             else if (tc == 'k')
1025                 mode |= PRSFS_LOCK;
1026             else if (tc == 'a')
1027                 mode |= PRSFS_ADMINISTER;
1028             else if (tc == 'A')
1029                 mode |= PRSFS_USR0;
1030             else if (tc == 'B')
1031                 mode |= PRSFS_USR1;
1032             else if (tc == 'C')
1033                 mode |= PRSFS_USR2;
1034             else if (tc == 'D')
1035                 mode |= PRSFS_USR3;
1036             else if (tc == 'E')
1037                 mode |= PRSFS_USR4;
1038             else if (tc == 'F')
1039                 mode |= PRSFS_USR5;
1040             else if (tc == 'G')
1041                 mode |= PRSFS_USR6;
1042             else if (tc == 'H')
1043                 mode |= PRSFS_USR7;
1044             else {
1045                 printf("Illegal -implicit rights character '%c'.\n", tc);
1046                 return -1;
1047             }
1048         }
1049     }
1050     return mode;
1051 }
1052
1053 /*
1054  * Limit MAX_FILESERVER_THREAD by the system limit on the number of
1055  * pthreads (sysconf(_SC_THREAD_THREADS_MAX)), if applicable and
1056  * available.
1057  *
1058  * AIX:         sysconf() limit is real
1059  * HP-UX:       sysconf() limit is real
1060  * IRIX:        sysconf() limit is apparently NOT real -- too small
1061  * DUX:         sysconf() limit is apparently NOT real -- too big
1062  * Linux:       sysconf() limit is apparently NOT real -- too big
1063  * Solaris:     no sysconf() limit
1064  */
1065 static int
1066 max_fileserver_thread(void)
1067 {
1068 #if defined(AFS_PTHREAD_ENV)
1069 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV)
1070     long ans;
1071
1072     ans = sysconf(_SC_THREAD_THREADS_MAX);
1073     if (0 < ans && ans < MAX_FILESERVER_THREAD)
1074         return (int)ans;
1075 #endif
1076 #endif /* defined(AFS_PTHREAD_ENV) */
1077     return MAX_FILESERVER_THREAD;
1078 }
1079
1080 /* from ihandle.c */
1081 extern ih_init_params vol_io_params;
1082
1083 static int
1084 ParseArgs(int argc, char *argv[])
1085 {
1086     int SawL = 0, SawS = 0, SawVC = 0;
1087     int Sawrxpck = 0, Sawsmall = 0, Sawlarge = 0, Sawcbs = 0, Sawlwps =
1088         0, Sawbufs = 0;
1089     int Sawbusy = 0;
1090     int i;
1091     int bufSize = 0;            /* temp variable to read in udp socket buf size */
1092     int lwps_max;
1093     char *auditFileName = NULL;
1094
1095     for (i = 1; i < argc; i++) {
1096         if (!strcmp(argv[i], "-d")) {
1097             if ((i + 1) >= argc) {
1098                 fprintf(stderr, "missing argument for -d\n");
1099                 return -1;
1100             }
1101             debuglevel = atoi(argv[++i]);
1102             LogLevel = debuglevel;
1103         } else if (!strcmp(argv[i], "-banner")) {
1104             printBanner = 1;
1105         } else if (!strcmp(argv[i], "-implicit")) {
1106             if ((i + 1) >= argc) {
1107                 fprintf(stderr, "missing argument for -implicit\n");
1108                 return -1;
1109             }
1110             implicitAdminRights = ParseRights(argv[++i]);
1111             if (implicitAdminRights < 0)
1112                 return implicitAdminRights;
1113         } else if (!strcmp(argv[i], "-readonly")) {
1114             readonlyServer = 1;
1115         } else if (!strcmp(argv[i], "-L")) {
1116             SawL = 1;
1117         } else if (!strcmp(argv[i], "-S")) {
1118             SawS = 1;
1119         } else if (!strcmp(argv[i], "-p")) {
1120             Sawlwps = 1;
1121             if ((i + 1) >= argc) {
1122                 fprintf(stderr, "missing argument for -p\n");
1123                 return -1;
1124             }
1125             lwps = atoi(argv[++i]);
1126         } else if (!strcmp(argv[i], "-b")) {
1127             Sawbufs = 1;
1128             if ((i + 1) >= argc) {
1129                 fprintf(stderr, "missing argument for -b\n");
1130                 return -1;
1131             }
1132             buffs = atoi(argv[++i]);
1133         } else if (!strcmp(argv[i], "-l")) {
1134             Sawlarge = 1;
1135             if ((i + 1) >= argc) {
1136                 fprintf(stderr, "missing argument for -l\n");
1137                 return -1;
1138             }
1139             large = atoi(argv[++i]);
1140         } else if (!strcmp(argv[i], "-vc")) {
1141             SawVC = 1;
1142             if ((i + 1) >= argc) {
1143                 fprintf(stderr, "missing argument for -vc\n");
1144                 return -1;
1145             }
1146             volcache = atoi(argv[++i]);
1147         } else if (!strcmp(argv[i], "-novbc")) {
1148             novbc = 1;
1149         } else if (!strcmp(argv[i], "-rxpck")) {
1150             Sawrxpck = 1;
1151             if ((i + 1) >= argc) {
1152                 fprintf(stderr, "missing argument for -rxpck\n");
1153                 return -1;
1154             }
1155             rxpackets = atoi(argv[++i]);
1156 #ifdef AFS_PTHREAD_ENV
1157         } else if (!strcmp(argv[i], "-vattachpar")) {
1158             if ((i + 1) >= argc) {
1159                 fprintf(stderr, "missing argument for %s\n", argv[i]);
1160                 return -1;
1161             }
1162             vol_attach_threads = atoi(argv[++i]);
1163 #endif /* AFS_PTHREAD_ENV */
1164         } else if (!strcmp(argv[i], "-vhandle-setaside")) {
1165             if ((i + 1) >= argc) {
1166                 fprintf(stderr, "missing argument for %s\n", argv[i]);
1167                 return -1;
1168             }
1169             vol_io_params.fd_handle_setaside = atoi(argv[++i]);
1170         } else if (!strcmp(argv[i], "-vhandle-max-cachesize")) {
1171             if ((i + 1) >= argc) {
1172                 fprintf(stderr, "missing argument for %s\n", argv[i]);
1173                 return -1;
1174             }
1175             vol_io_params.fd_max_cachesize = atoi(argv[++i]);
1176         } else if (!strcmp(argv[i], "-vhandle-initial-cachesize")) {
1177             if ((i + 1) >= argc) {
1178                 fprintf(stderr, "missing argument for %s\n", argv[i]);
1179                 return -1;
1180             }
1181             vol_io_params.fd_initial_cachesize = atoi(argv[++i]);
1182 #ifdef AFS_DEMAND_ATTACH_FS
1183         } else if (!strcmp(argv[i], "-fs-state-dont-save")) {
1184             fs_state.options.fs_state_save = 0;
1185         } else if (!strcmp(argv[i], "-fs-state-dont-restore")) {
1186             fs_state.options.fs_state_restore = 0;
1187         } else if (!strcmp(argv[i], "-fs-state-verify")) {
1188             if ((i + 1) >= argc) {
1189                 fprintf(stderr, "missing argument for %s\n", argv[i]);
1190                 return -1;
1191             }
1192             i++;
1193             if (!strcmp(argv[i], "none")) {
1194                 fs_state.options.fs_state_verify_before_save = 0;
1195                 fs_state.options.fs_state_verify_after_restore = 0;
1196             } else if (!strcmp(argv[i], "save")) {
1197                 fs_state.options.fs_state_verify_after_restore = 0;
1198             } else if (!strcmp(argv[i], "restore")) {
1199                 fs_state.options.fs_state_verify_before_save = 0;
1200             } else if (!strcmp(argv[i], "both")) {
1201                 /* default */
1202             } else {
1203                 fprintf(stderr, "invalid argument for %s\n", argv[i-1]);
1204                 return -1;
1205             }
1206         } else if (!strcmp(argv[i], "-vhashsize")) {
1207             int hashsize;
1208             if ((i + 1) >= argc) {
1209                 fprintf(stderr, "missing argument for %s\n", argv[i]);
1210                 return -1;
1211             }
1212             hashsize = atoi(argv[++i]);
1213             if (VSetVolHashSize(hashsize)) {
1214                 fprintf(stderr, "specified -vhashsize (%s) is invalid or out "
1215                                 "of range\n", argv[i]);
1216                 return -1;
1217             }
1218         } else if (!strcmp(argv[i], "-vlrudisable")) {
1219             VLRU_SetOptions(VLRU_SET_ENABLED, 0);
1220         } else if (!strcmp(argv[i], "-vlruthresh")) {
1221             if ((i + 1) >= argc) {
1222                 fprintf(stderr, "missing argument for %s\n", argv[i]);
1223                 return -1;
1224             }
1225             VLRU_SetOptions(VLRU_SET_THRESH, 60*atoi(argv[++i]));
1226         } else if (!strcmp(argv[i], "-vlruinterval")) {
1227             if ((i + 1) >= argc) {
1228                 fprintf(stderr, "missing argument for %s\n", argv[i]);
1229                 return -1;
1230             }
1231             VLRU_SetOptions(VLRU_SET_INTERVAL, atoi(argv[++i]));
1232         } else if (!strcmp(argv[i], "-vlrumax")) {
1233             if ((i + 1) >= argc) {
1234                 fprintf(stderr, "missing argument for %s\n", argv[i]);
1235                 return -1;
1236             }
1237             VLRU_SetOptions(VLRU_SET_MAX, atoi(argv[++i]));
1238         } else if (!strcmp(argv[i], "-unsafe-nosalvage")) {
1239             unsafe_attach = 1;
1240 #endif /* AFS_DEMAND_ATTACH_FS */
1241         } else if (!strcmp(argv[i], "-s")) {
1242             Sawsmall = 1;
1243             if ((i + 1) >= argc) {
1244                 fprintf(stderr, "missing argument for -s\n");
1245                 return -1;
1246             }
1247             nSmallVns = atoi(argv[++i]);
1248         } else if (!strcmp(argv[i], "-abortthreshold")) {
1249             if ((i + 1) >= argc) {
1250                 fprintf(stderr, "missing argument for -abortthreshold\n");
1251                 return -1;
1252             }
1253             abort_threshold = atoi(argv[++i]);
1254         } else if (!strcmp(argv[i], "-k")) {
1255             if ((i + 1) >= argc) {
1256                 fprintf(stderr, "missing argument for -k\n");
1257                 return -1;
1258             }
1259             stack = atoi(argv[++i]);
1260         }
1261 #if defined(AFS_SGI_ENV)
1262         else if (!strcmp(argv[i], "-lock")) {
1263             SawLock = 1;
1264         }
1265 #endif
1266         else if (!strcmp(argv[i], "-spare")) {
1267             if ((i + 1) >= argc) {
1268                 fprintf(stderr, "missing argument for -spare\n");
1269                 return -1;
1270             }
1271             BlocksSpare = atoi(argv[++i]);
1272             SawSpare = 1;
1273         } else if (!strcmp(argv[i], "-pctspare")) {
1274             if ((i + 1) >= argc) {
1275                 fprintf(stderr, "missing argument for -pctspare\n");
1276                 return -1;
1277             }
1278             PctSpare = atoi(argv[++i]);
1279             BlocksSpare = 0;    /* has non-zero default */
1280             SawPctSpare = 1;
1281         } else if (!strcmp(argv[i], "-w")) {
1282             if ((i + 1) >= argc) {
1283                 fprintf(stderr, "missing argument for -w\n");
1284                 return -1;
1285             }
1286             fiveminutes = atoi(argv[++i]);
1287         } else if (!strcmp(argv[i], "-hr")) {
1288             int hr;
1289             if ((i + 1) >= argc) {
1290                 fprintf(stderr, "missing argument for -hr\n");
1291                 return -1;
1292             }
1293             hr = atoi(argv[++i]);
1294             if ((hr < 1) || (hr > 36)) {
1295                 printf
1296                     ("host acl refresh interval of %d hours is invalid; hours must be between 1 and 36\n\n",
1297                      hr);
1298                 return -1;
1299             }
1300             hostaclRefresh = hr * 60 * 60;
1301         } else if (!strcmp(argv[i], "-rxdbg"))
1302             rxlog = 1;
1303         else if (!strcmp(argv[i], "-rxdbge"))
1304             eventlog = 1;
1305         else if (!strcmp(argv[i], "-cb")) {
1306             Sawcbs = 1;
1307             if ((i + 1) >= argc) {
1308                 fprintf(stderr, "missing argument for -cb\n");
1309                 return -1;
1310             }
1311             numberofcbs = atoi(argv[++i]);
1312             if ((numberofcbs < 10000) || (numberofcbs > 2147483647)) {
1313                 printf
1314                     ("number of cbs %d invalid; must be between 10000 and 2147483647\n",
1315                      numberofcbs);
1316                 return -1;
1317             }
1318         } else if (!strcmp(argv[i], "-busyat")) {
1319             Sawbusy = 1;
1320             if ((i + 1) >= argc) {
1321                 fprintf(stderr, "missing argument for -busyat\n");
1322                 return -1;
1323             }
1324             busy_threshold = atoi(argv[++i]);
1325             if (busy_threshold < 10) {
1326                 printf
1327                     ("Busy threshold %d is too low, will compute default.\n",
1328                      busy_threshold);
1329                 Sawbusy = 0;
1330             }
1331         } else if (!strcmp(argv[i], "-nobusy"))
1332             busyonrst = 0;
1333 #ifdef  AFS_AIX32_ENV
1334         else if (!strcmp(argv[i], "-m")) {
1335             extern int aixlow_water;
1336             if ((i + 1) >= argc) {
1337                 fprintf(stderr, "missing argument for -m\n");
1338                 return -1;
1339             }
1340             aixlow_water = atoi(argv[++i]);
1341             if ((aixlow_water < 0) || (aixlow_water > 30)) {
1342                 printf("space reserved %d% invalid; must be between 0-30%\n",
1343                        aixlow_water);
1344                 return -1;
1345             }
1346         }
1347 #endif
1348         else if (!strcmp(argv[i], "-nojumbo")) {
1349             rxJumbograms = 0;
1350         } else if (!strcmp(argv[i], "-jumbo")) {
1351             rxJumbograms = 1;
1352         } else if (!strcmp(argv[i], "-rxbind")) {
1353             rxBind = 1;
1354         } else if (!strcmp(argv[i], "-allow-dotted-principals")) {
1355             rxkadDisableDotCheck = 1;
1356         } else if (!strcmp(argv[i], "-rxmaxmtu")) {
1357             if ((i + 1) >= argc) {
1358                 fprintf(stderr, "missing argument for -rxmaxmtu\n");
1359                 return -1;
1360             }
1361             rxMaxMTU = atoi(argv[++i]);
1362             if ((rxMaxMTU < RX_MIN_PACKET_SIZE) ||
1363                 (rxMaxMTU > RX_MAX_PACKET_DATA_SIZE)) {
1364                 printf("rxMaxMTU %d%% invalid; must be between %d-%" AFS_SIZET_FMT "\n",
1365                        rxMaxMTU, RX_MIN_PACKET_SIZE,
1366                        RX_MAX_PACKET_DATA_SIZE);
1367                 return -1;
1368                 }
1369         } else if (!strcmp(argv[i], "-realm")) {
1370             extern char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
1371             extern int  num_lrealms;
1372             if ((i + 1) >= argc) {
1373                 fprintf(stderr, "missing argument for -realm\n");
1374                 return -1;
1375             }
1376             if (strlen(argv[++i]) >= AFS_REALM_SZ) {
1377                 printf
1378                     ("-realm argument must contain fewer than %d characters.\n",
1379                      AFS_REALM_SZ);
1380                 return -1;
1381             }
1382             if (num_lrealms == -1)
1383                 num_lrealms = 0;
1384             if (num_lrealms >= AFS_NUM_LREALMS) {
1385                 printf
1386                     ("a maximum of %d -realm arguments can be specified.\n",
1387                      AFS_NUM_LREALMS);
1388                 return -1;
1389             }
1390             strncpy(local_realms[num_lrealms++], argv[i], AFS_REALM_SZ);
1391         } else if (!strcmp(argv[i], "-udpsize")) {
1392             if ((i + 1) >= argc) {
1393                 printf("You have to specify -udpsize <integer value>\n");
1394                 return -1;
1395             }
1396             bufSize = atoi(argv[++i]);
1397             if (bufSize < rx_GetMinUdpBufSize())
1398                 printf
1399                     ("Warning:udpsize %d is less than minimum %d; ignoring\n",
1400                      bufSize, rx_GetMinUdpBufSize());
1401             else
1402                 udpBufSize = bufSize;
1403         } else if (!strcmp(argv[i], "-sendsize")) {
1404             if ((i + 1) >= argc) {
1405                 printf("You have to specify -sendsize <integer value>\n");
1406                 return -1;
1407             }
1408             bufSize = atoi(argv[++i]);
1409             if (bufSize < 16384)
1410                 printf
1411                     ("Warning:sendsize %d is less than minimum %d; ignoring\n",
1412                      bufSize, 16384);
1413             else
1414                 sendBufSize = bufSize;
1415         } else if (!strcmp(argv[i], "-enable_peer_stats")) {
1416             rx_enablePeerRPCStats();
1417         } else if (!strcmp(argv[i], "-enable_process_stats")) {
1418             rx_enableProcessRPCStats();
1419         }
1420         else if (strcmp(argv[i], "-auditlog") == 0) {
1421             auditFileName = argv[++i];
1422         }
1423         else if (strcmp(argv[i], "-audit-interface") == 0) {
1424             char *interface = argv[++i];
1425
1426             if (osi_audit_interface(interface)) {
1427                 printf("Invalid audit interface '%s'\n", interface);
1428                 return -1;
1429             }
1430         }
1431 #ifndef AFS_NT40_ENV
1432         else if (strcmp(argv[i], "-syslog") == 0) {
1433             /* set syslog logging flag */
1434             serverLogSyslog = 1;
1435         } else if (strncmp(argv[i], "-syslog=", 8) == 0) {
1436             serverLogSyslog = 1;
1437             serverLogSyslogFacility = atoi(argv[i] + 8);
1438         }
1439 #endif
1440         else if (strcmp(argv[i], "-mrafslogs") == 0) {
1441             /* set syslog logging flag */
1442             mrafsStyleLogs = 1;
1443         }
1444         else if (strcmp(argv[i], "-saneacls") == 0) {
1445             saneacls = 1;
1446         }
1447         else if (strcmp(argv[i], "-offline-timeout") == 0) {
1448             if (i + 1 >= argc) {
1449                 printf("You have to specify -offline-timeout <integer>\n");
1450                 return -1;
1451             }
1452             offline_timeout = atoi(argv[++i]);
1453 #ifndef AFS_PTHREAD_ENV
1454             if (offline_timeout != -1) {
1455                 printf("The only valid -offline-timeout value for the LWP "
1456                        "fileserver is -1\n");
1457                 return -1;
1458             }
1459 #endif /* AFS_PTHREAD_ENV */
1460             if (offline_timeout < -1) {
1461                 printf("Invalid -offline-timeout value %s; the only valid "
1462                        "negative value is -1\n", argv[i]);
1463                 return -1;
1464             }
1465         }
1466         else if (strcmp(argv[i], "-offline-shutdown-timeout") == 0) {
1467             if (i + 1 >= argc) {
1468                 printf("You have to specify -offline-shutdown-timeout "
1469                        "<integer>\n");
1470                 return -1;
1471             }
1472             offline_shutdown_timeout = atoi(argv[++i]);
1473 #ifndef AFS_PTHREAD_ENV
1474             if (offline_shutdown_timeout != -1) {
1475                 printf("The only valid -offline-shutdown-timeout value for the "
1476                        "LWP fileserver is -1\n");
1477                 return -1;
1478             }
1479 #endif /* AFS_PTHREAD_ENV */
1480             if (offline_shutdown_timeout < -1) {
1481                 printf("Invalid -offline-timeout value %s; the only valid "
1482                        "negative value is -1\n", argv[i]);
1483                 return -1;
1484             }
1485         }
1486         else {
1487             return (-1);
1488         }
1489     }
1490     if (SawS && SawL) {
1491         printf("Only one of -L, or -S must be specified\n");
1492         return -1;
1493     }
1494     if (SawS) {
1495         if (!Sawrxpck)
1496             rxpackets = 100;
1497         if (!Sawsmall)
1498             nSmallVns = 200;
1499         if (!Sawlarge)
1500             large = 200;
1501         if (!Sawcbs)
1502             numberofcbs = 20000;
1503         if (!Sawlwps)
1504             lwps = 6;
1505         if (!Sawbufs)
1506             buffs = 70;
1507         if (!SawVC)
1508             volcache = 200;
1509     }
1510     if (SawL) {
1511         if (!Sawrxpck)
1512             rxpackets = 200;
1513         if (!Sawsmall)
1514             nSmallVns = 600;
1515         if (!Sawlarge)
1516             large = 600;
1517         if (!Sawcbs)
1518             numberofcbs = 64000;
1519         if (!Sawlwps)
1520             lwps = 128;
1521         if (!Sawbufs)
1522             buffs = 120;
1523         if (!SawVC)
1524             volcache = 600;
1525     }
1526     if (!Sawbusy)
1527         busy_threshold = 3 * rxpackets / 2;
1528     if (auditFileName)
1529         osi_audit_file(auditFileName);
1530
1531     lwps_max = max_fileserver_thread() - FILESERVER_HELPER_THREADS;
1532     if (lwps > lwps_max)
1533         lwps = lwps_max;
1534     else if (lwps < 6)
1535         lwps = 6;
1536
1537     return (0);
1538
1539 }                               /*ParseArgs */
1540
1541
1542 #define MAXPARMS 15
1543
1544 static void
1545 NewParms(int initializing)
1546 {
1547     static struct afs_stat sbuf;
1548     int i, fd;
1549     char *parms;
1550     char *argv[MAXPARMS];
1551     int argc;
1552
1553     if (!(afs_stat("/vice/file/parms", &sbuf))) {
1554         parms = (char *)malloc(sbuf.st_size);
1555         if (!parms)
1556             return;
1557         fd = afs_open("parms", O_RDONLY, 0666);
1558         if (fd <= 0) {
1559             ViceLog(0, ("Open for parms failed with errno = %d\n", errno));
1560             return;
1561         }
1562
1563         i = read(fd, parms, sbuf.st_size);
1564         close(fd);
1565         if (i != sbuf.st_size) {
1566             if (i < 0) {
1567                 ViceLog(0, ("Read on parms failed with errno = %d\n", errno));
1568             } else {
1569                 ViceLog(0,
1570                         ("Read on parms failed; expected %ld bytes but read %d\n",
1571                          (long) sbuf.st_size, i));
1572             }
1573             free(parms);
1574             return;
1575         }
1576
1577         for (i = 0; i < MAXPARMS; argv[i++] = 0);
1578
1579         for (argc = i = 0; i < sbuf.st_size; i++) {
1580             if ((*(parms + i) != ' ') && (*(parms + i) != '\n')) {
1581                 if (argv[argc] == 0)
1582                     argv[argc] = (parms + i);
1583             } else {
1584                 *(parms + i) = '\0';
1585                 if (argv[argc] != 0) {
1586                     if (++argc == MAXPARMS)
1587                         break;
1588                 }
1589                 while ((*(parms + i + 1) == ' ')
1590                        || (*(parms + i + 1) == '\n'))
1591                     i++;
1592             }
1593         }
1594         if (ParseArgs(argc, argv) == 0) {
1595             ViceLog(0, ("Change parameters to:"));
1596         } else {
1597             ViceLog(0, ("Invalid parameter in:"));
1598         }
1599         for (i = 0; i < argc; i++) {
1600             ViceLog(0, (" %s", argv[i]));
1601         }
1602         ViceLog(0, ("\n"));
1603         free(parms);
1604     } else if (!initializing)
1605         ViceLog(0,
1606                 ("Received request to change parms but no parms file exists\n"));
1607
1608 }                               /*NewParms */
1609
1610
1611 /* Miscellaneous routines */
1612 void
1613 Die(char *msg)
1614 {
1615     ViceLog(0, ("%s\n", msg));
1616     osi_Panic("%s\n", msg);
1617
1618 }                               /*Die */
1619
1620
1621 afs_int32
1622 InitPR(void)
1623 {
1624     int code;
1625
1626     /*
1627      * If this fails, it's because something major is wrong, and is not
1628      * likely to be time dependent.
1629      */
1630     code = pr_Initialize(2, AFSDIR_SERVER_ETC_DIRPATH, 0);
1631     if (code != 0) {
1632         ViceLog(0,
1633                 ("Couldn't initialize protection library; code=%d.\n", code));
1634         return code;
1635     }
1636
1637 #ifdef AFS_PTHREAD_ENV
1638     osi_Assert(pthread_key_create(&viced_uclient_key, NULL) == 0);
1639 #endif
1640
1641     SystemId = SYSADMINID;
1642     SystemAnyUser = ANYUSERID;
1643     SystemAnyUserCPS.prlist_len = 0;
1644     SystemAnyUserCPS.prlist_val = NULL;
1645     AnonCPS.prlist_len = 0;
1646     AnonCPS.prlist_val = NULL;
1647     while (1) {
1648         code = pr_GetCPS(SystemAnyUser, &SystemAnyUserCPS);
1649         if (code != 0) {
1650             ViceLog(0,
1651                     ("Couldn't get CPS for AnyUser, will try again in 30 seconds; code=%d.\n",
1652                      code));
1653             goto sleep;
1654         }
1655         code = pr_GetCPS(ANONYMOUSID, &AnonCPS);
1656         if (code != 0) {
1657             ViceLog(0,
1658                     ("Couldn't get Anonymous CPS, exiting; code=%d.\n",
1659                      code));
1660             return -1;
1661         }
1662         AnonymousID = ANONYMOUSID;
1663         return 0;
1664       sleep:
1665 #ifdef AFS_PTHREAD_ENV
1666         sleep(30);
1667 #else /* AFS_PTHREAD_ENV */
1668         IOMGR_Sleep(30);
1669 #endif /* AFS_PTHREAD_ENV */
1670     }
1671 }                               /*InitPR */
1672
1673 struct rx_connection *serverconns[MAXSERVERS];
1674 struct ubik_client *cstruct;
1675
1676 afs_int32
1677 vl_Initialize(const char *confDir)
1678 {
1679     afs_int32 code, i;
1680     afs_int32 scIndex = RX_SECIDX_NULL;
1681     struct afsconf_dir *tdir;
1682     struct rx_securityClass *sc;
1683     struct afsconf_cell info;
1684
1685     tdir = afsconf_Open(confDir);
1686     if (!tdir) {
1687         ViceLog(0,
1688                 ("Could not open configuration directory (%s).\n", confDir));
1689         exit(1);
1690     }
1691     code = afsconf_ClientAuth(tdir, &sc, &scIndex);
1692     if (code) {
1693         ViceLog(0, ("Could not get security object for localAuth\n"));
1694         exit(1);
1695     }
1696     code = afsconf_GetCellInfo(tdir, NULL, AFSCONF_VLDBSERVICE, &info);
1697     if (info.numServers > MAXSERVERS) {
1698         ViceLog(0,
1699                 ("vl_Initialize: info.numServers=%d (> MAXSERVERS=%d)\n",
1700                  info.numServers, MAXSERVERS));
1701         exit(1);
1702     }
1703     for (i = 0; i < info.numServers; i++)
1704         serverconns[i] =
1705             rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
1706                              info.hostAddr[i].sin_port, USER_SERVICE_ID, sc,
1707                              scIndex);
1708     code = ubik_ClientInit(serverconns, &cstruct);
1709     afsconf_Close(tdir);
1710     if (code) {
1711         ViceLog(0, ("vl_Initialize: ubik client init failed.\n"));
1712         return code;
1713     }
1714     return 0;
1715 }
1716
1717 #define SYSIDMAGIC      0x88aabbcc
1718 #define SYSIDVERSION    1
1719
1720 afs_int32
1721 ReadSysIdFile(void)
1722 {
1723     afs_int32 fd, nentries, i;
1724     struct versionStamp vsn;
1725     struct afs_stat status;
1726     afsUUID uuid;
1727
1728     if ((afs_stat(AFSDIR_SERVER_SYSID_FILEPATH, &status))
1729         || (status.st_size <= 0)) {
1730         ViceLog(0, ("%s: doesn't exist\n", AFSDIR_SERVER_SYSID_FILEPATH));
1731         return ENOENT;
1732     }
1733     if (!(fd = afs_open(AFSDIR_SERVER_SYSID_FILEPATH, O_RDONLY, 0))) {
1734         ViceLog(0,
1735                 ("%s: can't open (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH,
1736                  errno));
1737         return EIO;
1738     }
1739     if ((i = read(fd, (char *)&vsn, sizeof(vsn))) != sizeof(vsn)) {
1740         ViceLog(0,
1741                 ("%s: Read failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH,
1742                  errno));
1743         return EIO;
1744     }
1745     if (vsn.magic != SYSIDMAGIC) {
1746         ViceLog(0,
1747                 ("%s: wrong magic %x (we support %x)\n",
1748                  AFSDIR_SERVER_SYSID_FILEPATH, vsn.magic, SYSIDMAGIC));
1749         return EIO;
1750     }
1751     if (vsn.version != SYSIDVERSION) {
1752         ViceLog(0,
1753                 ("%s: wrong version %d (we support %d)\n",
1754                  AFSDIR_SERVER_SYSID_FILEPATH, vsn.version, SYSIDVERSION));
1755         return EIO;
1756     }
1757     if ((i =
1758          read(fd, (char *)&uuid,
1759               sizeof(struct afsUUID))) != sizeof(struct afsUUID)) {
1760         ViceLog(0,
1761                 ("%s: read of uuid failed (%d)\n",
1762                  AFSDIR_SERVER_SYSID_FILEPATH, errno));
1763         return EIO;
1764     }
1765     afs_ntohuuid(&uuid);
1766     FS_HostUUID = uuid;
1767     if ((i =
1768          read(fd, (char *)&nentries,
1769               sizeof(afs_int32))) != sizeof(afs_int32)) {
1770         ViceLog(0,
1771                 ("%s: Read of entries failed (%d)\n",
1772                  AFSDIR_SERVER_SYSID_FILEPATH, errno));
1773         return EIO;
1774     }
1775     if (nentries <= 0 || nentries > ADDRSPERSITE) {
1776         ViceLog(0,
1777                 ("%s: invalid num of interfaces: %d\n",
1778                  AFSDIR_SERVER_SYSID_FILEPATH, nentries));
1779         return EIO;
1780     }
1781     if (FS_HostAddr_cnt == 0) {
1782         FS_HostAddr_cnt = nentries;
1783         for (i = 0; i < nentries; i++) {
1784             if (read(fd, (char *)&FS_HostAddrs[i], sizeof(afs_int32)) !=
1785                 sizeof(afs_int32)) {
1786                 ViceLog(0,
1787                         ("%s: Read of addresses failed (%d)\n",
1788                          AFSDIR_SERVER_SYSID_FILEPATH, errno));
1789                 FS_HostAddr_cnt = 0;    /* reset it */
1790                 return EIO;
1791             }
1792         }
1793     } else {
1794         ViceLog(1,
1795                 ("%s: address list ignored (NetInfo/NetRestrict override)\n",
1796                  AFSDIR_SERVER_SYSID_FILEPATH));
1797     }
1798     close(fd);
1799     return 0;
1800 }
1801
1802 afs_int32
1803 WriteSysIdFile(void)
1804 {
1805     afs_int32 fd, i;
1806     struct versionStamp vsn;
1807     struct afs_stat status;
1808     afsUUID uuid;
1809
1810     if (!afs_stat(AFSDIR_SERVER_SYSID_FILEPATH, &status)) {
1811         /*
1812          * File exists; keep the old one around
1813          */
1814         renamefile(AFSDIR_SERVER_SYSID_FILEPATH,
1815                    AFSDIR_SERVER_OLDSYSID_FILEPATH);
1816     }
1817     fd = afs_open(AFSDIR_SERVER_SYSID_FILEPATH, O_WRONLY | O_TRUNC | O_CREAT,
1818                   0666);
1819     if (fd < 1) {
1820         ViceLog(0,
1821                 ("%s: can't create (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH,
1822                  errno));
1823         return EIO;
1824     }
1825     vsn.magic = SYSIDMAGIC;
1826     vsn.version = 1;
1827     if ((i = write(fd, (char *)&vsn, sizeof(vsn))) != sizeof(vsn)) {
1828         ViceLog(0,
1829                 ("%s: write failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH,
1830                  errno));
1831         return EIO;
1832     }
1833     uuid = FS_HostUUID;
1834     afs_htonuuid(&uuid);
1835     if ((i =
1836          write(fd, (char *)&uuid,
1837                sizeof(struct afsUUID))) != sizeof(struct afsUUID)) {
1838         ViceLog(0,
1839                 ("%s: write of uuid failed (%d)\n",
1840                  AFSDIR_SERVER_SYSID_FILEPATH, errno));
1841         return EIO;
1842     }
1843     if ((i =
1844          write(fd, (char *)&FS_HostAddr_cnt,
1845                sizeof(afs_int32))) != sizeof(afs_int32)) {
1846         ViceLog(0,
1847                 ("%s: write of # of entries failed (%d)\n",
1848                  AFSDIR_SERVER_SYSID_FILEPATH, errno));
1849         return EIO;
1850     }
1851     for (i = 0; i < FS_HostAddr_cnt; i++) {
1852         if (write(fd, (char *)&FS_HostAddrs[i], sizeof(afs_int32)) !=
1853             sizeof(afs_int32)) {
1854             ViceLog(0,
1855                     ("%s: write of addresses failed (%d)\n",
1856                      AFSDIR_SERVER_SYSID_FILEPATH, errno));
1857             return EIO;
1858         }
1859     }
1860     close(fd);
1861     return 0;
1862 }
1863
1864 /*
1865  * defect 10966
1866  * This routine sets up the buffers for the VL_RegisterAddrs RPC. All addresses
1867  * in FS_HostAddrs[] are in NBO, while the RPC treats them as a "blob" of data
1868  * and so we need to convert each of them into HBO which is what the extra
1869  * array called FS_HostAddrs_HBO is used here.
1870  */
1871 static afs_int32
1872 Do_VLRegisterRPC(void)
1873 {
1874     int code;
1875     bulkaddrs addrs;
1876     afs_uint32 FS_HostAddrs_HBO[ADDRSPERSITE];
1877     int i = 0;
1878
1879     for (i = 0; i < FS_HostAddr_cnt; i++)
1880         FS_HostAddrs_HBO[i] = ntohl(FS_HostAddrs[i]);
1881     addrs.bulkaddrs_len = FS_HostAddr_cnt;
1882     addrs.bulkaddrs_val = (afs_uint32 *) FS_HostAddrs_HBO;
1883     code = ubik_VL_RegisterAddrs(cstruct, 0, &FS_HostUUID, 0, &addrs);
1884     if (code) {
1885         if (code == VL_MULTIPADDR) {
1886             ViceLog(0,
1887                     ("VL_RegisterAddrs rpc failed; The IP address exists on a different server; repair it\n"));
1888             ViceLog(0,
1889                     ("VL_RegisterAddrs rpc failed; See VLLog for details\n"));
1890             return code;
1891         } else if (code == RXGEN_OPCODE) {
1892             ViceLog(0,
1893                     ("vlserver doesn't support VL_RegisterAddrs rpc; ignored\n"));
1894             FS_registered = 2;  /* So we don't have to retry in the gc daemon */
1895         } else {
1896             ViceLog(0,
1897                     ("VL_RegisterAddrs rpc failed; will retry periodically (code=%d, err=%d)\n",
1898                      code, errno));
1899             FS_registered = 1;  /* Retry in the gc daemon */
1900         }
1901     } else {
1902         FS_registered = 2;      /* So we don't have to retry in the gc daemon */
1903         WriteSysIdFile();
1904     }
1905
1906     return 0;
1907 }
1908
1909 afs_int32
1910 SetupVL(void)
1911 {
1912     afs_int32 code;
1913
1914     if (AFSDIR_SERVER_NETRESTRICT_FILEPATH || AFSDIR_SERVER_NETINFO_FILEPATH) {
1915         /*
1916          * Find addresses we are supposed to register as per the netrestrict
1917          * and netinfo files (/usr/afs/local/NetInfo and
1918          * /usr/afs/local/NetRestict)
1919          */
1920         char reason[1024];
1921         afs_int32 code = parseNetFiles(FS_HostAddrs, NULL, NULL,
1922                                        ADDRSPERSITE, reason,
1923                                        AFSDIR_SERVER_NETINFO_FILEPATH,
1924                                        AFSDIR_SERVER_NETRESTRICT_FILEPATH);
1925         if (code < 0) {
1926             ViceLog(0, ("Can't register any valid addresses: %s\n", reason));
1927             exit(1);
1928         }
1929         FS_HostAddr_cnt = (afs_uint32) code;
1930     } else
1931     {
1932         FS_HostAddr_cnt = rx_getAllAddr(FS_HostAddrs, ADDRSPERSITE);
1933     }
1934
1935     if (FS_HostAddr_cnt == 1 && rxBind == 1)
1936         code = FS_HostAddrs[0];
1937     else
1938         code = htonl(INADDR_ANY);
1939     return code;
1940 }
1941
1942 afs_int32
1943 InitVL(void)
1944 {
1945     afs_int32 code;
1946
1947     /*
1948      * If this fails, it's because something major is wrong, and is not
1949      * likely to be time dependent.
1950      */
1951     code = vl_Initialize(AFSDIR_SERVER_ETC_DIRPATH);
1952     if (code != 0) {
1953         ViceLog(0,
1954                 ("Couldn't initialize protection library; code=%d.\n", code));
1955         return code;
1956     }
1957
1958     /* Read or create the sysid file and register the fileserver's
1959      * IP addresses with the vlserver.
1960      */
1961     code = ReadSysIdFile();
1962     if (code) {
1963         /* Need to create the file */
1964         ViceLog(0, ("Creating new SysID file\n"));
1965         if ((code = afs_uuid_create(&FS_HostUUID))) {
1966             ViceLog(0, ("Failed to create new uuid: %d\n", code));
1967             exit(1);
1968         }
1969     }
1970     /* A good sysid file exists; inform the vlserver. If any conflicts,
1971      * we always use the latest interface available as the real truth.
1972      */
1973
1974     code = Do_VLRegisterRPC();
1975     return code;
1976 }
1977
1978 int
1979 main(int argc, char *argv[])
1980 {
1981     afs_int32 code;
1982     char tbuffer[32];
1983     struct rx_securityClass **securityClasses;
1984     afs_int32 numClasses;
1985     struct rx_service *tservice;
1986 #ifdef AFS_PTHREAD_ENV
1987     pthread_t serverPid;
1988     pthread_attr_t tattr;
1989 #else /* AFS_PTHREAD_ENV */
1990     PROCESS parentPid, serverPid;
1991 #endif /* AFS_PTHREAD_ENV */
1992     struct hostent *he;
1993     int minVnodesRequired;      /* min size of vnode cache */
1994 #ifndef AFS_NT40_ENV
1995     struct rlimit rlim;         /* max number of open file descriptors */
1996 #endif
1997     int curLimit;
1998     time_t t;
1999     afs_uint32 rx_bindhost;
2000     VolumePackageOptions opts;
2001
2002 #ifdef  AFS_AIX32_ENV
2003     struct sigaction nsa;
2004
2005     sigemptyset(&nsa.sa_mask);
2006     nsa.sa_handler = SIG_DFL;
2007     nsa.sa_flags = SA_FULLDUMP;
2008     sigaction(SIGABRT, &nsa, NULL);
2009     sigaction(SIGSEGV, &nsa, NULL);
2010 #endif
2011     osi_audit_init();
2012
2013     /* Initialize dirpaths */
2014     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
2015 #ifdef AFS_NT40_ENV
2016         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
2017 #endif
2018         fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
2019                 argv[0]);
2020         exit(2);
2021     }
2022     /* set ihandle package defaults prior to parsing args */
2023     ih_PkgDefaults();
2024
2025     if (ParseArgs(argc, argv)) {
2026         FlagMsg();
2027         exit(-1);
2028     }
2029 #ifdef AFS_PTHREAD_ENV
2030     MUTEX_INIT(&fileproc_glock_mutex, "fileproc", MUTEX_DEFAULT, 0);
2031 #endif /* AFS_PTHREAD_ENV */
2032
2033 #ifdef AFS_SGI_VNODE_GLUE
2034     if (afs_init_kernel_config(-1) < 0) {
2035         printf
2036             ("Can't determine NUMA configuration, not starting fileserver.\n");
2037         exit(1);
2038     }
2039 #endif
2040     confDir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
2041     if (!confDir) {
2042         fprintf(stderr, "Unable to open config directory %s\n",
2043                 AFSDIR_SERVER_ETC_DIRPATH);
2044         exit(-1);
2045     }
2046
2047     NewParms(1);
2048
2049     /* Open FileLog on stdout, stderr, fd 1 and fd2 (for perror), sigh. */
2050 #ifndef AFS_NT40_ENV
2051     serverLogSyslogTag = "fileserver";
2052 #endif
2053     OpenLog(AFSDIR_SERVER_FILELOG_FILEPATH);
2054     SetupLogSignals();
2055
2056     if (SawSpare && SawPctSpare) {
2057         ViceLog(0, ("Both -spare and -pctspare specified, exiting.\n"));
2058         exit(-1);
2059     }
2060     LogCommandLine(argc, argv, "starting", "", "File server", FSLog);
2061
2062 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
2063     /* initialize the pthread soft signal handler thread */
2064     softsig_init();
2065 #endif
2066
2067     /* install signal handlers for controlling the fileserver process */
2068     ResetCheckSignal();         /* set CheckSignal_Signal() sig handler */
2069     ResetCheckDescriptors();    /* set CheckDescriptors_Signal() sig handler */
2070
2071 #if defined(AFS_SGI_ENV)
2072     /* give this guy a non-degrading priority so help busy servers */
2073     schedctl(NDPRI, 0, NDPNORMMAX);
2074     if (SawLock)
2075         plock(PROCLOCK);
2076 #else
2077 #ifndef AFS_NT40_ENV
2078     nice(-5);                   /* TODO: */
2079 #endif
2080 #endif
2081     osi_Assert(DInit(buffs) == 0);
2082 #ifdef AFS_DEMAND_ATTACH_FS
2083     FS_STATE_INIT;
2084 #endif
2085
2086 #ifdef AFS_NT40_ENV
2087     if (afs_winsockInit() < 0) {
2088         ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
2089         ViceLog(0, ("File server failed to intialize winsock.\n"));
2090         exit(1);
2091     }
2092 #endif
2093     CheckAdminName();
2094
2095     /* if we support more than 16 threads, then we better have the ability
2096      ** to keep open a large number of files simultaneously
2097      */
2098 #if     defined(AFS_AIX_ENV) && !defined(AFS_AIX42_ENV)
2099     curLimit = OPEN_MAX;        /* for pre AIX 4.2 systems */
2100 #elif defined(AFS_NT40_ENV)
2101     curLimit = NT_OPEN_MAX;     /* open file descriptor limit on NT */
2102 #else
2103
2104     curLimit = 0;               /* the number of open file descriptors */
2105     code = getrlimit(RLIMIT_NOFILE, &rlim);
2106     if (code == 0) {
2107         curLimit = rlim.rlim_cur;
2108         rlim.rlim_cur = rlim.rlim_max;
2109         code = setrlimit(RLIMIT_NOFILE, &rlim);
2110         if (code == 0)
2111             curLimit = rlim.rlim_max;
2112     }
2113     if (code != 0)
2114         ViceLog(0, ("Failed to increase open file limit, using default\n"));
2115
2116 #endif /* defined(AFS_AIX_ENV) && !defined(AFS_AIX42_ENV) */
2117
2118     curLimit -= 32;             /* leave a slack of 32 file descriptors */
2119     if (lwps > curLimit) {
2120         if (curLimit > 0)
2121             lwps = curLimit;
2122         else if (lwps > 16)
2123             lwps = 16;          /* default to a maximum of 16 threads */
2124
2125         /* tune the ihandle fd cache accordingly */
2126         if (vol_io_params.fd_max_cachesize < curLimit)
2127             vol_io_params.fd_max_cachesize = curLimit + 1;
2128
2129         ViceLog(0,
2130                 ("The system supports a max of %d open files and we are starting %d threads (ihandle fd cache is %d)\n",
2131                  curLimit, lwps, vol_io_params.fd_max_cachesize));
2132     }
2133 #ifndef AFS_PTHREAD_ENV
2134     osi_Assert(LWP_InitializeProcessSupport(LWP_MAX_PRIORITY - 2, &parentPid) ==
2135            LWP_SUCCESS);
2136 #endif /* !AFS_PTHREAD_ENV */
2137
2138     /* Initialize volume support */
2139     if (!novbc) {
2140         V_BreakVolumeCallbacks = BreakVolumeCallBacksLater;
2141     }
2142
2143 #ifdef AFS_PTHREAD_ENV
2144     SetLogThreadNumProgram( threadNum );
2145 #endif
2146
2147     /* initialize libacl routines */
2148     acl_Initialize(ACL_VERSION);
2149
2150     /* initialize RX support */
2151 #ifndef AFS_NT40_ENV
2152     rxi_syscallp = viced_syscall;
2153 #endif
2154     rx_extraPackets = rxpackets;
2155     rx_extraQuota = 4;          /* for outgoing prserver calls from R threads */
2156     rx_SetBusyThreshold(busy_threshold, VBUSY);
2157     rx_SetCallAbortThreshold(abort_threshold);
2158     rx_SetConnAbortThreshold(abort_threshold);
2159 #ifdef AFS_XBSD_ENV
2160     stackSize = 128 * 1024;
2161 #else
2162     stackSize = lwps * 4000;
2163     if (stackSize < 32000)
2164         stackSize = 32000;
2165     else if (stackSize > 44000)
2166         stackSize = 44000;
2167 #endif
2168 #if defined(AFS_HPUX_ENV) || defined(AFS_SUN_ENV) || defined(AFS_SGI51_ENV) || defined(AFS_XBSD_ENV)
2169     rx_SetStackSize(1, stackSize);
2170 #endif
2171     if (udpBufSize)
2172         rx_SetUdpBufSize(udpBufSize);   /* set the UDP buffer size for receive */
2173     rx_bindhost = SetupVL();
2174
2175     if (rx_InitHost(rx_bindhost, (int)htons(7000)) < 0) {
2176         ViceLog(0, ("Cannot initialize RX\n"));
2177         exit(1);
2178     }
2179     if (!rxJumbograms) {
2180         /* Don't send and don't allow 3.4 clients to send jumbograms. */
2181         rx_SetNoJumbo();
2182     }
2183     if (rxMaxMTU != -1) {
2184         rx_SetMaxMTU(rxMaxMTU);
2185     }
2186     rx_GetIFInfo();
2187     rx_SetRxDeadTime(30);
2188     afsconf_BuildServerSecurityObjects(confDir, AFSCONF_SEC_OBJS_RXKAD_CRYPT,
2189                                        &securityClasses, &numClasses);
2190
2191     tservice = rx_NewServiceHost(rx_bindhost,  /* port */ 0, /* service id */
2192                                  1,     /*service name */
2193                                  "AFS",
2194                                  securityClasses, numClasses,
2195                                  RXAFS_ExecuteRequest);
2196     if (!tservice) {
2197         ViceLog(0,
2198                 ("Failed to initialize RX, probably two servers running.\n"));
2199         exit(-1);
2200     }
2201     if (rxkadDisableDotCheck) {
2202         rx_SetSecurityConfiguration(tservice, RXS_CONFIG_FLAGS,
2203                                     (void *)RXS_CONFIG_FLAGS_DISABLE_DOTCHECK);
2204     }
2205     rx_SetMinProcs(tservice, 3);
2206     rx_SetMaxProcs(tservice, lwps);
2207     rx_SetCheckReach(tservice, 1);
2208     rx_SetServerIdleDeadErr(tservice, VNOSERVICE);
2209
2210     tservice =
2211         rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats", securityClasses,
2212                       numClasses, RXSTATS_ExecuteRequest);
2213     if (!tservice) {
2214         ViceLog(0, ("Failed to initialize rpc stat service.\n"));
2215         exit(-1);
2216     }
2217     rx_SetMinProcs(tservice, 2);
2218     rx_SetMaxProcs(tservice, 4);
2219
2220     /*
2221      * Enable RX hot threads, which allows the listener thread to trade
2222      * places with an idle thread and moves the context switch from listener
2223      * to worker out of the critical path.
2224      */
2225     rx_EnableHotThread();
2226
2227     /* Some rx debugging */
2228     if (rxlog || eventlog) {
2229         debugFile = afs_fopen("rx_dbg", "w");
2230         if (rxlog)
2231             rx_debugFile = debugFile;
2232         if (eventlog)
2233             rxevent_debugFile = debugFile;
2234     }
2235
2236     init_sys_error_to_et();     /* Set up error table translation */
2237     h_InitHostPackage();        /* set up local cellname and realmname */
2238     InitCallBack(numberofcbs);
2239     ClearXStatValues();
2240
2241     code = InitVL();
2242     if (code && code != VL_MULTIPADDR) {
2243         ViceLog(0, ("Fatal error in library initialization, exiting!!\n"));
2244         exit(1);
2245     }
2246
2247     code = InitPR();
2248     if (code && code != -1) {
2249         ViceLog(0, ("Fatal error in protection initialization, exiting!!\n"));
2250         exit(1);
2251     }
2252
2253     /* allow super users to manage RX statistics */
2254     rx_SetRxStatUserOk(fs_rxstat_userok);
2255
2256     CV_INIT(&fsync_cond, "fsync", CV_DEFAULT, 0);
2257     MUTEX_INIT(&fsync_glock_mutex, "fsync", MUTEX_DEFAULT, 0);
2258
2259 #if !defined(AFS_DEMAND_ATTACH_FS)
2260     /*
2261      * For DAFS, we do not start the Rx server threads until after
2262      * the volume package is initialized, and fileserver state is
2263      * restored.  This is necessary in order to keep host and callback
2264      * package state pristine until we have a chance to restore state.
2265      *
2266      * Furthermore, startup latency is much lower with dafs, so this
2267      * shouldn't pose a serious problem.
2268      */
2269     rx_StartServer(0);          /* now start handling requests */
2270 #endif
2271
2272     /* we ensure that there is enough space in the vnode buffer to satisfy
2273      ** requests from all concurrent threads.
2274      ** the maximum number of vnodes used by a single thread at any one time
2275      ** is three ( "link" uses three vnodes simultaneously, one vLarge and
2276      ** two vSmall for linking files and two vLarge and one vSmall for linking
2277      ** files  ) : dhruba
2278      */
2279     minVnodesRequired = 2 * lwps + 1;
2280     if (minVnodesRequired > nSmallVns) {
2281         nSmallVns = minVnodesRequired;
2282         ViceLog(0,
2283                 ("Overriding -s command line parameter with %d\n",
2284                  nSmallVns));
2285     }
2286     if (minVnodesRequired > large) {
2287         large = minVnodesRequired;
2288         ViceLog(0, ("Overriding -l command line parameter with %d\n", large));
2289     }
2290
2291     /* We now do this after getting the listener up and running, so that client
2292      * connections don't timeout (maybe) if a file server is restarted, since it
2293      * will be available "real soon now".  Worry about whether we can satisfy the
2294      * calls in the volume package itself.
2295      */
2296     VOptDefaults(fileServer, &opts);
2297     opts.nLargeVnodes = large;
2298     opts.nSmallVnodes = nSmallVns;
2299     opts.volcache = volcache;
2300     opts.unsafe_attach = unsafe_attach;
2301     if (offline_timeout != -1) {
2302         opts.interrupt_rxcall = rx_InterruptCall;
2303         opts.offline_timeout = offline_timeout;
2304     }
2305     if (offline_shutdown_timeout == -1) {
2306         /* default to -offline-timeout, if shutdown-specific timeout is not
2307          * specified */
2308         opts.offline_shutdown_timeout = offline_timeout;
2309     } else {
2310         opts.interrupt_rxcall = rx_InterruptCall;
2311         opts.offline_shutdown_timeout = offline_shutdown_timeout;
2312     }
2313
2314     if (VInitVolumePackage2(fileServer, &opts)) {
2315         ViceLog(0,
2316                 ("Shutting down: errors encountered initializing volume package\n"));
2317         VShutdown();
2318         exit(1);
2319     }
2320
2321     /* Install handler to catch the shutdown signal;
2322      * bosserver assumes SIGQUIT shutdown
2323      */
2324 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
2325     softsig_signal(SIGQUIT, ShutDown_Signal);
2326 #else
2327     (void)signal(SIGQUIT, ShutDown_Signal);
2328 #endif
2329
2330     if (VInitAttachVolumes(fileServer)) {
2331         ViceLog(0,
2332                 ("Shutting down: errors encountered initializing volume package\n"));
2333         VShutdown();
2334         exit(1);
2335     }
2336
2337 #ifdef AFS_DEMAND_ATTACH_FS
2338     if (fs_state.options.fs_state_restore) {
2339         /*
2340          * demand attach fs
2341          * restore fileserver state */
2342         fs_stateRestore();
2343     }
2344     rx_StartServer(0);  /* now start handling requests */
2345 #endif /* AFS_DEMAND_ATTACH_FS */
2346
2347     /*
2348      * We are done calling fopen/fdopen. It is safe to use a large
2349      * of the file descriptor cache.
2350      */
2351     ih_UseLargeCache();
2352
2353 #ifdef AFS_PTHREAD_ENV
2354     ViceLog(5, ("Starting pthreads\n"));
2355     osi_Assert(pthread_attr_init(&tattr) == 0);
2356     osi_Assert(pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) == 0);
2357
2358     osi_Assert(pthread_create
2359            (&serverPid, &tattr, FiveMinuteCheckLWP,
2360             &fiveminutes) == 0);
2361     osi_Assert(pthread_create
2362            (&serverPid, &tattr, HostCheckLWP, &fiveminutes) == 0);
2363     osi_Assert(pthread_create
2364            (&serverPid, &tattr, FsyncCheckLWP, &fiveminutes) == 0);
2365 #else /* AFS_PTHREAD_ENV */
2366     ViceLog(5, ("Starting LWP\n"));
2367     osi_Assert(LWP_CreateProcess
2368            (FiveMinuteCheckLWP, stack * 1024, LWP_MAX_PRIORITY - 2,
2369             (void *)&fiveminutes, "FiveMinuteChecks",
2370             &serverPid) == LWP_SUCCESS);
2371
2372     osi_Assert(LWP_CreateProcess
2373            (HostCheckLWP, stack * 1024, LWP_MAX_PRIORITY - 2,
2374             (void *)&fiveminutes, "HostCheck", &serverPid) == LWP_SUCCESS);
2375     osi_Assert(LWP_CreateProcess
2376            (FsyncCheckLWP, stack * 1024, LWP_MAX_PRIORITY - 2,
2377             (void *)&fiveminutes, "FsyncCheck", &serverPid) == LWP_SUCCESS);
2378 #endif /* AFS_PTHREAD_ENV */
2379
2380     FT_GetTimeOfDay(&tp, 0);
2381
2382     /*
2383      * Figure out the FileServer's name and primary address.
2384      */
2385     ViceLog(0, ("Getting FileServer name...\n"));
2386     code = gethostname(FS_HostName, 64);
2387     if (code) {
2388         ViceLog(0, ("gethostname() failed\n"));
2389     }
2390     ViceLog(0, ("FileServer host name is '%s'\n", FS_HostName));
2391
2392     ViceLog(0, ("Getting FileServer address...\n"));
2393     he = gethostbyname(FS_HostName);
2394     if (!he) {
2395         ViceLog(0, ("Can't find address for FileServer '%s'\n", FS_HostName));
2396     } else {
2397         char hoststr[16];
2398         memcpy(&FS_HostAddr_NBO, he->h_addr, 4);
2399         (void)afs_inet_ntoa_r(FS_HostAddr_NBO, hoststr);
2400         FS_HostAddr_HBO = ntohl(FS_HostAddr_NBO);
2401         ViceLog(0,
2402                 ("FileServer %s has address %s (0x%x or 0x%x in host byte order)\n",
2403                  FS_HostName, hoststr, FS_HostAddr_NBO, FS_HostAddr_HBO));
2404     }
2405
2406     t = tp.tv_sec;
2407     ViceLog(0,
2408             ("File Server started %s",
2409              afs_ctime(&t, tbuffer, sizeof(tbuffer))));
2410 #if FS_STATS_DETAILED
2411     afs_FullPerfStats.det.epoch.tv_sec = StartTime = tp.tv_sec;
2412 #endif
2413 #ifdef AFS_PTHREAD_ENV
2414     while (1) {
2415         sleep(1000);            /* long time */
2416     }
2417 #else /* AFS_PTHREAD_ENV */
2418     osi_Assert(LWP_WaitProcess(&parentPid) == LWP_SUCCESS);
2419 #endif /* AFS_PTHREAD_ENV */
2420     return 0;
2421 }