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