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