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