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