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