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