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