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