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