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