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