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