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