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