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