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