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