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