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