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