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