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