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