DEVEL15-ubik-call-sucks-20060703
[openafs.git] / src / viced / viced.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  *
9  * Portions Copyright (c) 2006 Sine Nomine Associates
10  */
11
12 /*  viced.c     - File Server main loop                                  */
13 /*                                                                       */
14 /*  Date: 5/1/85                                                         */
15 /*                                                                       */
16 /*  Function    - This routine has the initialization code for           */
17 /*                FileServer II                                          */
18 /*                                                                       */
19 /* ********************************************************************** */
20
21 #include <afsconfig.h>
22 #include <afs/param.h>
23
24 RCSID
25     ("$Header$");
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <errno.h>
30 #include <sys/types.h>
31 #include <afs/procmgmt.h>       /* signal(), kill(), wait(), etc. */
32 #include <sys/stat.h>
33 #include <fcntl.h>
34 #ifdef AFS_NT40_ENV
35 #include <io.h>
36 #include <windows.h>
37 #include <WINNT/afsevent.h>
38 #else
39 #include <sys/file.h>
40 #include <netinet/in.h>
41 #include <netdb.h>
42 #include <unistd.h>             /* sysconf() */
43
44 #ifdef HAVE_STRING_H
45 #include <string.h>
46 #else
47 #ifdef HAVE_STRINGS_H
48 #include <strings.h>
49 #endif
50 #endif
51
52 #ifndef ITIMER_REAL
53 #include <sys/time.h>
54 #endif /* ITIMER_REAL */
55 #include <sys/resource.h>
56 #endif /* AFS_NT40_ENV */
57 #include <afs/stds.h>
58 #undef SHARED
59 #include <rx/xdr.h>
60 #include <afs/nfs.h>
61 #ifdef AFS_PTHREAD_ENV
62 #include <assert.h>
63 #else /* AFS_PTHREAD_ENV */
64 #include <afs/assert.h>
65 #endif /* AFS_PTHREAD_ENV */
66 #include <lwp.h>
67 #include <lock.h>
68 #include <afs/ptclient.h>
69 #include <afs/afsint.h>
70 #include <afs/vldbint.h>
71 #include <afs/errors.h>
72 #include <afs/ihandle.h>
73 #include <afs/vnode.h>
74 #include <afs/volume.h>
75 #include <afs/auth.h>
76 #include <afs/cellconfig.h>
77 #include <afs/acl.h>
78 #include <afs/prs_fs.h>
79 #include <rx/rx.h>
80 #include <rx/rxkad.h>
81 #include <afs/keys.h>
82 #include <afs/afs_args.h>
83 #include <afs/vlserver.h>
84 #include <afs/afsutil.h>
85 #include <afs/fileutil.h>
86 #include <afs/ptuser.h>
87 #include <afs/audit.h>
88 #include <afs/partition.h>
89 #ifndef AFS_NT40_ENV
90 #include <afs/netutils.h>
91 #endif
92 #include "viced.h"
93 #include "host.h"
94 #ifdef AFS_PTHREAD_ENV
95 #include "softsig.h"
96 #endif
97 #if defined(AFS_SGI_ENV)
98 #include "sys/schedctl.h"
99 #include "sys/lock.h"
100 #endif
101 #include <rx/rx_globals.h>
102
103 #ifdef O_LARGEFILE
104 #define afs_stat        stat64
105 #define afs_fstat       fstat64
106 #define afs_open        open64
107 #define afs_fopen       fopen64
108 #else /* !O_LARGEFILE */
109 #define afs_stat        stat
110 #define afs_fstat       fstat
111 #define afs_open        open
112 #define afs_fopen       fopen
113 #endif /* !O_LARGEFILE */
114
115 extern int BreakVolumeCallBacks(), InitCallBack();
116 extern int BreakVolumeCallBacks(), InitCallBack(), BreakLaterCallBacks();
117 extern int BreakVolumeCallBacksLater();
118 extern int LogLevel, etext;
119 extern afs_int32 BlocksSpare, PctSpare;
120
121 int ShutDown(void);
122 static void ClearXStatValues(), NewParms(), PrintCounters();
123 static void ResetCheckDescriptors(void), ResetCheckSignal(void);
124 static int CheckSignal(void);
125 extern int GetKeysFromToken();
126 extern int RXAFS_ExecuteRequest();
127 extern int RXSTATS_ExecuteRequest();
128 afs_int32 Do_VLRegisterRPC();
129
130 int eventlog = 0, rxlog = 0;
131 FILE *debugFile;
132 FILE *console = NULL;
133
134 #ifdef AFS_PTHREAD_ENV
135 pthread_mutex_t fsync_glock_mutex;
136 pthread_cond_t fsync_cond;
137 #else
138 char fsync_wait[1];
139 #endif /* AFS_PTHREAD_ENV */
140
141 #ifdef AFS_NT40_ENV
142 #define AFS_QUIETFS_ENV 1
143 #define NT_OPEN_MAX    1024     /* This is an arbitrary no. we came up with for 
144                                  * now. We hope this will be replaced by a more
145                                  * intelligent estimate later. */
146 #endif
147
148 int SystemId;                   /* ViceID of "Administrators" */
149 int SystemAnyUser;              /* Viceid of "System:AnyUser" */
150 prlist SystemAnyUserCPS;        /* CPS for "system:AnyUser */
151 int AnonymousID = 0;            /* ViceId of "Anonymous" */
152 prlist AnonCPS;                 /* CPS for "Anonymous" */
153
154 struct afsconf_dir *confDir;    /* Configuration dir object */
155
156 int restartMode = RESTART_ORDINARY;
157
158 int Testing = 0;                /* for ListViceInodes */
159
160 /*
161  * Home for the performance statistics.
162  */
163 struct afs_PerfStats afs_perfstats;
164
165 extern int LogLevel;
166 extern int Statistics;
167
168 int busyonrst = 1;
169 int timeout = 30;
170 int SawSpare;
171 int SawPctSpare;
172 int debuglevel = 0;
173 int printBanner = 0;
174 int rxJumbograms = 1;           /* default is to send and receive jumbograms. */
175 int rxBind = 0;         /* don't bind */
176 int rxMaxMTU = -1;
177 afs_int32 implicitAdminRights = PRSFS_LOOKUP;   /* The ADMINISTER right is 
178                                                  * already implied */
179 afs_int32 readonlyServer = 0;
180
181 int stack = 24;
182 int stackSize = 24000;
183 int fiveminutes = 300;          /* 5 minutes.  Change this for debugging only */
184 int CurrentConnections = 0;
185 int hostaclRefresh = 7200;      /* refresh host clients' acls every 2 hrs */
186 #if defined(AFS_SGI_ENV)
187 int SawLock;
188 #endif
189 time_t StartTime;
190
191 int rxpackets = 150;            /* 100 */
192 int nSmallVns = 400;            /* 200 */
193 int large = 400;                /* 200 */
194 int volcache = 400;             /* 400 */
195 int numberofcbs = 60000;        /* 60000 */
196 int lwps = 9;                   /* 6 */
197 int buffs = 90;                 /* 70 */
198 int novbc = 0;                  /* Enable Volume Break calls */
199 int busy_threshold = 600;
200 int abort_threshold = 10;
201 int udpBufSize = 0;             /* UDP buffer size for receive */
202 int sendBufSize = 16384;        /* send buffer size */
203
204 struct timeval tp;
205
206 #ifdef AFS_PTHREAD_ENV
207 pthread_key_t viced_uclient_key;
208 #endif
209
210 #ifdef AFS_PTHREAD_ENV
211 pthread_key_t viced_uclient_key;
212 #endif
213
214 #ifdef AFS_PTHREAD_ENV
215 pthread_key_t viced_uclient_key;
216 #endif
217
218 /*
219  * FileServer's name and IP address, both network byte order and
220  * host byte order.
221  */
222 #define ADDRSPERSITE 16         /* Same global is in rx/rx_user.c */
223
224 char FS_HostName[128] = "localhost";
225 afs_uint32 FS_HostAddr_NBO;
226 afs_uint32 FS_HostAddr_HBO;
227 afs_uint32 FS_HostAddrs[ADDRSPERSITE], FS_HostAddr_cnt = 0, FS_registered = 0;
228 /* All addresses in FS_HostAddrs are in NBO */
229 afsUUID FS_HostUUID;
230
231 static void FlagMsg();
232
233 #ifdef AFS_DEMAND_ATTACH_FS
234 /*
235  * demand attach fs
236  * fileserver mode support
237  *
238  * during fileserver shutdown, we have to track the graceful shutdown of
239  * certain background threads before we are allowed to dump state to
240  * disk
241  */
242 struct fs_state fs_state = 
243     { FS_MODE_NORMAL, 
244       0, 
245       0, 
246       0, 
247       0,
248       { 1,1,1,1 },
249       PTHREAD_COND_INITIALIZER,
250       PTHREAD_RWLOCK_INITIALIZER
251     };
252 #endif /* AFS_DEMAND_ATTACH_FS */
253
254 /*
255  * Home for the performance statistics.
256  */
257
258 /* DEBUG HACK */
259 static int
260 CheckDescriptors()
261 {
262 #ifndef AFS_NT40_ENV
263     struct afs_stat status;
264     register int tsize = getdtablesize();
265     register int i;
266     for (i = 0; i < tsize; i++) {
267         if (afs_fstat(i, &status) != -1) {
268             printf("%d: dev %x, inode %u, length %u, type/mode %x\n", i,
269                    status.st_dev, status.st_ino, status.st_size,
270                    status.st_mode);
271         }
272     }
273     fflush(stdout);
274     ResetCheckDescriptors();
275     return 0;
276 #endif
277 }                               /*CheckDescriptors */
278
279
280 #ifdef AFS_PTHREAD_ENV
281 void
282 CheckSignal_Signal(x)
283 {
284     CheckSignal();
285 }
286
287 void
288 ShutDown_Signal(x)
289 {
290     ShutDown();
291 }
292
293 void
294 CheckDescriptors_Signal(x)
295 {
296     CheckDescriptors();
297 }
298 #else /* AFS_PTHREAD_ENV */
299 void
300 CheckSignal_Signal(x)
301 {
302     IOMGR_SoftSig(CheckSignal, 0);
303 }
304
305 void
306 ShutDown_Signal(x)
307 {
308     IOMGR_SoftSig(ShutDown, 0);
309 }
310
311 void
312 CheckDescriptors_Signal(x)
313 {
314     IOMGR_SoftSig(CheckDescriptors, 0);
315 }
316 #endif /* AFS_PTHREAD_ENV */
317
318 /* check whether caller is authorized to manage RX statistics */
319 int
320 fs_rxstat_userok(struct rx_call *call)
321 {
322     return afsconf_SuperUser(confDir, call, NULL);
323 }
324
325 static void
326 ResetCheckSignal(void)
327 {
328     int signo;
329
330 #if defined(AFS_HPUX_ENV)
331     signo = SIGPOLL;
332 #else
333 #if defined(AFS_NT40_ENV)
334     signo = SIGUSR2;
335 #else
336     signo = SIGXCPU;
337 #endif
338 #endif
339
340 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
341     softsig_signal(signo, CheckSignal_Signal);
342 #else
343     signal(signo, CheckSignal_Signal);
344 #endif
345 }
346
347 static void
348 ResetCheckDescriptors(void)
349 {
350 #ifndef AFS_NT40_ENV
351 #if defined(AFS_PTHREAD_ENV)
352     softsig_signal(SIGTERM, CheckDescriptors_Signal);
353 #else
354     (void)signal(SIGTERM, CheckDescriptors_Signal);
355 #endif
356 #endif
357 }
358
359 #if defined(AFS_PTHREAD_ENV)
360 char *
361 threadNum(void)
362 {
363     return pthread_getspecific(rx_thread_id_key);
364 }
365 #endif
366
367 /* proc called by rxkad module to get a key */
368 static int
369 get_key(char *arock, register afs_int32 akvno, char *akey)
370 {
371     /* find the key */
372     static struct afsconf_key tkey;
373     register afs_int32 code;
374
375     if (!confDir) {
376         ViceLog(0, ("conf dir not open\n"));
377         return 1;
378     }
379     code = afsconf_GetKey(confDir, akvno, tkey.key);
380     if (code) {
381         ViceLog(0, ("afsconf_GetKey failure: kvno %d code %d\n", akvno, code));
382         return code;
383     }
384     memcpy(akey, tkey.key, sizeof(tkey.key));
385     return 0;
386
387 }                               /*get_key */
388
389 #ifndef AFS_NT40_ENV
390 int
391 viced_syscall(afs_uint32 a3, afs_uint32 a4, void *a5)
392 {
393     afs_uint32 rcode;
394     void (*old) ();
395
396 #ifndef AFS_LINUX20_ENV
397     old = (void (*)())signal(SIGSYS, SIG_IGN);
398 #endif
399     rcode = syscall(AFS_SYSCALL, 28 /* AFSCALL_CALL */ , a3, a4, a5);
400 #ifndef AFS_LINUX20_ENV
401     signal(SIGSYS, old);
402 #endif
403
404     return rcode;
405 }
406 #endif
407
408 #if !defined(AFS_NT40_ENV)
409 #include "AFS_component_version_number.c"
410 #endif /* !AFS_NT40_ENV */
411
412 #define MAXADMINNAME 64
413 char adminName[MAXADMINNAME];
414
415 static void
416 CheckAdminName()
417 {
418     int fd = 0;
419     struct afs_stat status;
420
421     if ((afs_stat("/AdminName", &status)) ||    /* if file does not exist */
422         (status.st_size <= 0) ||        /* or it is too short */
423         (status.st_size >= (MAXADMINNAME)) ||   /* or it is too long */
424         !(fd = afs_open("/AdminName", O_RDONLY, 0))) {  /* or the open fails */
425         strcpy(adminName, "System:Administrators");     /* use the default name */
426     } else {
427         (void)read(fd, adminName, status.st_size);      /* use name from the file */
428     }
429     if (fd)
430         close(fd);              /* close fd if it was opened */
431
432 }                               /*CheckAdminName */
433
434
435 static void
436 setThreadId(char *s)
437 {
438 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
439     /* set our 'thread-id' so that the host hold table works */
440     MUTEX_ENTER(&rx_stats_mutex);       /* protects rxi_pthread_hinum */
441     ++rxi_pthread_hinum;
442     pthread_setspecific(rx_thread_id_key, (void *)rxi_pthread_hinum);
443     MUTEX_EXIT(&rx_stats_mutex);
444     ViceLog(0,
445             ("Set thread id %d for '%s'\n",
446              pthread_getspecific(rx_thread_id_key), s));
447 #endif
448 }
449
450 /* This LWP does things roughly every 5 minutes */
451 static void
452 FiveMinuteCheckLWP()
453 {
454     static int msg = 0;
455     char tbuffer[32];
456
457     ViceLog(1, ("Starting five minute check process\n"));
458     setThreadId("FiveMinuteCheckLWP");
459
460 #ifdef AFS_DEMAND_ATTACH_FS
461     FS_STATE_WRLOCK;
462     while (fs_state.mode == FS_MODE_NORMAL) {
463         fs_state.FiveMinuteLWP_tranquil = 1;
464         FS_STATE_UNLOCK;
465 #else
466     while (1) {
467 #endif
468
469 #ifdef AFS_PTHREAD_ENV
470         sleep(fiveminutes);
471 #else /* AFS_PTHREAD_ENV */
472         IOMGR_Sleep(fiveminutes);
473 #endif /* AFS_PTHREAD_ENV */
474
475 #ifdef AFS_DEMAND_ATTACH_FS
476         FS_STATE_WRLOCK;
477         if (fs_state.mode != FS_MODE_NORMAL) {
478             break;
479         }
480         fs_state.FiveMinuteLWP_tranquil = 0;
481         FS_STATE_UNLOCK;
482 #endif
483
484         /* close the log so it can be removed */
485         ReOpenLog(AFSDIR_SERVER_FILELOG_FILEPATH);      /* don't trunc, just append */
486         ViceLog(2, ("Cleaning up timed out callbacks\n"));
487         if (CleanupTimedOutCallBacks())
488             ViceLog(5, ("Timed out callbacks deleted\n"));
489         ViceLog(2, ("Set disk usage statistics\n"));
490         VSetDiskUsage();
491         if (FS_registered == 1)
492             Do_VLRegisterRPC();
493         /* Force wakeup in case we missed something; pthreads does timedwait */
494 #ifndef AFS_PTHREAD_ENV
495         LWP_NoYieldSignal(fsync_wait);
496 #endif
497         if (printBanner && (++msg & 1)) {       /* Every 10 minutes */
498             time_t now = FT_ApproxTime();
499             if (console != NULL) {
500 #ifndef AFS_QUIETFS_ENV
501                 fprintf(console, "File server is running at %s\r",
502                         afs_ctime(&now, tbuffer, sizeof(tbuffer)));
503 #endif /* AFS_QUIETFS_ENV */
504                 ViceLog(2,
505                         ("File server is running at %s\n",
506                          afs_ctime(&now, tbuffer, sizeof(tbuffer))));
507             }
508         }
509 #ifdef AFS_DEMAND_ATTACH_FS
510         FS_STATE_WRLOCK;
511 #endif
512     }
513 #ifdef AFS_DEMAND_ATTACH_FS
514     fs_state.FiveMinuteLWP_tranquil = 1;
515     FS_LOCK;
516     assert(pthread_cond_broadcast(&fs_state.worker_done_cv)==0);
517     FS_UNLOCK;
518     FS_STATE_UNLOCK;
519 #endif
520 }                               /*FiveMinuteCheckLWP */
521
522
523 /* This LWP does host checks every 5 minutes:  it should not be used for
524  * other 5 minute activities because it may be delayed by timeouts when
525  * it probes the workstations
526  */
527
528 static void
529 HostCheckLWP()
530 {
531     ViceLog(1, ("Starting Host check process\n"));
532     setThreadId("HostCheckLWP");
533 #ifdef AFS_DEMAND_ATTACH_FS
534     FS_STATE_WRLOCK;
535     while (fs_state.mode == FS_MODE_NORMAL) {
536         fs_state.HostCheckLWP_tranquil = 1;
537         FS_STATE_UNLOCK;
538 #else
539     while(1) {
540 #endif
541
542 #ifdef AFS_PTHREAD_ENV
543         sleep(fiveminutes);
544 #else /* AFS_PTHREAD_ENV */
545         IOMGR_Sleep(fiveminutes);
546 #endif /* AFS_PTHREAD_ENV */
547
548 #ifdef AFS_DEMAND_ATTACH_FS
549         FS_STATE_WRLOCK;
550         if (fs_state.mode != FS_MODE_NORMAL) {
551             break;
552         }
553         fs_state.HostCheckLWP_tranquil = 0;
554         FS_STATE_UNLOCK;
555 #endif
556
557         ViceLog(2, ("Checking for dead venii & clients\n"));
558         h_CheckHosts();
559
560 #ifdef AFS_DEMAND_ATTACH_FS
561         FS_STATE_WRLOCK;
562 #endif
563     }
564 #ifdef AFS_DEMAND_ATTACH_FS
565     fs_state.HostCheckLWP_tranquil = 1;
566     FS_LOCK;
567     assert(pthread_cond_broadcast(&fs_state.worker_done_cv)==0);
568     FS_UNLOCK;
569     FS_STATE_UNLOCK;
570 #endif
571 }                               /*HostCheckLWP */
572
573 /* This LWP does fsync checks every 5 minutes:  it should not be used for
574  * other 5 minute activities because it may be delayed by timeouts when
575  * it probes the workstations
576  */
577 static void
578 FsyncCheckLWP()
579 {
580     afs_int32 code;
581 #ifdef AFS_PTHREAD_ENV
582     struct timespec fsync_next;
583 #endif
584     ViceLog(1, ("Starting fsync check process\n"));
585
586     setThreadId("FsyncCheckLWP");
587
588 #ifdef AFS_PTHREAD_ENV
589     assert(pthread_cond_init(&fsync_cond, NULL) == 0);
590     assert(pthread_mutex_init(&fsync_glock_mutex, NULL) == 0);
591 #endif
592
593 #ifdef AFS_DEMAND_ATTACH_FS
594     FS_STATE_WRLOCK;
595     while (fs_state.mode == FS_MODE_NORMAL) {
596         fs_state.FsyncCheckLWP_tranquil = 1;
597         FS_STATE_UNLOCK;
598 #else
599     while(1) {
600 #endif
601         FSYNC_LOCK;
602 #ifdef AFS_PTHREAD_ENV
603         /* rounding is fine */
604         fsync_next.tv_nsec = 0;
605         fsync_next.tv_sec = time(0) + fiveminutes;
606
607         code =
608             pthread_cond_timedwait(&fsync_cond, &fsync_glock_mutex,
609                                    &fsync_next);
610         if (code != 0 && code != ETIMEDOUT)
611             ViceLog(0, ("pthread_cond_timedwait returned %d\n", code));
612 #else /* AFS_PTHREAD_ENV */
613         if ((code = LWP_WaitProcess(fsync_wait)) != LWP_SUCCESS)
614             ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
615 #endif /* AFS_PTHREAD_ENV */
616         FSYNC_UNLOCK;
617
618 #ifdef AFS_DEMAND_ATTACH_FS
619         FS_STATE_WRLOCK;
620         if (fs_state.mode != FS_MODE_NORMAL) {
621             break;
622         }
623         fs_state.FsyncCheckLWP_tranquil = 0;
624         FS_STATE_UNLOCK;
625 #endif /* AFS_DEMAND_ATTACH_FS */
626
627         ViceLog(2, ("Checking for fsync events\n"));
628         do {
629             code = BreakLaterCallBacks();
630         } while (code != 0);
631 #ifdef AFS_DEMAND_ATTACH_FS
632         FS_STATE_WRLOCK;
633 #endif
634     }
635 #ifdef AFS_DEMAND_ATTACH_FS
636     fs_state.FsyncCheckLWP_tranquil = 1;
637     FS_LOCK;
638     assert(pthread_cond_broadcast(&fs_state.worker_done_cv)==0);
639     FS_UNLOCK;
640     FS_STATE_UNLOCK;
641 #endif /* AFS_DEMAND_ATTACH_FS */
642 }
643
644 /*------------------------------------------------------------------------
645  * PRIVATE ClearXStatValues
646  *
647  * Description:
648  *      Initialize all of the values collected via the xstat
649  *      interface.
650  *
651  * Arguments:
652  *      None.
653  *
654  * Returns:
655  *      Nothing.
656  *
657  * Environment:
658  *      Must be called during File Server initialization.
659  *
660  * Side Effects:
661  *      As advertised.
662  *------------------------------------------------------------------------*/
663
664 static void
665 ClearXStatValues()
666 {                               /*ClearXStatValues */
667
668     struct fs_stats_opTimingData *opTimeP;      /*Ptr to timing struct */
669     struct fs_stats_xferData *opXferP;  /*Ptr to xfer struct */
670     int i;                      /*Loop counter */
671
672     /*
673      * Zero all xstat-related structures.
674      */
675     memset((char *)(&afs_perfstats), 0, sizeof(struct afs_PerfStats));
676 #if FS_STATS_DETAILED
677     memset((char *)(&afs_FullPerfStats), 0,
678            sizeof(struct fs_stats_FullPerfStats));
679
680     /*
681      * That's not enough.  We have to set reasonable minima for
682      * time and xfer values in the detailed stats.
683      */
684     opTimeP = &(afs_FullPerfStats.det.rpcOpTimes[0]);
685     for (i = 0; i < FS_STATS_NUM_RPC_OPS; i++, opTimeP++)
686         opTimeP->minTime.tv_sec = 999999;
687
688     opXferP = &(afs_FullPerfStats.det.xferOpTimes[0]);
689     for (i = 0; i < FS_STATS_NUM_XFER_OPS; i++, opXferP++) {
690         opXferP->minTime.tv_sec = 999999;
691         opXferP->minBytes = 999999999;
692     }
693
694     /*
695      * There's more.  We have to set our unique system identifier, as
696      * declared in param.h.  If such a thing is not defined, we bitch
697      * and declare ourselves to be an unknown system type.
698      */
699 #ifdef SYS_NAME_ID
700     afs_perfstats.sysname_ID = SYS_NAME_ID;
701 #else
702 #ifndef AFS_NT40_ENV
703     ViceLog(0, ("Sys name ID constant not defined in param.h!!\n"));
704     ViceLog(0, ("[Choosing ``undefined'' sys name ID.\n"));
705 #endif
706     afs_perfstats.sysname_ID = SYS_NAME_ID_UNDEFINED;
707 #endif /* SYS_NAME_ID */
708 #endif
709
710 }                               /*ClearXStatValues */
711
712
713 static void
714 PrintCounters()
715 {
716     int dirbuff, dircall, dirio;
717     struct timeval tpl;
718     int workstations, activeworkstations, delworkstations;
719     int processSize = 0;
720     char tbuffer[32];
721
722     TM_GetTimeOfDay(&tpl, 0);
723     Statistics = 1;
724     ViceLog(0,
725             ("Vice was last started at %s\n",
726              afs_ctime(&StartTime, tbuffer, sizeof(tbuffer))));
727
728 #ifdef AFS_DEMAND_ATTACH_FS
729     /* XXX perhaps set extended stats verbosity flags
730      * based upon LogLevel ?? */
731     VPrintExtendedCacheStats(VOL_STATS_PER_CHAIN2);
732 #endif
733     VPrintCacheStats();
734     VPrintDiskStats();
735     DStat(&dirbuff, &dircall, &dirio);
736     ViceLog(0,
737             ("With %d directory buffers; %d reads resulted in %d read I/Os\n",
738              dirbuff, dircall, dirio));
739     rx_PrintStats(stderr);
740     h_PrintStats();
741     PrintCallBackStats();
742 #ifdef AFS_NT40_ENV
743     processSize = -1;           /* TODO: */
744 #else
745     processSize = (int)((long)sbrk(0) >> 10);
746 #endif
747     ViceLog(0,
748             ("There are %d connections, process size %d\n",
749              CurrentConnections, processSize));
750     h_GetWorkStats(&workstations, &activeworkstations, &delworkstations,
751                    tpl.tv_sec - 15 * 60);
752     ViceLog(0,
753             ("There are %d workstations, %d are active (req in < 15 mins), %d marked \"down\"\n",
754              workstations, activeworkstations, delworkstations));
755     Statistics = 0;
756
757 }                               /*PrintCounters */
758
759
760
761 static int
762 CheckSignal()
763 {
764     if (FS_registered > 0) {
765         /*
766          * We have proper ip addresses; tell the vlserver what we got; the following
767          * routine will do the proper reporting for us
768          */
769         Do_VLRegisterRPC();
770     }
771     h_DumpHosts();
772     h_PrintClients();
773     DumpCallBackState();
774     PrintCounters();
775     ResetCheckSignal();
776     return 0;
777 }                               /*CheckSignal */
778
779 void
780 ShutDownAndCore(int dopanic)
781 {
782     time_t now = time(0);
783     char tbuffer[32];
784
785     /* do not allows new reqests to be served from now on, all new requests
786      * are returned with an error code of RX_RESTARTING ( transient failure ) */
787     rx_SetRxTranquil();         /* dhruba */
788
789 #ifdef AFS_DEMAND_ATTACH_FS
790     FS_STATE_WRLOCK;
791     fs_state.mode = FS_MODE_SHUTDOWN;
792     FS_STATE_UNLOCK;
793 #endif
794
795     ViceLog(0,
796             ("Shutting down file server at %s",
797              afs_ctime(&now, tbuffer, sizeof(tbuffer))));
798     if (dopanic)
799         ViceLog(0, ("ABNORMAL SHUTDOWN, see core file.\n"));
800 #ifndef AFS_QUIETFS_ENV
801     if (console != NULL) {
802         fprintf(console, "File server restart/shutdown received at %s\r",
803                 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
804     }
805 #endif
806     DFlush();
807     if (!dopanic)
808         PrintCounters();
809
810     /* shut down volume package */
811     VShutdown();
812
813 #ifdef AFS_DEMAND_ATTACH_FS
814     if (fs_state.options.fs_state_save) {
815         /* 
816          * demand attach fs
817          * save fileserver state to disk */
818
819         /* make sure background threads have finished all of their asynchronous 
820          * work on host and callback structures */
821         FS_STATE_RDLOCK;
822         while (!fs_state.FiveMinuteLWP_tranquil ||
823                !fs_state.HostCheckLWP_tranquil ||
824                !fs_state.FsyncCheckLWP_tranquil) {
825             FS_LOCK;
826             FS_STATE_UNLOCK;
827             ViceLog(0, ("waiting for background host/callback threads to quiesce before saving fileserver state...\n"));
828             assert(pthread_cond_wait(&fs_state.worker_done_cv, &fileproc_glock_mutex) == 0);
829             FS_UNLOCK;
830             FS_STATE_RDLOCK;
831         }
832
833         /* ok. it should now be fairly safe. let's do the state dump */
834         fs_stateSave();
835     }
836 #endif /* AFS_DEMAND_ATTACH_FS */
837
838     if (debugFile) {
839         rx_PrintStats(debugFile);
840         fflush(debugFile);
841     }
842     if (console != NULL) {
843         now = time(0);
844         if (dopanic) {
845 #ifndef AFS_QUIETFS_ENV
846             fprintf(console, "File server has terminated abnormally at %s\r",
847                     afs_ctime(&now, tbuffer, sizeof(tbuffer)));
848 #endif
849             ViceLog(0,
850                     ("File server has terminated abnormally at %s\n",
851                      afs_ctime(&now, tbuffer, sizeof(tbuffer))));
852         } else {
853 #ifndef AFS_QUIETFS_ENV
854             fprintf(console, "File server has terminated normally at %s\r",
855                     afs_ctime(&now, tbuffer, sizeof(tbuffer)));
856 #endif
857             ViceLog(0,
858                     ("File server has terminated normally at %s\n",
859                      afs_ctime(&now, tbuffer, sizeof(tbuffer))));
860         }
861     }
862
863     exit(0);
864 }
865
866 int
867 ShutDown(void)
868 {                               /* backward compatibility */
869     ShutDownAndCore(DONTPANIC);
870     return 0;
871 }
872
873
874 static void
875 FlagMsg()
876 {
877     char buffer[2048];
878
879     /* default supports help flag */
880
881     strcpy(buffer, "Usage: fileserver ");
882     strcpy(buffer, "[-auditlog <log path>] ");
883     strcat(buffer, "[-d <debug level>] ");
884     strcat(buffer, "[-p <number of processes>] ");
885     strcat(buffer, "[-spare <number of spare blocks>] ");
886     strcat(buffer, "[-pctspare <percentage spare>] ");
887     strcat(buffer, "[-b <buffers>] ");
888     strcat(buffer, "[-l <large vnodes>] ");
889     strcat(buffer, "[-s <small vnodes>] ");
890     strcat(buffer, "[-vc <volume cachesize>] ");
891     strcat(buffer, "[-w <call back wait interval>] ");
892     strcat(buffer, "[-cb <number of call backs>] ");
893     strcat(buffer, "[-banner (print banner every 10 minutes)] ");
894     strcat(buffer, "[-novbc (whole volume cbs disabled)] ");
895     strcat(buffer, "[-implicit <admin mode bits: rlidwka>] ");
896     strcat(buffer, "[-readonly (read-only file server)] ");
897     strcat(buffer,
898            "[-hr <number of hours between refreshing the host cps>] ");
899     strcat(buffer, "[-busyat <redirect clients when queue > n>] ");
900     strcat(buffer, "[-nobusy <no VBUSY before a volume is attached>] ");
901     strcat(buffer, "[-rxpck <number of rx extra packets>] ");
902     strcat(buffer, "[-rxdbg (enable rx debugging)] ");
903     strcat(buffer, "[-rxdbge (enable rxevent debugging)] ");
904     strcat(buffer, "[-rxmaxmtu <bytes>] ");
905     strcat(buffer, "[-rxbind (bind the Rx socket to one address)] ");
906 #ifdef AFS_DEMAND_ATTACH_FS
907     strcat(buffer, "[-fs-state-dont-save (disable state save during shutdown)] ");
908     strcat(buffer, "[-fs-state-dont-restore (disable state restore during startup)] ");
909     strcat(buffer, "[-fs-state-verify <none|save|restore|both> (default is both)] ");
910     strcat(buffer, "[-vattachpar <max number of volume attach/shutdown threads> (default is 1)] ");
911     strcat(buffer, "[-vhashsize <log(2) of number of volume hash buckets> (default is 8)] ");
912     strcat(buffer, "[-vlrudisable (disable VLRU functionality)] ");
913     strcat(buffer, "[-vlruthresh <minutes before unused volumes become eligible for soft detach> (default is 2 hours)] ");
914     strcat(buffer, "[-vlruinterval <seconds between VLRU scans> (default is 2 minutes)] ");
915     strcat(buffer, "[-vlrumax <max volumes to soft detach in one VLRU scan> (default is 8)] ");
916 #elif AFS_PTHREAD_ENV
917     strcat(buffer, "[-vattachpar <number of volume attach threads> (default is 1)] ");
918 #endif
919 #ifdef  AFS_AIX32_ENV
920     strcat(buffer, "[-m <min percentage spare in partition>] ");
921 #endif
922 #if defined(AFS_SGI_ENV)
923     strcat(buffer, "[-lock (keep fileserver from swapping)] ");
924 #endif
925     strcat(buffer, "[-L (large server conf)] ");
926     strcat(buffer, "[-S (small server conf)] ");
927     strcat(buffer, "[-k <stack size>] ");
928     strcat(buffer, "[-realm <Kerberos realm name>] ");
929     strcat(buffer, "[-udpsize <size of socket buffer in bytes>] ");
930     strcat(buffer, "[-sendsize <size of send buffer in bytes>] ");
931     strcat(buffer, "[-abortthreshold <abort threshold>] ");
932 /*   strcat(buffer, "[-enable_peer_stats] "); */
933 /*   strcat(buffer, "[-enable_process_stats] "); */
934     strcat(buffer, "[-help]\n");
935 /*
936     ViceLog(0, ("%s", buffer));
937 */
938
939     printf("%s", buffer);
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], "-rxbind")) {
1284             rxBind = 1;
1285         } else if (!strcmp(argv[i], "-rxmaxmtu")) {
1286             if ((i + 1) >= argc) {
1287                 fprintf(stderr, "missing argument for -rxmaxmtu\n"); 
1288                 return -1; 
1289             }
1290             rxMaxMTU = atoi(argv[++i]);
1291             if ((rxMaxMTU < RX_MIN_PACKET_SIZE) || 
1292                 (rxMaxMTU > RX_MAX_PACKET_DATA_SIZE)) {
1293                 printf("rxMaxMTU %d%% invalid; must be between %d-%d\n",
1294                        rxMaxMTU, RX_MIN_PACKET_SIZE, 
1295                        RX_MAX_PACKET_DATA_SIZE);
1296                 return -1;
1297             }
1298         } else if (!strcmp(argv[i], "-realm")) {
1299             extern char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
1300             extern int  num_lrealms;
1301             if ((i + 1) >= argc) {
1302                 fprintf(stderr, "missing argument for -realm\n"); 
1303                 return -1; 
1304             }
1305             if (strlen(argv[++i]) >= AFS_REALM_SZ) {
1306                 printf
1307                     ("-realm argument must contain fewer than %d characters.\n",
1308                      AFS_REALM_SZ);
1309                 return -1;
1310             }
1311             if (num_lrealms == -1) 
1312                 num_lrealms = 0;
1313             if (num_lrealms >= AFS_NUM_LREALMS) {
1314                 printf
1315                     ("a maximum of %d -realm arguments can be specified.\n",
1316                      AFS_NUM_LREALMS);
1317                 return -1;
1318             }
1319             strncpy(local_realms[num_lrealms++], argv[i], AFS_REALM_SZ);
1320         } else if (!strcmp(argv[i], "-udpsize")) {
1321             if ((i + 1) >= argc) {
1322                 printf("You have to specify -udpsize <integer value>\n");
1323                 return -1;
1324             }
1325             bufSize = atoi(argv[++i]);
1326             if (bufSize < rx_GetMinUdpBufSize())
1327                 printf
1328                     ("Warning:udpsize %d is less than minimum %d; ignoring\n",
1329                      bufSize, rx_GetMinUdpBufSize());
1330             else
1331                 udpBufSize = bufSize;
1332         } else if (!strcmp(argv[i], "-sendsize")) {
1333             if ((i + 1) >= argc) {
1334                 printf("You have to specify -sendsize <integer value>\n");
1335                 return -1;
1336             }
1337             bufSize = atoi(argv[++i]);
1338             if (bufSize < 16384)
1339                 printf
1340                     ("Warning:sendsize %d is less than minimum %d; ignoring\n",
1341                      bufSize, 16384);
1342             else
1343                 sendBufSize = bufSize;
1344         } else if (!strcmp(argv[i], "-enable_peer_stats")) {
1345             rx_enablePeerRPCStats();
1346         } else if (!strcmp(argv[i], "-enable_process_stats")) {
1347             rx_enableProcessRPCStats();
1348         }
1349         else if (strcmp(argv[i], "-auditlog") == 0) {
1350             int tempfd, flags;
1351             FILE *auditout;
1352             char oldName[MAXPATHLEN];
1353             char *fileName = argv[++i];
1354             
1355 #ifndef AFS_NT40_ENV
1356             struct stat statbuf;
1357             
1358             if ((lstat(fileName, &statbuf) == 0) 
1359                 && (S_ISFIFO(statbuf.st_mode))) {
1360                 flags = O_WRONLY | O_NONBLOCK;
1361             } else 
1362 #endif
1363             {
1364                 strcpy(oldName, fileName);
1365                 strcat(oldName, ".old");
1366                 renamefile(fileName, oldName);
1367                 flags = O_WRONLY | O_TRUNC | O_CREAT;
1368             }
1369             tempfd = open(fileName, flags, 0666);
1370             if (tempfd > -1) {
1371                 auditout = fdopen(tempfd, "a");
1372                 if (auditout) {
1373                     osi_audit_file(auditout);
1374                 } else
1375                     printf("Warning: auditlog %s not writable, ignored.\n", fileName);
1376             } else
1377                 printf("Warning: auditlog %s not writable, ignored.\n", fileName);
1378         }
1379 #ifndef AFS_NT40_ENV
1380         else if (strcmp(argv[i], "-syslog") == 0) {
1381             /* set syslog logging flag */
1382             serverLogSyslog = 1;
1383         } else if (strncmp(argv[i], "-syslog=", 8) == 0) {
1384             serverLogSyslog = 1;
1385             serverLogSyslogFacility = atoi(argv[i] + 8);
1386         }
1387 #endif
1388         else if (strcmp(argv[i], "-mrafslogs") == 0) {
1389             /* set syslog logging flag */
1390             mrafsStyleLogs = 1;
1391         } 
1392         else {
1393             return (-1);
1394         }
1395     }
1396     if (SawS && SawL) {
1397         printf("Only one of -L, or -S must be specified\n");
1398         return -1;
1399     }
1400     if (SawS) {
1401         if (!Sawrxpck)
1402             rxpackets = 100;
1403         if (!Sawsmall)
1404             nSmallVns = 200;
1405         if (!Sawlarge)
1406             large = 200;
1407         if (!Sawcbs)
1408             numberofcbs = 20000;
1409         if (!Sawlwps)
1410             lwps = 6;
1411         if (!Sawbufs)
1412             buffs = 70;
1413         if (!SawVC)
1414             volcache = 200;
1415     }
1416     if (SawL) {
1417         if (!Sawrxpck)
1418             rxpackets = 200;
1419         if (!Sawsmall)
1420             nSmallVns = 600;
1421         if (!Sawlarge)
1422             large = 600;
1423         if (!Sawcbs)
1424             numberofcbs = 64000;
1425         if (!Sawlwps)
1426             lwps = 12;
1427         if (!Sawbufs)
1428             buffs = 120;
1429         if (!SawVC)
1430             volcache = 600;
1431     }
1432     if (!Sawbusy)
1433         busy_threshold = 3 * rxpackets / 2;
1434
1435     return (0);
1436
1437 }                               /*ParseArgs */
1438
1439
1440 #define MAXPARMS 15
1441
1442 static void
1443 NewParms(int initializing)
1444 {
1445     static struct afs_stat sbuf;
1446     register int i, fd;
1447     char *parms;
1448     char *argv[MAXPARMS];
1449     register int argc;
1450
1451     if (!(afs_stat("/vice/file/parms", &sbuf))) {
1452         parms = (char *)malloc(sbuf.st_size);
1453         if (!parms)
1454             return;
1455         fd = afs_open("parms", O_RDONLY, 0666);
1456         if (fd <= 0) {
1457             ViceLog(0, ("Open for parms failed with errno = %d\n", errno));
1458             return;
1459         }
1460
1461         i = read(fd, parms, sbuf.st_size);
1462         close(fd);
1463         if (i != sbuf.st_size) {
1464             if (i < 0) {
1465                 ViceLog(0, ("Read on parms failed with errno = %d\n", errno));
1466             } else {
1467                 ViceLog(0,
1468                         ("Read on parms failed; expected %d bytes but read %d\n",
1469                          sbuf.st_size, i));
1470             }
1471             free(parms);
1472             return;
1473         }
1474
1475         for (i = 0; i < MAXPARMS; argv[i++] = 0);
1476
1477         for (argc = i = 0; i < sbuf.st_size; i++) {
1478             if ((*(parms + i) != ' ') && (*(parms + i) != '\n')) {
1479                 if (argv[argc] == 0)
1480                     argv[argc] = (parms + i);
1481             } else {
1482                 *(parms + i) = '\0';
1483                 if (argv[argc] != 0) {
1484                     if (++argc == MAXPARMS)
1485                         break;
1486                 }
1487                 while ((*(parms + i + 1) == ' ')
1488                        || (*(parms + i + 1) == '\n'))
1489                     i++;
1490             }
1491         }
1492         if (ParseArgs(argc, argv) == 0) {
1493             ViceLog(0, ("Change parameters to:"));
1494         } else {
1495             ViceLog(0, ("Invalid parameter in:"));
1496         }
1497         for (i = 0; i < argc; i++) {
1498             ViceLog(0, (" %s", argv[i]));
1499         }
1500         ViceLog(0, ("\n"));
1501         free(parms);
1502     } else if (!initializing)
1503         ViceLog(0,
1504                 ("Received request to change parms but no parms file exists\n"));
1505
1506 }                               /*NewParms */
1507
1508
1509 /* Miscellaneous routines */
1510 void
1511 Die(char *msg)
1512 {
1513     ViceLog(0, ("%s\n", msg));
1514     assert(0);
1515
1516 }                               /*Die */
1517
1518
1519 afs_int32
1520 InitPR()
1521 {
1522     int code;
1523
1524     /*
1525      * If this fails, it's because something major is wrong, and is not
1526      * likely to be time dependent.
1527      */
1528     code = pr_Initialize(2, AFSDIR_SERVER_ETC_DIRPATH, 0);
1529     if (code != 0) {
1530         ViceLog(0,
1531                 ("Couldn't initialize protection library; code=%d.\n", code));
1532         return code;
1533     }
1534
1535 #ifdef AFS_PTHREAD_ENV
1536     assert(pthread_key_create(&viced_uclient_key, NULL) == 0);
1537 #endif
1538
1539     SystemId = SYSADMINID;
1540     SystemAnyUser = ANYUSERID;
1541     SystemAnyUserCPS.prlist_len = 0;
1542     SystemAnyUserCPS.prlist_val = NULL;
1543     AnonCPS.prlist_len = 0;
1544     AnonCPS.prlist_val = NULL;
1545     while (1) {
1546         code = pr_GetCPS(SystemAnyUser, &SystemAnyUserCPS);
1547         if (code != 0) {
1548             ViceLog(0,
1549                     ("Couldn't get CPS for AnyUser, will try again in 30 seconds; code=%d.\n",
1550                      code));
1551             goto sleep;
1552         }
1553         code = pr_GetCPS(ANONYMOUSID, &AnonCPS);
1554         if (code != 0) {
1555             ViceLog(0,
1556                     ("Couldn't get Anonymous CPS, exiting; code=%d.\n",
1557                      code));
1558             return -1;
1559         }
1560         AnonymousID = ANONYMOUSID;
1561         return 0;
1562       sleep:
1563 #ifdef AFS_PTHREAD_ENV
1564         sleep(30);
1565 #else /* AFS_PTHREAD_ENV */
1566         IOMGR_Sleep(30);
1567 #endif /* AFS_PTHREAD_ENV */
1568     }
1569 }                               /*InitPR */
1570
1571 struct rx_connection *serverconns[MAXSERVERS];
1572 struct ubik_client *cstruct;
1573
1574 afs_int32
1575 vl_Initialize(const char *confDir)
1576 {
1577     afs_int32 code, scIndex = 0, i;
1578     struct afsconf_dir *tdir;
1579     struct rx_securityClass *sc;
1580     struct afsconf_cell info;
1581
1582     tdir = afsconf_Open(confDir);
1583     if (!tdir) {
1584         ViceLog(0,
1585                 ("Could not open configuration directory (%s).\n", confDir));
1586         exit(1);
1587     }
1588     code = afsconf_ClientAuth(tdir, &sc, &scIndex);
1589     if (code) {
1590         ViceLog(0, ("Could not get security object for localAuth\n"));
1591         exit(1);
1592     }
1593     code = afsconf_GetCellInfo(tdir, NULL, AFSCONF_VLDBSERVICE, &info);
1594     if (info.numServers > MAXSERVERS) {
1595         ViceLog(0,
1596                 ("vl_Initialize: info.numServers=%d (> MAXSERVERS=%d)\n",
1597                  info.numServers, MAXSERVERS));
1598         exit(1);
1599     }
1600     for (i = 0; i < info.numServers; i++)
1601         serverconns[i] =
1602             rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
1603                              info.hostAddr[i].sin_port, USER_SERVICE_ID, sc,
1604                              scIndex);
1605     code = ubik_ClientInit(serverconns, &cstruct);
1606     if (code) {
1607         ViceLog(0, ("vl_Initialize: ubik client init failed.\n"));
1608         return code;
1609     }
1610     return 0;
1611 }
1612
1613 #define SYSIDMAGIC      0x88aabbcc
1614 #define SYSIDVERSION    1
1615
1616 afs_int32
1617 ReadSysIdFile()
1618 {
1619     afs_int32 fd, nentries, i;
1620     struct versionStamp vsn;
1621     struct afs_stat status;
1622     afsUUID uuid;
1623
1624     if ((afs_stat(AFSDIR_SERVER_SYSID_FILEPATH, &status))
1625         || (status.st_size <= 0)) {
1626         ViceLog(0, ("%s: doesn't exist\n", AFSDIR_SERVER_SYSID_FILEPATH));
1627         return ENOENT;
1628     }
1629     if (!(fd = afs_open(AFSDIR_SERVER_SYSID_FILEPATH, O_RDONLY, 0))) {
1630         ViceLog(0,
1631                 ("%s: can't open (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH,
1632                  errno));
1633         return EIO;
1634     }
1635     if ((i = read(fd, (char *)&vsn, sizeof(vsn))) != sizeof(vsn)) {
1636         ViceLog(0,
1637                 ("%s: Read failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH,
1638                  errno));
1639         return EIO;
1640     }
1641     if (vsn.magic != SYSIDMAGIC) {
1642         ViceLog(0,
1643                 ("%s: wrong magic %x (we support %x)\n",
1644                  AFSDIR_SERVER_SYSID_FILEPATH, vsn.magic, SYSIDMAGIC));
1645         return EIO;
1646     }
1647     if (vsn.version != SYSIDVERSION) {
1648         ViceLog(0,
1649                 ("%s: wrong version %d (we support %d)\n",
1650                  AFSDIR_SERVER_SYSID_FILEPATH, vsn.version, SYSIDVERSION));
1651         return EIO;
1652     }
1653     if ((i =
1654          read(fd, (char *)&uuid,
1655               sizeof(struct afsUUID))) != sizeof(struct afsUUID)) {
1656         ViceLog(0,
1657                 ("%s: read of uuid failed (%d)\n",
1658                  AFSDIR_SERVER_SYSID_FILEPATH, errno));
1659         return EIO;
1660     }
1661     afs_ntohuuid(&uuid);
1662     FS_HostUUID = uuid;
1663     if ((i =
1664          read(fd, (char *)&nentries,
1665               sizeof(afs_int32))) != sizeof(afs_int32)) {
1666         ViceLog(0,
1667                 ("%s: Read of entries failed (%d)\n",
1668                  AFSDIR_SERVER_SYSID_FILEPATH, errno));
1669         return EIO;
1670     }
1671     if (nentries <= 0 || nentries > ADDRSPERSITE) {
1672         ViceLog(0,
1673                 ("%s: invalid num of interfaces: %d\n",
1674                  AFSDIR_SERVER_SYSID_FILEPATH, nentries));
1675         return EIO;
1676     }
1677     FS_HostAddr_cnt = nentries;
1678     for (i = 0; i < nentries; i++) {
1679         if (read(fd, (char *)&FS_HostAddrs[i], sizeof(afs_int32)) !=
1680             sizeof(afs_int32)) {
1681             ViceLog(0,
1682                     ("%s: Read of addresses failed (%d)\n",
1683                      AFSDIR_SERVER_SYSID_FILEPATH, errno));
1684             FS_HostAddr_cnt = 0;        /* reset it */
1685             return EIO;
1686         }
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     assert(pthread_attr_init(&tattr) == 0);
2189     assert(pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) == 0);
2190
2191     assert(pthread_create
2192            (&serverPid, &tattr, (void *)FiveMinuteCheckLWP,
2193             &fiveminutes) == 0);
2194     assert(pthread_create
2195            (&serverPid, &tattr, (void *)HostCheckLWP, &fiveminutes) == 0);
2196     assert(pthread_create
2197            (&serverPid, &tattr, (void *)FsyncCheckLWP, &fiveminutes) == 0);
2198 #else /* AFS_PTHREAD_ENV */
2199     ViceLog(5, ("Starting LWP\n"));
2200     assert(LWP_CreateProcess
2201            (FiveMinuteCheckLWP, stack * 1024, LWP_MAX_PRIORITY - 2,
2202             (void *)&fiveminutes, "FiveMinuteChecks",
2203             &serverPid) == LWP_SUCCESS);
2204
2205     assert(LWP_CreateProcess
2206            (HostCheckLWP, stack * 1024, LWP_MAX_PRIORITY - 2,
2207             (void *)&fiveminutes, "HostCheck", &serverPid) == LWP_SUCCESS);
2208     assert(LWP_CreateProcess
2209            (FsyncCheckLWP, stack * 1024, LWP_MAX_PRIORITY - 2,
2210             (void *)&fiveminutes, "FsyncCheck", &serverPid) == LWP_SUCCESS);
2211 #endif /* AFS_PTHREAD_ENV */
2212
2213     TM_GetTimeOfDay(&tp, 0);
2214
2215 #ifndef AFS_QUIETFS_ENV
2216     if (console != NULL) { 
2217         time_t t = tp.tv_sec;
2218         fprintf(console, "File server has started at %s\r",
2219                 afs_ctime(&t, tbuffer, sizeof(tbuffer)));
2220     }
2221 #endif
2222
2223     /*
2224      * Figure out the FileServer's name and primary address.
2225      */
2226     ViceLog(0, ("Getting FileServer name...\n"));
2227     code = gethostname(FS_HostName, 64);
2228     if (code) {
2229         ViceLog(0, ("gethostname() failed\n"));
2230     }
2231     ViceLog(0, ("FileServer host name is '%s'\n", FS_HostName));
2232
2233     ViceLog(0, ("Getting FileServer address...\n"));
2234     he = gethostbyname(FS_HostName);
2235     if (!he) {
2236         ViceLog(0, ("Can't find address for FileServer '%s'\n", FS_HostName));
2237     } else {
2238         char hoststr[16];
2239         memcpy(&FS_HostAddr_NBO, he->h_addr, 4);
2240         (void)afs_inet_ntoa_r(FS_HostAddr_NBO, hoststr);
2241         FS_HostAddr_HBO = ntohl(FS_HostAddr_NBO);
2242         ViceLog(0,
2243                 ("FileServer %s has address %s (0x%x or 0x%x in host byte order)\n",
2244                  FS_HostName, hoststr, FS_HostAddr_NBO, FS_HostAddr_HBO));
2245     }
2246
2247     /* Install handler to catch the shutdown signal;
2248      * bosserver assumes SIGQUIT shutdown
2249      */
2250 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
2251     softsig_signal(SIGQUIT, ShutDown_Signal);
2252 #else
2253     (void)signal(SIGQUIT, ShutDown_Signal);
2254 #endif
2255
2256     t = tp.tv_sec;
2257     ViceLog(0,
2258             ("File Server started %s",
2259              afs_ctime(&t, tbuffer, sizeof(tbuffer))));
2260 #if FS_STATS_DETAILED
2261     afs_FullPerfStats.det.epoch.tv_sec = StartTime = tp.tv_sec;
2262 #endif
2263 #ifdef AFS_PTHREAD_ENV
2264     while (1) {
2265         sleep(1000);            /* long time */
2266     }
2267 #else /* AFS_PTHREAD_ENV */
2268     assert(LWP_WaitProcess(&parentPid) == LWP_SUCCESS);
2269 #endif /* AFS_PTHREAD_ENV */
2270 }