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