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