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