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