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