fileserver-readonly-support-20021028
[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
10 /*  viced.c     - File Server main loop                                  */
11 /*                                                                       */
12 /*  Date: 5/1/85                                                         */
13 /*                                                                       */
14 /*  Function    - This routine has the initialization code for           */
15 /*                FileServer II                                          */
16 /*                                                                       */
17 /* ********************************************************************** */
18
19 #include <afsconfig.h>
20 #include <afs/param.h>
21
22 RCSID("$Header$");
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <errno.h>
27 #include <sys/types.h>
28 #include <afs/procmgmt.h>  /* signal(), kill(), wait(), etc. */
29 #include <sys/stat.h>
30 #ifdef AFS_NT40_ENV
31 #include <fcntl.h>
32 #include <io.h>
33 #include <windows.h>
34 #include <WINNT/afsevent.h>
35 #else
36 #include <sys/file.h>
37 #include <netinet/in.h>
38 #include <netdb.h>
39 #include <unistd.h>     /* sysconf() */
40
41 #ifdef HAVE_STRING_H
42 #include <string.h>
43 #else
44 #ifdef HAVE_STRINGS_H
45 #include <strings.h>
46 #endif
47 #endif
48
49 #ifndef ITIMER_REAL
50 #include <sys/time.h>
51 #endif /* ITIMER_REAL */
52 #include <sys/resource.h>
53 #endif /* AFS_NT40_ENV */
54 #include <afs/stds.h>
55 #undef SHARED
56 #include <rx/xdr.h>
57 #include <afs/nfs.h>
58 #ifdef AFS_PTHREAD_ENV
59 #include <assert.h>
60 #else /* AFS_PTHREAD_ENV */
61 #include <afs/assert.h>
62 #endif /* AFS_PTHREAD_ENV */
63 #include <lwp.h>
64 #include <lock.h>
65 #include <afs/ptclient.h>
66 #include <afs/afsint.h>
67 #include <afs/vldbint.h>
68 #include <afs/errors.h>
69 #include <afs/ihandle.h>
70 #include <afs/vnode.h>
71 #include <afs/volume.h>
72 #include <afs/auth.h>
73 #include <afs/cellconfig.h>
74 #include <afs/acl.h>
75 #include <afs/prs_fs.h>
76 #include <rx/rx.h>
77 #include <rx/rxkad.h>
78 #include <afs/keys.h>
79 #include <afs/afs_args.h>
80 #include <afs/vlserver.h>
81 #include <afs/afsutil.h>
82 #include <afs/fileutil.h>
83 #ifndef AFS_NT40_ENV
84 #include <afs/netutils.h>
85 #endif
86 #include "viced.h"
87 #include "host.h"
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
95 extern int      BreakVolumeCallBacks(), InitCallBack();
96 extern  int     LogLevel, etext;
97 extern afs_int32        BlocksSpare, PctSpare;
98
99 void            ShutDown();
100 static void     ClearXStatValues(), NewParms(), PrintCounters();
101 static void     ResetCheckDescriptors(void), ResetCheckSignal(void);
102 static int      CheckSignal();
103 static int      FiveMinuteCheckLWP(), HostCheckLWP();
104 extern  int     GetKeysFromToken();
105 extern int RXAFS_ExecuteRequest();
106 extern int RXSTATS_ExecuteRequest();
107
108 int eventlog = 0, rxlog = 0;
109 FILE *debugFile;
110 FILE * console = NULL;
111
112 #ifdef AFS_NT40_ENV
113 #define AFS_QUIETFS_ENV 1
114 #define NT_OPEN_MAX    1024 /* This is an arbitrary no. we came up with for 
115                              * now. We hope this will be replaced by a more
116                              * intelligent estimate later. */
117 #endif
118
119 int     SystemId;               /* ViceID of "Administrators"*/
120 int     SystemAnyUser;          /* Viceid of "System:AnyUser" */
121 prlist  SystemAnyUserCPS;       /* CPS for "system:AnyUser */
122 int     AnonymousID = 0;        /* ViceId of "Anonymous"*/
123 prlist  AnonCPS;                /* CPS for "Anonymous"*/
124
125 struct afsconf_dir *confDir;    /* Configuration dir object */
126
127 int     restartMode = RESTART_ORDINARY;
128
129 int Testing = 0; /* for ListViceInodes */
130
131 /*
132  * Home for the performance statistics.
133  */
134 struct afs_PerfStats afs_perfstats;
135
136 extern  int     LogLevel;
137 extern  int     Statistics;
138
139 int     timeout = 30;
140 int     SawSpare;
141 int     SawPctSpare;
142 int     debuglevel = 0;
143 int     printBanner = 0;
144 int     rxJumbograms = 1; /* default is to send and receive jumbograms. */
145 afs_int32       implicitAdminRights = PRSFS_LOOKUP;     /* The ADMINISTER right is 
146                                                    already implied */
147 afs_int32       readonlyServer = 0;
148
149 int     stack = 24;
150 int     stackSize = 24000;
151 int     fiveminutes = 300;              /* 5 minutes.  Change this for debugging only */
152 int     CurrentConnections = 0;
153 int     hostaclRefresh = 7200;          /* refresh host clients' acls every 2 hrs */
154 #if defined(AFS_SGI_ENV)
155 int     SawLock;
156 #endif
157 time_t  StartTime;
158
159 int     rxpackets = 150;        /* 100 */
160 int     nSmallVns = 400;        /* 200 */
161 int     large = 400;            /* 200 */
162 int     volcache = 400;         /* 400 */
163 int     numberofcbs = 60000;    /* 60000 */
164 int     lwps = 9;               /* 6 */
165 int     buffs = 90;             /* 70 */
166 int     novbc = 0;              /* Enable Volume Break calls */
167 int     busy_threshold = 600;
168 int     udpBufSize = 0;         /* UDP buffer size for receive*/
169
170 struct timeval  tp;
171
172 /*
173  * FileServer's name and IP address, both network byte order and
174  * host byte order.
175  */
176 #define ADDRSPERSITE 16     /* Same global is in rx/rx_user.c */
177
178 char FS_HostName[128] = "localhost";
179 afs_uint32 FS_HostAddr_NBO;
180 afs_uint32 FS_HostAddr_HBO;
181 afs_uint32 FS_HostAddrs[ADDRSPERSITE], FS_HostAddr_cnt = 0, FS_registered=0;
182 /* All addresses in FS_HostAddrs are in NBO */
183 afsUUID FS_HostUUID;
184
185 static ParseArgs();
186 static FlagMsg();
187
188 /*
189  * Home for the performance statistics.
190  */
191
192 /* DEBUG HACK */
193 static CheckDescriptors()
194 {
195 #ifndef AFS_NT40_ENV
196     struct stat status;
197     register int tsize = getdtablesize();
198     register int i;
199     for (i = 0; i<tsize; i++) {
200         if (fstat(i, &status) != -1) {
201             printf("%d: dev %x, inode %u, length %u, type/mode %x\n",
202                    i, status.st_dev, status.st_ino,
203                    status.st_size, status.st_mode);
204         }
205     }
206     fflush(stdout);
207     ResetCheckDescriptors();
208 #endif
209 } /*CheckDescriptors*/
210
211
212 #ifdef AFS_PTHREAD_ENV
213 void CheckSignal_Signal(x)       {CheckSignal(0);}
214 void ShutDown_Signal(x)          {ShutDown(0);}
215 void CheckDescriptors_Signal(x)  {CheckDescriptors(0);}
216 #else /* AFS_PTHREAD_ENV */
217 void CheckSignal_Signal(x)       {IOMGR_SoftSig(CheckSignal, 0);}
218 void ShutDown_Signal(x)          {IOMGR_SoftSig(ShutDown, 0);}
219 void CheckDescriptors_Signal(x)  {IOMGR_SoftSig(CheckDescriptors, 0);}
220 #endif /* AFS_PTHREAD_ENV */
221
222 /* check whether caller is authorized to manage RX statistics */
223 int fs_rxstat_userok(call)
224     struct rx_call *call;
225 {
226     return afsconf_SuperUser(confDir, call, NULL);
227 }
228
229 static void ResetCheckSignal(void)
230 {
231 #ifdef  AFS_HPUX_ENV
232     signal(SIGPOLL, CheckSignal_Signal);
233 #else
234 #ifdef AFS_NT40_ENV
235     signal(SIGUSR2, CheckSignal_Signal);
236 #else
237     signal(SIGXCPU, CheckSignal_Signal);
238 #endif
239 #endif
240 }
241
242 static void ResetCheckDescriptors(void)
243 {
244 #ifndef AFS_NT40_ENV
245     signal(SIGTERM, CheckDescriptors_Signal);
246 #endif
247 }
248
249
250 /* proc called by rxkad module to get a key */
251 static int get_key(arock, akvno, akey)
252     char *akey;
253     char *arock;
254     register afs_int32 akvno;
255
256 {
257     /* find the key */
258     static struct afsconf_key tkey;
259     register afs_int32 code;
260
261     if (!confDir) {
262         ViceLog(0, ("conf dir not open\n"));
263         return 1;
264     }
265     code = afsconf_GetKey(confDir, akvno, tkey.key);
266     if (code)
267         return code;
268     memcpy(akey, tkey.key, sizeof(tkey.key));
269     return 0;
270
271 } /*get_key*/
272
273 #ifndef AFS_NT40_ENV
274 int viced_syscall(a3, a4, a5)
275 afs_uint32 a3, a4;
276 void * a5;
277 {
278   afs_uint32 rcode;
279   void (*old)();
280         
281 #ifndef AFS_LINUX20_ENV
282   old = (void (*)())signal(SIGSYS, SIG_IGN);    
283 #endif
284   rcode = syscall (AFS_SYSCALL, 28 /* AFSCALL_CALL */, a3, a4, a5);
285 #ifndef AFS_LINUX20_ENV
286   signal(SIGSYS, old);  
287 #endif
288
289   return rcode;
290 }
291 #endif
292
293 #if !defined(AFS_NT40_ENV)
294 #include "AFS_component_version_number.c"
295 #endif /* !AFS_NT40_ENV */
296
297 main(argc, argv)
298     int argc;
299     char * argv[];
300
301 {
302     int     i;
303     afs_int32    code;
304     FILE   *file;
305     char tbuffer[32];
306     struct rx_securityClass *sc[4];
307     struct rx_service *tservice;
308 #ifdef AFS_PTHREAD_ENV
309     pthread_t parentPid, serverPid;
310     pthread_attr_t tattr;
311     AFS_SIGSET_DECL;
312 #else /* AFS_PTHREAD_ENV */
313     PROCESS parentPid, serverPid;
314 #endif /* AFS_PTHREAD_ENV */
315     struct hostent *he;
316     int minVnodesRequired;      /* min size of vnode cache */
317 #ifndef AFS_NT40_ENV
318     struct rlimit rlim;         /* max number of open file descriptors */
319 #endif
320     int curLimit;
321
322 #ifdef  AFS_AIX32_ENV
323     struct sigaction nsa;
324     
325     sigemptyset(&nsa.sa_mask);
326     nsa.sa_handler = SIG_DFL;
327     nsa.sa_flags = SA_FULLDUMP;
328     sigaction(SIGABRT, &nsa, NULL);
329     sigaction(SIGSEGV, &nsa, NULL);
330 #endif
331
332     /* Initialize dirpaths */
333     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
334 #ifdef AFS_NT40_ENV
335         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0],0);
336 #endif
337         fprintf(stderr,"%s: Unable to obtain AFS server directory.\n", argv[0]);
338         exit(2);
339     }
340
341 #ifndef AFS_QUIETFS_ENV
342     console = fopen("/dev/console","w");
343 #endif
344
345     if(ParseArgs(argc,argv)) {
346         FlagMsg();
347         exit(-1);
348     }
349
350 #ifdef AFS_PTHREAD_ENV
351     assert(pthread_mutex_init(&fileproc_glock_mutex, NULL) == 0);
352 #endif /* AFS_PTHREAD_ENV */
353
354 #ifdef AFS_SGI_VNODE_GLUE
355     if (afs_init_kernel_config(-1) <0) {
356         printf("Can't determine NUMA configuration, not starting fileserver.\n");
357         exit(1);
358     }
359 #endif
360     confDir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
361     if (!confDir) {
362         fprintf(stderr, "Unable to open config directory %s\n",
363                 AFSDIR_SERVER_ETC_DIRPATH);
364         exit(-1);
365     }
366
367     NewParms(1);
368
369     /* Open FileLog on stdout, stderr, fd 1 and fd2 (for perror), sigh. */
370     OpenLog(AFSDIR_SERVER_FILELOG_FILEPATH);
371     SetupLogSignals(); 
372
373     if (SawSpare && SawPctSpare) {
374         ViceLog(0, ("Both -spare and -pctspare specified, exiting.\n"));
375         exit(-1);
376     }
377
378 #ifdef AFS_SGI_XFS_IOPS_ENV
379     ViceLog(0, ("XFS/EFS File server starting\n"));
380 #else
381     ViceLog(0, ("File server starting\n"));
382 #endif
383
384     /* install signal handlers for controlling the fileserver process */
385     ResetCheckSignal();  /* set CheckSignal_Signal() sig handler */
386     ResetCheckDescriptors();  /* set CheckDescriptors_Signal() sig handler */
387
388 #if defined(AFS_SGI_ENV)
389     /* give this guy a non-degrading priority so help busy servers */
390     schedctl(NDPRI, 0, NDPNORMMAX);
391     if (SawLock)
392         plock(PROCLOCK);
393 #else
394 #ifndef AFS_NT40_ENV
395     nice(-5); /* TODO: */
396 #endif
397 #endif
398     assert(DInit(buffs) == 0);
399  
400 #ifdef AFS_NT40_ENV
401     if (afs_winsockInit()<0) {
402         ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
403         ViceLog(0, ("File server failed to intialize winsock.\n"));
404         exit(1);
405     }
406 #endif
407     CheckAdminName();
408
409     /* if we support more than 16 threads, then we better have the ability 
410     ** to keep open a large number of files simultaneously 
411     */
412 #if     defined(AFS_AIX_ENV) && !defined(AFS_AIX42_ENV)
413     curLimit = OPEN_MAX;        /* for pre AIX 4.2 systems */
414 #elif defined(AFS_NT40_ENV)
415     curLimit = NT_OPEN_MAX;     /* open file descriptor limit on NT */
416 #else
417
418     curLimit = 0;               /* the number of open file descriptors */
419     code     = getrlimit(RLIMIT_NOFILE, &rlim);
420     if (code == 0) {
421         curLimit      = rlim.rlim_cur;
422         rlim.rlim_cur = rlim.rlim_max;
423         code = setrlimit(RLIMIT_NOFILE, &rlim);
424         if ( code == 0 ) 
425             curLimit  = rlim.rlim_max;
426     }
427     if ( code != 0 )
428         ViceLog(0, ("Failed to increase open file limit, using default\n"));
429
430 #endif /* defined(AFS_AIX_ENV) && !defined(AFS_AIX42_ENV) */
431
432     curLimit -= 32;             /* leave a slack of 32 file descriptors */
433     if ( lwps > curLimit ) {
434         if ( curLimit > 0)
435             lwps = curLimit; 
436         else if ( lwps > 16 )
437             lwps = 16;            /* default to a maximum of 16 threads */
438         ViceLog(0, ("The system supports a max of %d open files and we are starting %d threads\n", curLimit, lwps));
439     }
440
441
442 #ifndef AFS_PTHREAD_ENV
443     assert(LWP_InitializeProcessSupport(LWP_MAX_PRIORITY - 2, &parentPid) == LWP_SUCCESS);
444 #endif /* !AFS_PTHREAD_ENV */
445
446     /* Initialize volume support */
447     if (!novbc) {
448         V_BreakVolumeCallbacks = BreakVolumeCallBacks;
449     }
450
451     /* initialize libacl routines */
452     acl_Initialize(ACL_VERSION);
453
454     /* initialize RX support */
455 #ifndef AFS_NT40_ENV
456     rxi_syscallp = viced_syscall;
457 #endif
458     rx_extraPackets = rxpackets;
459     rx_extraQuota = 4;  /* for outgoing prserver calls from R threads */
460     rx_SetBusyThreshold(busy_threshold, VBUSY);
461     rx_SetCallAbortThreshold(10);
462     rx_SetConnAbortThreshold(10);
463     stackSize = lwps * 4000;
464     if (stackSize < 32000)
465         stackSize = 32000;
466     else if (stackSize > 44000)
467         stackSize = 44000;
468 #if    defined(AFS_HPUX_ENV) || defined(AFS_SUN_ENV) || defined(AFS_SGI51_ENV)
469     rx_SetStackSize(1, stackSize);      
470 #endif
471     if ( udpBufSize )
472         rx_SetUdpBufSize(udpBufSize);/* set the UDP buffer size for receive */
473     if (rx_Init((int)htons(7000))<0) {
474         ViceLog(0, ("Cannot initialize RX\n"));
475         exit(1);
476     }
477     if (!rxJumbograms) {
478         /* Don't send and don't allow 3.4 clients to send jumbograms. */
479         rx_SetNoJumbo();
480     }
481     rx_GetIFInfo();
482     rx_SetRxDeadTime(30);
483     sc[0] = rxnull_NewServerSecurityObject();
484     sc[1] = 0; /* rxvab_NewServerSecurityObject(key1, 0) */
485     sc[2] = rxkad_NewServerSecurityObject (rxkad_clear, NULL,
486                                            get_key, NULL);
487     sc[3] = rxkad_NewServerSecurityObject (rxkad_crypt, NULL,
488                                            get_key, NULL);
489     tservice = rx_NewService
490         (/* port */ 0, /* service id */ 1, /*service name */ "AFS",
491          /* security classes */ sc, /* numb sec classes */ 4,
492          RXAFS_ExecuteRequest);
493     if (!tservice) {
494         ViceLog(0, ("Failed to initialize RX, probably two servers running.\n"));
495         exit(-1);
496     }
497     rx_SetDestroyConnProc(tservice, h_FreeConnection);
498     rx_SetMinProcs(tservice, 3);
499     rx_SetMaxProcs(tservice, lwps);
500     rx_SetCheckReach(tservice, 1);
501
502     tservice = rx_NewService(0,  RX_STATS_SERVICE_ID, "rpcstats", sc, 4, RXSTATS_ExecuteRequest);
503     if (!tservice) {
504         ViceLog(0, ("Failed to initialize rpc stat service.\n"));
505         exit(-1);
506     }
507     rx_SetMinProcs(tservice, 2);
508     rx_SetMaxProcs(tservice, 4);
509
510     /*
511      * Enable RX hot threads, which allows the listener thread to trade
512      * places with an idle thread and moves the context switch from listener
513      * to worker out of the critical path.
514      */
515     rx_EnableHotThread();
516
517     /* Some rx debugging */
518     if (rxlog || eventlog) {
519         debugFile = fopen("rx_dbg", "w");
520         if (rxlog) rx_debugFile = debugFile;
521         if (eventlog) rxevent_debugFile = debugFile;
522     }
523
524     h_InitHostPackage();  /* set up local cellname and realmname */
525     InitCallBack(numberofcbs);
526     ClearXStatValues();
527
528     code = InitVL();
529     if (code) {
530         ViceLog(0,("Fatal error in library initialization, exiting!!\n"));
531         exit(1);
532     }
533
534     code = InitPR();
535     if (code) {
536         ViceLog(0,("Fatal error in protection initialization, exiting!!\n"));
537         exit(1);
538     }
539
540     /* allow super users to manage RX statistics */
541     rx_SetRxStatUserOk(fs_rxstat_userok);
542
543     rx_StartServer(0);  /* now start handling requests */
544
545     /* we ensure that there is enough space in the vnode buffer to satisfy
546     ** requests from all concurrent threads. 
547     ** the maximum number of vnodes used by a single thread at any one time
548     ** is three ( "link" uses three vnodes simultaneously, one vLarge and
549     ** two vSmall for linking files and two vLarge and one vSmall for linking
550     ** files  ) : dhruba 
551     */
552     minVnodesRequired = 2 * lwps + 1;     
553     if ( minVnodesRequired > nSmallVns ) {
554         nSmallVns = minVnodesRequired;
555         ViceLog(0, ("Overriding -s command line parameter with %d\n",
556                     nSmallVns));
557     }
558     if ( minVnodesRequired > large ) {
559         large = minVnodesRequired;
560         ViceLog(0, ("Overriding -l command line parameter with %d\n", large));
561     }
562
563     /* We now do this after getting the listener up and running, so that client
564        connections don't timeout (maybe) if a file server is restarted, since it
565        will be available "real soon now".  Worry about whether we can satisfy the 
566        calls in the volume package itself.
567      */
568     if (VInitVolumePackage(fileServer,large,nSmallVns,0, volcache)) {
569         ViceLog(0, ("Shutting down: errors encountered initializing volume package\n"));
570         VShutdown();
571         exit(1);
572     }
573
574     /*
575      * We are done calling fopen/fdopen. It is safe to use a large
576      * of the file descriptor cache.
577      */
578     ih_UseLargeCache();
579
580 #ifdef AFS_PTHREAD_ENV
581     assert(pthread_attr_init(&tattr) == 0);
582     assert(pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) == 0);
583     /* Block signals in the threads */
584     AFS_SIGSET_CLEAR();
585     assert(pthread_create(&serverPid, &tattr, (void *)FiveMinuteCheckLWP, &fiveminutes) == 0);
586     assert(pthread_create(&serverPid, &tattr, (void *)HostCheckLWP, &fiveminutes) == 0);
587     AFS_SIGSET_RESTORE();
588 #else /* AFS_PTHREAD_ENV */
589     assert(LWP_CreateProcess(FiveMinuteCheckLWP, stack*1024, LWP_MAX_PRIORITY - 2,
590                              (void *) &fiveminutes, "FiveMinuteChecks", &serverPid) == LWP_SUCCESS);
591             
592     assert(LWP_CreateProcess(HostCheckLWP, stack*1024, LWP_MAX_PRIORITY - 2,
593             (void *) &fiveminutes, "HostCheck", &serverPid) == LWP_SUCCESS);
594 #endif /* AFS_PTHREAD_ENV */
595
596     TM_GetTimeOfDay(&tp, 0);
597
598 #ifndef AFS_QUIETFS_ENV
599     if (console != NULL) {
600         fprintf(console, "File server has started at %s\r",
601                 afs_ctime(&tp.tv_sec, tbuffer, sizeof(tbuffer)));
602     }
603 #endif
604
605     /*
606      * Figure out the FileServer's name and primary address.
607      */
608     ViceLog(0, ("Getting FileServer name...\n"));
609     code = gethostname(FS_HostName, 64);
610     if (code) {
611         ViceLog(0, ("gethostname() failed\n"));
612     }
613     ViceLog(0, ("FileServer host name is '%s'\n", FS_HostName));
614
615     ViceLog(0, ("Getting FileServer address...\n"));
616     he = gethostbyname(FS_HostName);
617     if (!he) {
618         ViceLog(0, ("Can't find address for FileServer '%s'\n", FS_HostName));
619     }
620     else {
621         char hoststr[16];
622         memcpy(&FS_HostAddr_NBO, he->h_addr, 4);
623         afs_inet_ntoa_r(FS_HostAddr_NBO, hoststr);
624         FS_HostAddr_HBO = ntohl(FS_HostAddr_NBO);
625         ViceLog(0,("FileServer %s has address %s (0x%x or 0x%x in host byte order)\n",
626                    FS_HostName, hoststr, FS_HostAddr_NBO, FS_HostAddr_HBO));
627     }
628
629     /* Install handler to catch the shutdown signal */
630     signal(SIGQUIT, ShutDown_Signal); /* bosserver assumes SIGQUIT shutdown */
631
632     ViceLog(0,("File Server started %s",
633                afs_ctime(&tp.tv_sec, tbuffer, sizeof(tbuffer))));
634 #if FS_STATS_DETAILED
635     afs_FullPerfStats.det.epoch.tv_sec = StartTime = tp.tv_sec;
636 #endif
637 #ifdef AFS_PTHREAD_ENV
638     while(1) {
639         sleep(1000); /* long time */
640     }
641 #else /* AFS_PTHREAD_ENV */
642     assert(LWP_WaitProcess(&parentPid) == LWP_SUCCESS);
643 #endif /* AFS_PTHREAD_ENV */
644 }
645
646
647 /* This LWP does things roughly every 5 minutes */
648 static FiveMinuteCheckLWP()
649
650 {
651     static int msg  = 0;
652     char tbuffer[32];
653
654     ViceLog(1, ("Starting five minute check process\n"));
655     while (1) {
656 #ifdef AFS_PTHREAD_ENV
657         sleep(fiveminutes);
658 #else /* AFS_PTHREAD_ENV */
659         IOMGR_Sleep(fiveminutes);
660 #endif /* AFS_PTHREAD_ENV */
661
662         /* close the log so it can be removed */
663         ReOpenLog(AFSDIR_SERVER_FILELOG_FILEPATH); /* don't trunc, just append */
664         ViceLog(2, ("Cleaning up timed out callbacks\n"));
665         if(CleanupTimedOutCallBacks())
666             ViceLog(5,("Timed out callbacks deleted\n"));
667         ViceLog(2, ("Set disk usage statistics\n"));
668         VSetDiskUsage();
669         if (FS_registered == 1) Do_VLRegisterRPC();
670         if(printBanner && (++msg&1)) { /* Every 10 minutes */
671             time_t now = FT_ApproxTime();
672             if (console != NULL) {
673 #ifndef AFS_QUIETFS_ENV
674                 fprintf(console,"File server is running at %s\r",
675                         afs_ctime(&now, tbuffer, sizeof(tbuffer)));
676 #endif /* AFS_QUIETFS_ENV */
677                 ViceLog(2, ("File server is running at %s\n",
678                         afs_ctime(&now, tbuffer, sizeof(tbuffer))));
679             }
680         }
681     }
682 } /*FiveMinuteCheckLWP*/
683
684
685 /* This LWP does host checks every 5 minutes:  it should not be used for
686  * other 5 minute activities because it may be delayed by timeouts when
687  * it probes the workstations
688  */
689 static HostCheckLWP()
690
691 {
692     ViceLog(1, ("Starting Host check process\n"));
693     while(1) {
694 #ifdef AFS_PTHREAD_ENV
695         sleep(fiveminutes);
696 #else /* AFS_PTHREAD_ENV */
697         IOMGR_Sleep(fiveminutes);
698 #endif /* AFS_PTHREAD_ENV */
699         ViceLog(2, ("Checking for dead venii & clients\n"));
700         h_CheckHosts();
701     }
702 } /*HostCheckLWP*/
703
704
705 #define MAXADMINNAME 64
706 char adminName[MAXADMINNAME];
707
708 CheckAdminName()
709
710 {
711     int             fd = 0;
712     struct stat     status;
713     
714     if ((stat("/AdminName", &status)) ||        /* if file does not exist */
715         (status.st_size <= 0) ||                /* or it is too short */
716         (status.st_size >= (MAXADMINNAME)) ||   /* or it is too long */
717         !(fd = open("/AdminName", O_RDONLY, 0))) {      /* or the open fails */
718         strcpy(adminName, "System:Administrators");     /* use the default name */
719     }
720     else {
721         read(fd, adminName, status.st_size);    /* use name from the file */
722     }
723     if (fd)
724         close(fd);      /* close fd if it was opened */
725
726 } /*CheckAdminName*/
727
728
729 /*------------------------------------------------------------------------
730  * PRIVATE ClearXStatValues
731  *
732  * Description:
733  *      Initialize all of the values collected via the xstat
734  *      interface.
735  *
736  * Arguments:
737  *      None.
738  *
739  * Returns:
740  *      Nothing.
741  *
742  * Environment:
743  *      Must be called during File Server initialization.
744  *
745  * Side Effects:
746  *      As advertised.
747  *------------------------------------------------------------------------*/
748
749 static void ClearXStatValues()
750
751 { /*ClearXStatValues*/
752
753     struct fs_stats_opTimingData *opTimeP;      /*Ptr to timing struct*/
754     struct fs_stats_xferData *opXferP;          /*Ptr to xfer struct*/
755     int i;                                      /*Loop counter*/
756
757     /*
758      * Zero all xstat-related structures.
759      */
760     memset((char *)(&afs_perfstats), 0, sizeof(struct afs_PerfStats));
761 #if FS_STATS_DETAILED
762     memset((char *)(&afs_FullPerfStats), 0, sizeof(struct fs_stats_FullPerfStats));
763
764     /*
765      * That's not enough.  We have to set reasonable minima for
766      * time and xfer values in the detailed stats.
767      */
768     opTimeP = &(afs_FullPerfStats.det.rpcOpTimes[0]);
769     for (i = 0; i < FS_STATS_NUM_RPC_OPS; i++, opTimeP++)
770         opTimeP->minTime.tv_sec = 999999;
771
772     opXferP = &(afs_FullPerfStats.det.xferOpTimes[0]);
773     for (i = 0; i < FS_STATS_NUM_XFER_OPS; i++, opXferP++) {
774         opXferP->minTime.tv_sec = 999999;
775         opXferP->minBytes = 999999999;
776     }
777
778     /*
779      * There's more.  We have to set our unique system identifier, as
780      * declared in param.h.  If such a thing is not defined, we bitch
781      * and declare ourselves to be an unknown system type.
782      */
783 #ifdef SYS_NAME_ID
784     afs_perfstats.sysname_ID = SYS_NAME_ID;
785 #else
786 #ifndef AFS_NT40_ENV
787     ViceLog(0, ("Sys name ID constant not defined in param.h!!\n"));
788     ViceLog(0, ("[Choosing ``undefined'' sys name ID.\n"));
789 #endif
790     afs_perfstats.sysname_ID = SYS_NAME_ID_UNDEFINED;
791 #endif /* SYS_NAME_ID */
792 #endif
793
794 } /*ClearXStatValues*/
795
796
797 static void PrintCounters()
798
799 {
800     int dirbuff, dircall, dirio;
801     struct timeval  tpl;
802     int workstations, activeworkstations, delworkstations;
803     int processSize = 0;
804     char tbuffer[32];
805
806     TM_GetTimeOfDay(&tpl, 0);
807     Statistics = 1;
808     ViceLog(0, ("Vice was last started at %s\n",
809                 afs_ctime(&StartTime, tbuffer, sizeof(tbuffer))));
810
811     VPrintCacheStats();
812     VPrintDiskStats();
813     DStat(&dirbuff, &dircall, &dirio);
814     ViceLog(0,("With %d directory buffers; %d reads resulted in %d read I/Os\n",
815             dirbuff, dircall, dirio));
816     rx_PrintStats(stderr);
817     h_PrintStats();
818     PrintCallBackStats();
819 #ifdef AFS_NT40_ENV
820     processSize = -1; /* TODO: */
821 #else
822     processSize = (int)((long) sbrk(0) >> 10);
823 #endif
824     ViceLog(0,("There are %d connections, process size %d\n",  CurrentConnections, processSize));
825     h_GetWorkStats(&workstations, &activeworkstations, &delworkstations,
826          tpl.tv_sec-15*60);
827     ViceLog(0,
828             ("There are %d workstations, %d are active (req in < 15 mins), %d marked \"down\"\n",
829             workstations, activeworkstations, delworkstations));
830     Statistics = 0;
831
832 } /*PrintCounters*/
833
834
835
836 static CheckSignal()
837
838 {
839     if (FS_registered > 0)  {
840         /*
841          * We have proper ip addresses; tell the vlserver what we got; the following
842          * routine will do the proper reporting for us
843          */
844         Do_VLRegisterRPC();
845     }
846     h_DumpHosts();
847     h_PrintClients();
848     DumpCallBackState();
849     PrintCounters();
850     ResetCheckSignal();
851
852 } /*CheckSignal*/
853
854 void ShutDownAndCore(dopanic)
855 int dopanic;
856 {
857     time_t now = time(0);
858     char *tstr;
859     char tbuffer[32];
860
861     ViceLog(0, ("Shutting down file server at %s",
862                 afs_ctime(&now, tbuffer, sizeof(tbuffer))));
863     if (dopanic) 
864         ViceLog(0, ("ABNORMAL SHUTDOWN, see core file.\n"));
865 #ifndef AFS_QUIETFS_ENV
866     if (console != NULL) {
867         fprintf(console,"File server restart/shutdown received at %s\r",
868                 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
869     }
870 #endif
871     DFlush();
872     PrintCounters();
873
874     /* do not allows new reqests to be served from now on, all new requests
875        are returned with an error code of RX_RESTARTING ( transient failure ) */
876     rx_SetRxTranquil();                 /* dhruba */
877     VShutdown();
878
879     if (debugFile) {
880         rx_PrintStats(debugFile);
881         fflush(debugFile);
882     }
883     if (console != NULL) {
884         now = time(0);
885         if (dopanic) {
886 #ifndef AFS_QUIETFS_ENV
887             fprintf(console, "File server has terminated abnormally at %s\r",
888                     afs_ctime(&now, tbuffer, sizeof(tbuffer)));
889 #endif
890             ViceLog(0, ("File server has terminated abnormally at %s\n",
891                 afs_ctime(&now, tbuffer, sizeof(tbuffer))));
892         } else {
893 #ifndef AFS_QUIETFS_ENV
894             fprintf(console, "File server has terminated normally at %s\r",
895                     afs_ctime(&now, tbuffer, sizeof(tbuffer)));
896 #endif
897             ViceLog(0, ("File server has terminated normally at %s\n",
898                 afs_ctime(&now, tbuffer, sizeof(tbuffer))));
899         }
900     }
901
902     exit(0);
903
904 } /*ShutDown*/
905
906 void ShutDown() /* backward compatibility */
907 {
908   ShutDownAndCore(DONTPANIC);
909 }
910
911
912 static FlagMsg()
913
914 {
915     char buffer[1024];
916
917         /* default supports help flag */
918
919     strcpy(buffer, "Usage: fileserver ");
920     strcat(buffer, "[-d <debug level>] ");
921     strcat(buffer, "[-p <number of processes>] ");
922     strcat(buffer, "[-spare <number of spare blocks>] ");
923     strcat(buffer, "[-pctspare <percentage spare>] ");
924     strcat(buffer, "[-b <buffers>] ");
925     strcat(buffer, "[-l <large vnodes>] ");
926     strcat(buffer, "[-s <small vnodes>] ");
927     strcat(buffer, "[-vc <volume cachesize>] ");
928     strcat(buffer, "[-w <call back wait interval>] ");
929     strcat(buffer, "[-cb <number of call backs>] ");
930     strcat(buffer, "[-banner (print banner every 10 minutes)] ");
931     strcat(buffer, "[-novbc (whole volume cbs disabled)] ");
932     strcat(buffer, "[-implicit <admin mode bits: rlidwka>] ");
933     strcat(buffer, "[-readonly (read-only file server)] ");
934     strcat(buffer, "[-hr <number of hours between refreshing the host cps>] ");
935     strcat(buffer, "[-busyat <redirect clients when queue > n>] ");
936     strcat(buffer, "[-rxpck <number of rx extra packets>] ");
937     strcat(buffer, "[-rxdbg (enable rx debugging)] ");
938     strcat(buffer, "[-rxdbge (enable rxevent debugging)] ");
939 #ifdef  AFS_AIX32_ENV
940     strcat(buffer, "[-m <min percentage spare in partition>] ");
941 #endif
942 #if defined(AFS_SGI_ENV)
943     strcat(buffer, "[-lock (keep fileserver from swapping)] ");
944 #endif
945     strcat(buffer, "[-L (large server conf)] ");
946     strcat(buffer, "[-S (small server conf)] ");
947     strcat(buffer, "[-k <stack size>] ");
948     strcat(buffer, "[-realm <Kerberos realm name>] ");
949     strcat(buffer, "[-udpsize <size of socket buffer in bytes>] ");
950 /*   strcat(buffer, "[-enable_peer_stats] "); */
951 /*   strcat(buffer, "[-enable_process_stats] "); */
952     strcat(buffer, "[-help]\n");
953 /*
954     ViceLog(0, ("%s", buffer));
955 */
956
957         printf("%s",buffer);
958         fflush(stdout);
959
960 } /*FlagMsg*/
961
962
963 static afs_int32 ParseRights(arights)
964     char *arights;
965 {
966     afs_int32 mode = 0;
967     int i, len;
968     char tc;
969
970     if (!arights || !strcmp(arights, "")) {
971         printf("Missing list of mode bits on -implicit option\n");
972         return -1;
973     }
974     if (!strcmp(arights, "none"))
975       mode = 0;
976     else if (!strcmp(arights, "read")) 
977       mode = PRSFS_READ | PRSFS_LOOKUP;
978     else if (!strcmp(arights, "write"))
979       mode = PRSFS_READ | PRSFS_LOOKUP | PRSFS_INSERT | 
980              PRSFS_DELETE | PRSFS_WRITE | PRSFS_LOCK;
981     else if (!strcmp(arights, "all"))
982       mode = PRSFS_READ | PRSFS_LOOKUP | PRSFS_INSERT | 
983              PRSFS_DELETE | PRSFS_WRITE | PRSFS_LOCK | PRSFS_ADMINISTER;
984     else {
985         len = strlen(arights);
986         for(i=0;i<len;i++) {
987             tc = *arights++;
988             if (tc == 'r') mode |= PRSFS_READ;
989             else if (tc == 'l') mode |= PRSFS_LOOKUP;
990             else if (tc == 'i') mode |= PRSFS_INSERT;
991             else if (tc == 'd') mode |= PRSFS_DELETE;
992             else if (tc == 'w') mode |= PRSFS_WRITE;
993             else if (tc == 'k') mode |= PRSFS_LOCK;
994             else if (tc == 'a') mode |= PRSFS_ADMINISTER;
995             else if (tc == 'A') mode |= PRSFS_USR0;
996             else if (tc == 'B') mode |= PRSFS_USR1;
997             else if (tc == 'C') mode |= PRSFS_USR2;
998             else if (tc == 'D') mode |= PRSFS_USR3;
999             else if (tc == 'E') mode |= PRSFS_USR4;
1000             else if (tc == 'F') mode |= PRSFS_USR5;
1001             else if (tc == 'G') mode |= PRSFS_USR6;
1002             else if (tc == 'H') mode |= PRSFS_USR7;
1003             else {
1004                 printf("Illegal -implicit rights character '%c'.\n", tc);
1005                 return -1;
1006             }
1007         }
1008     }
1009     return mode;
1010 }
1011
1012 /*
1013  * Limit MAX_FILESERVER_THREAD by the system limit on the number of
1014  * pthreads (sysconf(_SC_THREAD_THREADS_MAX)), if applicable and
1015  * available.
1016  *
1017  * AIX:         sysconf() limit is real
1018  * HP-UX:       sysconf() limit is real
1019  * IRIX:        sysconf() limit is apparently NOT real -- too small
1020  * DUX:         sysconf() limit is apparently NOT real -- too big
1021  * Linux:       sysconf() limit is apparently NOT real -- too big
1022  * Solaris:     no sysconf() limit
1023  */
1024 static int
1025 max_fileserver_thread(void)
1026 {
1027 #if defined(AFS_PTHREAD_ENV)
1028 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV)
1029         long ans;
1030
1031         ans = sysconf(_SC_THREAD_THREADS_MAX);
1032         if (0 < ans && ans < MAX_FILESERVER_THREAD)
1033                 return (int) ans;
1034 #endif
1035 #endif /* defined(AFS_PTHREAD_ENV) */
1036         return MAX_FILESERVER_THREAD;
1037 }
1038
1039 static ParseArgs(argc, argv)
1040     int argc;
1041     char *argv[];
1042
1043 {
1044     int SawL=0, SawS=0, SawVC=0;
1045     int Sawrxpck = 0, Sawsmall=0, Sawlarge=0, Sawcbs=0, Sawlwps=0, Sawbufs=0;
1046     int Sawbusy=0;
1047     int i;
1048     int bufSize = 0;      /* temp variable to read in udp socket buf size*/
1049
1050     for (i = 1; i < argc; i++) {
1051         if (!strcmp(argv[i], "-d")) {
1052             debuglevel = atoi(argv[++i]);
1053             LogLevel = debuglevel;
1054         }
1055         else
1056             if (!strcmp(argv[i], "-banner")) {
1057                 printBanner = 1;
1058         } else
1059             if (!strcmp(argv[i], "-implicit")) {
1060                 implicitAdminRights = ParseRights(argv[++i]);
1061                 if (implicitAdminRights < 0) return implicitAdminRights;
1062         } else
1063             if (!strcmp(argv[i], "-readonly")) {
1064                 readonlyServer = 1;
1065         } else
1066             if (!strcmp(argv[i], "-L")) {
1067                 SawL = 1;
1068         } else
1069             if (!strcmp(argv[i], "-S")) {
1070                 SawS = 1;
1071         }
1072         else
1073             if (!strcmp(argv[i], "-p")) {
1074                 int lwps_max = max_fileserver_thread() - FILESERVER_HELPER_THREADS;
1075                 Sawlwps = 1;
1076                 lwps = atoi(argv[++i]);
1077                 if (lwps > lwps_max)
1078                     lwps = lwps_max;
1079                 else if (lwps < 6)
1080                     lwps = 6;
1081             }
1082         else
1083             if (!strcmp(argv[i], "-b")) {
1084                 Sawbufs = 1;
1085                 buffs = atoi(argv[++i]);
1086             }
1087         else
1088             if (!strcmp(argv[i], "-l")) {
1089                 Sawlarge = 1;
1090                 large = atoi(argv[++i]);
1091             }
1092         else
1093             if (!strcmp(argv[i], "-vc")) {
1094                 SawVC = 1;
1095                 volcache = atoi(argv[++i]);
1096             }
1097         else
1098             if (!strcmp(argv[i], "-novbc")) {
1099                 novbc = 1;
1100             }
1101         else
1102             if (!strcmp(argv[i], "-rxpck")) {
1103                 Sawrxpck = 1;
1104                 rxpackets = atoi(argv[++i]);
1105             }
1106         else
1107             if (!strcmp(argv[i], "-s")) {
1108                 Sawsmall = 1;
1109                 nSmallVns = atoi(argv[++i]);
1110             }
1111         else    
1112             if (!strcmp(argv[i], "-k"))
1113                 stack = atoi(argv[++i]);
1114 #if defined(AFS_SGI_ENV)
1115         else
1116             if (!strcmp(argv[i], "-lock")) {
1117                 SawLock = 1;
1118             }
1119 #endif
1120         else
1121             if (!strcmp(argv[i], "-spare")) {
1122                 BlocksSpare = atoi(argv[++i]);
1123                 SawSpare = 1;
1124             }
1125         else
1126             if (!strcmp(argv[i], "-pctspare")) {
1127                 PctSpare = atoi(argv[++i]);
1128                 BlocksSpare = 0;                /* has non-zero default */
1129                 SawPctSpare = 1;
1130             }
1131         else
1132             if (!strcmp(argv[i], "-w"))
1133                 fiveminutes = atoi(argv[++i]);
1134         else
1135             if (!strcmp(argv[i], "-hr")) {
1136                 int hr = atoi(argv[++i]);
1137                 if ((hr < 1) || (hr > 36)) {
1138                     printf("host acl refresh interval of %d hours is invalid; hours must be between 1 and 36\n\n",
1139                            hr);
1140                     return -1;
1141                 }                   
1142                 hostaclRefresh = hr*60*60;
1143         } else
1144             if (!strcmp(argv[i], "-rxdbg"))
1145                 rxlog = 1;
1146         else 
1147             if (!strcmp(argv[i], "-rxdbge"))
1148                 eventlog = 1;
1149         else
1150             if (!strcmp(argv[i], "-cb")) {
1151                 Sawcbs = 1;
1152                 numberofcbs = atoi(argv[++i]);
1153                 if ((numberofcbs < 10000) || (numberofcbs > 4294967295)) {
1154                     printf("number of cbs %d invalid; must be between 10000 and 4294967295\n",
1155                            numberofcbs);
1156                     return -1;
1157                 }
1158             }
1159             else
1160               if (!strcmp(argv[i], "-busyat")) {
1161                 Sawbusy = 1;
1162                 busy_threshold = atoi(argv[++i]);
1163                 if (busy_threshold < 10) {
1164                     printf("Busy threshold %d is too low, will compute default.\n",
1165                            busy_threshold);
1166                     Sawbusy = 0;
1167                 }
1168             }
1169 #ifdef  AFS_AIX32_ENV
1170         else
1171             if (!strcmp(argv[i], "-m")) {
1172                 extern int aixlow_water;
1173                  aixlow_water = atoi(argv[++i]);
1174                 if ((aixlow_water < 0) || (aixlow_water > 30)) {
1175                     printf("space reserved %d% invalid; must be between 0-30%\n", aixlow_water);
1176                     return -1;
1177                 }
1178             }
1179 #endif
1180         else
1181             if (!strcmp(argv[i], "-nojumbo")) {
1182                 rxJumbograms = 0;
1183             }
1184         else
1185             if (!strcmp(argv[i], "-realm")) {
1186                 extern char local_realm[AFS_REALM_SZ];
1187                 if (strlen(argv[++i]) >= AFS_REALM_SZ) {
1188                     printf("-realm argument must contain fewer than %d characters.\n",AFS_REALM_SZ);
1189                     return -1;
1190                 }
1191                 strncpy (local_realm, argv[i], AFS_REALM_SZ);
1192             }
1193         else
1194             if ( !strcmp(argv[i], "-udpsize")) {
1195                 if ( (i+1) >= argc ) {
1196                     printf("You have to specify -udpsize <integer value>\n");
1197                     return -1;
1198                 }
1199                 bufSize = atoi(argv[++i]);
1200                 if ( bufSize < rx_GetMinUdpBufSize() )
1201                     printf("Warning:udpsize %d is less than minimum %d; ignoring\n",
1202                                 bufSize, rx_GetMinUdpBufSize() );
1203                 else
1204                     udpBufSize = bufSize;
1205             }
1206         else
1207             if (!strcmp(argv[i], "-enable_peer_stats")) {
1208                 rx_enablePeerRPCStats();
1209             }
1210         else
1211             if (!strcmp(argv[i], "-enable_process_stats")) {
1212                 rx_enableProcessRPCStats();
1213             }
1214 #ifndef AFS_NT40_ENV
1215         else 
1216             if (strcmp(argv[i], "-syslog")==0) {
1217                 /* set syslog logging flag */
1218                 serverLogSyslog = 1;
1219             } 
1220         else 
1221             if (strncmp(argv[i], "-syslog=", 8)==0) {
1222                 serverLogSyslog = 1;
1223                 serverLogSyslogFacility = atoi(argv[i]+8);
1224             }
1225 #endif
1226         else {
1227             return(-1);
1228         }
1229     }
1230     if (SawS && SawL) {
1231         printf("Only one of -L, or -S must be specified\n");
1232         return -1;
1233     }
1234     if (SawS) {
1235         if (!Sawrxpck) rxpackets = 100;
1236         if (!Sawsmall) nSmallVns = 200;
1237         if (!Sawlarge) large = 200;
1238         if (!Sawcbs) numberofcbs = 20000;
1239         if (!Sawlwps) lwps = 6;
1240         if (!Sawbufs) buffs = 70;
1241         if (!SawVC) volcache = 200;
1242     }
1243     if (SawL) {
1244         if (!Sawrxpck) rxpackets = 200;
1245         if (!Sawsmall) nSmallVns = 600;
1246         if (!Sawlarge) large = 600;
1247         if (!Sawcbs) numberofcbs = 64000;
1248         if (!Sawlwps) lwps = 12;
1249         if (!Sawbufs) buffs = 120;
1250         if (!SawVC) volcache = 600;
1251     }
1252     if (!Sawbusy) 
1253         busy_threshold = 3*rxpackets/2;
1254
1255     return(0);
1256
1257 } /*ParseArgs*/
1258
1259
1260 #define MAXPARMS 15
1261
1262 static void NewParms(initializing)
1263     int initializing;
1264
1265 {
1266     static struct stat sbuf;
1267     register int i, fd;
1268     char *parms;
1269     char *argv[MAXPARMS];
1270     register int argc;
1271
1272     if (!(stat("/vice/file/parms",&sbuf))) {
1273         parms = (char *)malloc(sbuf.st_size);
1274         if(!parms) return;
1275         fd = open("parms", O_RDONLY, 0666);
1276         if(fd <= 0) {
1277             ViceLog(0, ("Open for parms failed with errno = %d\n", errno));
1278             return;
1279         }
1280
1281         i = read(fd, parms, sbuf.st_size);
1282         close(fd);
1283         if(i != sbuf.st_size) {
1284             if (i < 0 ) {
1285                 ViceLog(0, ("Read on parms failed with errno = %d\n", errno));
1286             } else {
1287                 ViceLog(0,
1288                         ("Read on parms failed; expected %d bytes but read %d\n",
1289                         sbuf.st_size, i));
1290             }
1291             free(parms);
1292             return;
1293         }
1294
1295         for (i = 0;i < MAXPARMS; argv[i++] = 0 );
1296         
1297         for (argc = i = 0; i < sbuf.st_size; i++) {
1298             if ((*(parms + i) != ' ') && (*(parms + i) != '\n')){
1299                 if(argv[argc] == 0) argv[argc] = (parms+i);
1300             }
1301             else {
1302                 *(parms + i) = '\0';
1303                 if(argv[argc] != 0) {
1304                     if(++argc == MAXPARMS) break;
1305                 }
1306                 while ((*(parms + i + 1) == ' ') || (*(parms + i + 1) == '\n'))
1307                     i++;
1308             }
1309         }
1310         if(ParseArgs(argc, argv) == 0) {
1311             ViceLog(0, ("Change parameters to:"));
1312         } else {
1313             ViceLog(0, ("Invalid parameter in:"));
1314         }
1315         for(i = 0; i < argc; i++) {
1316             ViceLog(0, (" %s", argv[i]));
1317         }
1318         ViceLog(0,("\n"));
1319         free(parms);
1320     }
1321     else
1322         if(!initializing)
1323             ViceLog(0, ("Received request to change parms but no parms file exists\n"));
1324
1325 } /*NewParms*/
1326
1327
1328 /* Miscellaneous routines */
1329 Die (msg)
1330     char *msg;
1331
1332 {
1333     ViceLog (0,("%s\n", msg));
1334     assert(0);
1335
1336 } /*Die*/
1337
1338
1339 InitPR()
1340
1341 {
1342     register code;
1343
1344     /*
1345      * If this fails, it's because something major is wrong, and is not
1346      * likely to be time dependent.
1347      */
1348     code = pr_Initialize(2, AFSDIR_SERVER_ETC_DIRPATH, 0);
1349     if (code != 0) {
1350         ViceLog(0, ("Couldn't initialize protection library; code=%d.\n", code));
1351         return code; 
1352     }
1353     SystemId = SYSADMINID;
1354     SystemAnyUser = ANYUSERID;
1355     SystemAnyUserCPS.prlist_len = 0;
1356     SystemAnyUserCPS.prlist_val = NULL;
1357     AnonCPS.prlist_len = 0;
1358     AnonCPS.prlist_val = NULL;
1359     while (1) {
1360         code = pr_GetCPS(SystemAnyUser, &SystemAnyUserCPS);
1361         if (code != 0) {
1362             ViceLog(0,
1363                     ("Couldn't get CPS for AnyUser, will try again in 30 seconds; code=%d.\n",
1364                     code));
1365             goto sleep;
1366         }
1367         code = pr_GetCPS(ANONYMOUSID,&AnonCPS);
1368         if (code != 0) {
1369             ViceLog(0,("Couldn't get Anonymous CPS, exiting; code=%d.\n", code));
1370             return -1;
1371         }
1372         AnonymousID = ANONYMOUSID;
1373         return 0;
1374 sleep:
1375 #ifdef AFS_PTHREAD_ENV
1376         sleep(30);
1377 #else /* AFS_PTHREAD_ENV */
1378         IOMGR_Sleep(30);
1379 #endif /* AFS_PTHREAD_ENV */
1380     }
1381 } /*InitPR*/
1382
1383 struct rx_connection *serverconns[MAXSERVERS];
1384 struct ubik_client *cstruct;
1385 afs_int32 vl_Initialize(confDir)
1386 char *confDir;
1387 {   afs_int32 code, scIndex = 0, i;
1388     struct afsconf_dir *tdir;
1389     struct rx_securityClass *sc;
1390     struct afsconf_cell info;
1391
1392     tdir = afsconf_Open(confDir);
1393     if (!tdir) {
1394         ViceLog(0, ("Could not open configuration directory (%s).\n", confDir));
1395         exit(1);
1396     }
1397     code = afsconf_ClientAuth(tdir, &sc, &scIndex);
1398     if (code) {
1399         ViceLog(0, ("Could not get security object for localAuth\n"));
1400         exit(1);
1401     }
1402     code = afsconf_GetCellInfo(tdir,NULL, AFSCONF_VLDBSERVICE, &info);
1403     if (info.numServers > MAXSERVERS) {
1404         ViceLog(0, ("vl_Initialize: info.numServers=%d (> MAXSERVERS=%d)\n",info.numServers, MAXSERVERS));
1405         exit(1);
1406     }
1407     for (i = 0;i<info.numServers;i++) 
1408         serverconns[i] = rx_NewConnection(info.hostAddr[i].sin_addr.s_addr, info.hostAddr[i].sin_port,
1409                                           USER_SERVICE_ID, sc, scIndex);
1410     code = ubik_ClientInit(serverconns, &cstruct);
1411     if (code) {
1412         ViceLog(0, ("vl_Initialize: ubik client init failed.\n"));
1413         return code;
1414     }
1415     return 0;
1416 }
1417
1418 #define SYSIDMAGIC      0x88aabbcc
1419 #define SYSIDVERSION    1
1420
1421 ReadSysIdFile() {
1422     afs_int32 fd, nentries, i;
1423     struct versionStamp vsn;
1424     struct stat     status;
1425     afsUUID uuid;
1426
1427     if ((stat(AFSDIR_SERVER_SYSID_FILEPATH, &status)) || (status.st_size <= 0)) {
1428         ViceLog(0, ("%s: doesn't exist\n", AFSDIR_SERVER_SYSID_FILEPATH));
1429         return ENOENT;
1430     }
1431     if (!(fd = open(AFSDIR_SERVER_SYSID_FILEPATH, O_RDONLY, 0))) {
1432         ViceLog(0, ("%s: can't open (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1433         return EIO;
1434     }
1435     if ((i = read(fd, (char *)&vsn, sizeof(vsn))) != sizeof(vsn)) {
1436         ViceLog(0, ("%s: Read failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1437         return EIO;
1438     }
1439     if (vsn.magic != SYSIDMAGIC) {
1440         ViceLog(0, ("%s: wrong magic %x (we support %x)\n", AFSDIR_SERVER_SYSID_FILEPATH, vsn.magic, SYSIDMAGIC));
1441         return EIO;
1442     }
1443     if (vsn.version != SYSIDVERSION) {
1444         ViceLog(0, ("%s: wrong version %d (we support %d)\n", AFSDIR_SERVER_SYSID_FILEPATH, vsn.version, SYSIDVERSION));
1445         return EIO;
1446     }
1447     if ((i = read(fd, (char *)&uuid, sizeof(struct afsUUID))) != sizeof(struct afsUUID)) {
1448         ViceLog(0, ("%s: read of uuid failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1449         return EIO;
1450     }
1451     afs_ntohuuid(&uuid);
1452     FS_HostUUID = uuid;
1453     if ((i = read(fd, (char *)&nentries, sizeof(afs_int32))) != sizeof(afs_int32)) {
1454         ViceLog(0, ("%s: Read of entries failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1455         return EIO;
1456     }
1457     if (nentries <= 0 || nentries > ADDRSPERSITE) {
1458         ViceLog(0, ("%s: invalid num of interfaces: %d\n", AFSDIR_SERVER_SYSID_FILEPATH, nentries));
1459         return EIO;
1460     }
1461     FS_HostAddr_cnt = nentries;
1462     for (i = 0; i < nentries; i++) {
1463         if (read(fd, (char *)&FS_HostAddrs[i], sizeof(afs_int32)) != sizeof(afs_int32)) {       
1464             ViceLog(0, ("%s: Read of addresses failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1465             FS_HostAddr_cnt = 0;        /* reset it */
1466             return EIO;
1467         }
1468     }
1469     close(fd);
1470     return 0;
1471 }
1472
1473 WriteSysIdFile() {
1474     afs_int32 fd, nentries, i;
1475     struct versionStamp vsn;
1476     struct stat     status;
1477     afsUUID uuid;
1478     
1479     if (!stat(AFSDIR_SERVER_SYSID_FILEPATH, &status)) {
1480         /*
1481          * File exists; keep the old one around
1482          */
1483         renamefile(AFSDIR_SERVER_SYSID_FILEPATH, AFSDIR_SERVER_OLDSYSID_FILEPATH);      
1484     }
1485     fd = open(AFSDIR_SERVER_SYSID_FILEPATH, O_WRONLY|O_TRUNC|O_CREAT, 0666);
1486     if (fd < 1) {
1487         ViceLog(0, ("%s: can't create (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1488         return EIO;
1489     }
1490     vsn.magic = SYSIDMAGIC;
1491     vsn.version = 1;
1492     if ((i = write(fd, (char *)&vsn, sizeof(vsn))) != sizeof(vsn)) {
1493         ViceLog(0, ("%s: write failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1494         return EIO;
1495     }
1496     uuid = FS_HostUUID;
1497     afs_htonuuid(&uuid);
1498     if ((i = write(fd, (char *)&uuid, sizeof(struct afsUUID))) != sizeof(struct afsUUID)) {
1499         ViceLog(0, ("%s: write of uuid failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1500         return EIO;
1501     }
1502     if ((i = write(fd, (char *)&FS_HostAddr_cnt, sizeof(afs_int32))) != sizeof(afs_int32)) {
1503         ViceLog(0, ("%s: write of # of entries failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1504         return EIO;
1505     }
1506     for (i = 0; i < FS_HostAddr_cnt; i++) {
1507         if (write(fd, (char *)&FS_HostAddrs[i], sizeof(afs_int32)) != sizeof(afs_int32)) {      
1508             ViceLog(0, ("%s: write of addresses failed (%d)\n", AFSDIR_SERVER_SYSID_FILEPATH, errno));
1509             return EIO;
1510         }
1511     }
1512     close(fd);
1513     return 0;
1514 }
1515
1516 /*
1517  * defect 10966 
1518  * This routine sets up the buffers for the VL_RegisterAddrs RPC. All addresses
1519  * in FS_HostAddrs[] are in NBO, while the RPC treats them as a "blob" of data
1520  * and so we need to convert each of them into HBO which is what the extra 
1521  * array called FS_HostAddrs_HBO is used here.
1522  */ 
1523 Do_VLRegisterRPC() {
1524     register int code;
1525     bulkaddrs addrs;
1526     extern int VL_RegisterAddrs();
1527     afs_uint32 FS_HostAddrs_HBO[ADDRSPERSITE];
1528     int i=0;
1529  
1530     for (i=0; i < FS_HostAddr_cnt ; i++) 
1531      FS_HostAddrs_HBO[i]=ntohl(FS_HostAddrs[i]);
1532     addrs.bulkaddrs_len = FS_HostAddr_cnt;
1533     addrs.bulkaddrs_val = (afs_uint32 *)FS_HostAddrs_HBO;
1534     code = ubik_Call(VL_RegisterAddrs, cstruct, 0, &FS_HostUUID, 0, &addrs);
1535     if (code) {
1536        if (code == VL_MULTIPADDR) {
1537           ViceLog(0, ("VL_RegisterAddrs rpc failed; The ethernet address exist on a different server; repair it\n"));
1538           ViceLog(0, ("VL_RegisterAddrs rpc failed; See VLLog for details\n"));
1539           return code;
1540        } else if (code == RXGEN_OPCODE) {
1541           ViceLog(0, ("vlserver doesn't support VL_RegisterAddrs rpc; ignored\n"));
1542           FS_registered = 2;    /* So we don't have to retry in the gc daemon */
1543        } else {
1544           ViceLog(0, ("VL_RegisterAddrs rpc failed; will retry periodically (code=%d, err=%d)\n",
1545                       code, errno));
1546        }
1547     } else {
1548        FS_registered = 2;       /* So we don't have to retry in the gc daemon */
1549        WriteSysIdFile();
1550     }
1551
1552     return 0;
1553 }
1554
1555 #if 0
1556 static int AddrsEqual(cnt, addr1, addr2) 
1557     int cnt;
1558     afs_int32 *addr1, *addr2; 
1559 {
1560     register int i, j;
1561
1562     for (i = 0; i < cnt; i++) {
1563         for (j = 0; j < cnt; j++) {
1564             if (addr1[i] == addr2[j]) break;
1565         }
1566         if (j == cnt) return 0;
1567     }
1568     return 1;
1569 }
1570 #endif
1571
1572 InitVL() {
1573     int (*old)();
1574     afs_int32 code;
1575     afs_int32 cnt, i;
1576     extern int rxi_numNetAddrs;
1577     extern afs_uint32 rxi_NetAddrs[];
1578
1579     /*
1580      * If this fails, it's because something major is wrong, and is not
1581      * likely to be time dependent.
1582      */
1583     code = vl_Initialize(AFSDIR_SERVER_ETC_DIRPATH);
1584     if (code != 0) {
1585         ViceLog(0, ("Couldn't initialize protection library; code=%d.\n", code));
1586         return code;
1587     }
1588
1589     /* Read or create the sysid file and register the fileserver's
1590      * IP addresses with the vlserver.
1591      */
1592     code = ReadSysIdFile();
1593     if (code) {
1594        /* Need to create the file */
1595        ViceLog(0, ("Creating new SysID file\n")); 
1596        if ((code = afs_uuid_create(&FS_HostUUID))) {
1597           ViceLog(0, ("Failed to create new uuid: %d\n", code)); 
1598           exit(1);
1599        }
1600     }
1601     /* A good sysid file exists; inform the vlserver. If any conflicts,
1602      * we always use the latest interface available as the real truth.
1603      */
1604 #ifndef AFS_NT40_ENV
1605     if(AFSDIR_SERVER_NETRESTRICT_FILEPATH || AFSDIR_SERVER_NETINFO_FILEPATH) {
1606       /*
1607        * Find addresses we are supposed to register as per the netrestrict 
1608        * and netinfo files (/usr/afs/local/NetInfo and 
1609        * /usr/afs/local/NetRestict)
1610        */
1611       char reason[1024];
1612       afs_int32 code = parseNetFiles(FS_HostAddrs,NULL, NULL,
1613                                  ADDRSPERSITE, reason,
1614                                  AFSDIR_SERVER_NETINFO_FILEPATH,
1615                                  AFSDIR_SERVER_NETRESTRICT_FILEPATH);
1616       if (code < 0) {
1617         ViceLog(0,("Can't register any valid addresses: %s\n",reason));
1618         exit(1);
1619       }
1620       FS_HostAddr_cnt = (afs_uint32) code;
1621     }
1622     else 
1623 #endif
1624     {
1625       FS_HostAddr_cnt = rx_getAllAddr(FS_HostAddrs, ADDRSPERSITE);
1626     }
1627
1628     FS_registered = 1;
1629     code = Do_VLRegisterRPC();
1630     return code;
1631