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