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