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