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