Initial IBM OpenAFS 1.0 tree
[openafs.git] / src / afsd / afsd.c
1 /*
2  * (C) COPYRIGHT IBM CORPORATION 1987, 1998
3  * LICENSED MATERIALS - PROPERTY OF IBM
4  */
5
6 /*------------------------------------------------------------------------------
7   * afsd.c
8   *
9   *         Information Technology Center
10   *         October 1987
11   *
12   * Description:
13   *     The Andrew File System startup process.  It is responsible for
14   * reading and parsing the various configuration files, starting up
15   * the kernel processes required by AFS and feeding the configuration
16   * information to the kernel.
17   *
18   * Recognized flags are:
19   *     -blocks     The number of blocks available in the workstation cache.
20   *     -files      The target number of files in the workstation cache (Default:
21   *                 1000).
22   *     -rootvol            The name of the root volume to use.
23   *     -stat       The number of stat cache entries.
24   *     -hosts      List of servers to check for volume location info FOR THE
25   *                 HOME CELL.
26   *     -memcache   Use an in-memory cache rather than disk.
27   *     -cachedir    The base directory for the workstation cache.
28   *     -mountdir   The directory on which the AFS is to be mounted.
29   *     -confdir    The configuration directory .
30   *     -nosettime  Don't keep checking the time to avoid drift.
31   *     -verbose     Be chatty.
32   *     -debug     Print out additional debugging info.
33   *     -kerndev    [OBSOLETE] The kernel device for AFS.
34   *     -dontfork   [OBSOLETE] Don't fork off as a new process.
35   *     -daemons   The number of background daemons to start (Default: 2).
36   *     -rmtsys    Also fires up an afs remote sys call (e.g. pioctl, setpag)
37   *                support daemon 
38   *     -chunksize [n]   2^n is the chunksize to be used.  0 is default.
39   *     -dcache    The number of data cache entries.
40   *     -biods     Number of bkg I/O daemons (AIX3.1 only)
41   *     -prealloc  Number of preallocated "small" memory blocks
42   *     -pininodes Number of inodes which can be spared from inode[] for 
43   *                pointing at Vfiles.  If this is set too high, you may have
44   *                system problems, which can only be ameliorated by changing
45   *                NINODE (or equivalent) and rebuilding the kernel.
46   *                This option is now disabled.
47   *     -logfile   Place where to put the logfile (default in <cache>/etc/AFSLog.
48   *     -waitclose make close calls always synchronous (slows em down, tho)
49   *     -shutdown  Shutdown afs daemons
50   *---------------------------------------------------------------------------*/
51
52 #define VFS 1
53
54 #include <afs/param.h>
55 #include <afs/cmd.h>
56
57 #include <assert.h>
58 #include <itc.h>
59 #include <afs/afsutil.h>
60 #undef in
61 #undef out
62 #include <stdlib.h>
63 #include <stdio.h>
64 #include <signal.h>
65 #include <string.h>
66 #include <stdlib.h>
67 #include <time.h>
68 #include <sys/types.h>
69 #include <sys/stat.h>
70 #include <sys/file.h>
71 #include <errno.h>
72 #include <sys/time.h>
73 #ifdef  AFS_DEC_ENV
74 #include <sys/param.h>
75 #include <sys/fs_types.h>
76 #endif
77 #if     defined(AFS_SUN_ENV)
78 #include <sys/vfs.h>
79 #endif
80 #ifndef AFS_AIX41_ENV
81 #include <sys/mount.h>
82 #endif
83 #include <dirent.h>
84 #ifdef    AFS_SUN5_ENV
85 #include <sys/fcntl.h>
86 #include <sys/mnttab.h>
87 #include <sys/mntent.h>
88 #else
89 #if     defined(AFS_SUN_ENV) || defined(AFS_SGI_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_LINUX20_ENV)
90 #include <mntent.h>
91 #endif
92 #endif
93
94 #if defined(AFS_OSF_ENV) || defined(AFS_DEC_ENV)
95 #include <sys/mount.h>
96 #else
97 #include <sys/vfs.h>
98 #endif
99
100 #include <netinet/in.h>
101 #include <afs/afs_args.h>
102 #include <afs/cellconfig.h>
103 #include <afs/auth.h>
104 #include <ctype.h>
105 #include <afs/afssyscalls.h>
106 #include <afs/afsutil.h>
107
108 #ifdef AFS_SGI61_ENV
109 #include <unistd.h>
110 #include <libelf.h>
111 #include <dwarf.h>
112 #include <libdwarf.h>
113 void set_staticaddrs(void);
114 #endif /* AFS_SGI61_ENV */
115 #if defined(AFS_SGI62_ENV) && !defined(AFS_SGI65_ENV)
116 #include <sym.h>
117 #include <symconst.h>
118 #endif
119 #ifdef AFS_SGI65_ENV
120 #include <sched.h>
121 #endif
122 #ifdef AFS_LINUX20_ENV
123 #include <sys/resource.h>
124 #endif
125
126 #ifndef MOUNT_AFS
127 #define MOUNT_AFS AFS_MOUNT_AFS
128 #endif /* MOUNT_AFS */
129
130 #if AFS_HAVE_STATVFS
131 #include <sys/statvfs.h>
132 #else
133 #if !defined(AFS_OSF_ENV)
134 #include <sys/statfs.h>
135 #endif
136 #endif
137
138 #undef  VIRTUE
139 #undef  VICE
140
141 #define CACHEINFOFILE   "cacheinfo"
142 #define AFSLOGFILE      "AFSLog"
143 #define DCACHEFILE      "CacheItems"
144 #define VOLINFOFILE     "VolumeItems"
145
146 #define MAXIPADDRS 1024
147
148 char LclCellName[64];
149
150 #define MAX_CACHE_LOOPS 4
151
152 /*
153  * Internet address (old style... should be updated).  This was pulled out of the old 4.2
154  * version of <netinet/in.h>, since it's still useful.
155  */
156 struct in_addr_42 {
157         union {
158                 struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;
159                 struct { u_short s_w1,s_w2; } S_un_w;
160                 afs_uint32 S_addr;
161         } S_un;
162 #define s_host  S_un.S_un_b.s_b2        /* host on imp */
163 #define s_net   S_un.S_un_b.s_b1        /* network */
164 #define s_imp   S_un.S_un_w.s_w2        /* imp */
165 #define s_impno S_un.S_un_b.s_b4        /* imp # */
166 #define s_lh    S_un.S_un_b.s_b3        /* logical host */
167 };
168
169 #define mPrintIPAddr(ipaddr)  printf("[%d.%d.%d.%d] ",          \
170       ((struct in_addr_42 *) &(ipaddr))->S_un.S_un_b.s_b1,      \
171       ((struct in_addr_42 *) &(ipaddr))->S_un.S_un_b.s_b2,      \
172       ((struct in_addr_42 *) &(ipaddr))->S_un.S_un_b.s_b3,      \
173       ((struct in_addr_42 *) &(ipaddr))->S_un.S_un_b.s_b4)
174
175 /*
176  * Global configuration variables.
177  */
178 afs_int32 afs_shutdown = 0;
179 afs_int32 cacheBlocks;                  /*Num blocks in the cache*/
180 afs_int32 cacheFiles    = 1000;                 /*Optimal # of files in workstation cache*/
181 afs_int32 cacheStatEntries =    300;            /*Number of stat cache entries*/
182 char cacheBaseDir[1024];                /*Where the workstation AFS cache lives*/
183 char confDir[1024];                     /*Where the workstation AFS configuration lives*/
184 char fullpn_DCacheFile[1024];           /*Full pathname of DCACHEFILE*/
185 char fullpn_VolInfoFile[1024];          /*Full pathname of VOLINFOFILE*/
186 char fullpn_AFSLogFile[1024];           /*Full pathname of AFSLOGFILE*/
187 char fullpn_CacheInfo[1024];            /*Full pathname of CACHEINFO*/
188 char fullpn_VFile[1024];                /*Full pathname of data cache files*/
189 char *vFileNumber;                      /*Ptr to the number part of above pathname*/
190 int sawCacheMountDir = 0;               /* from cmd line */
191 int sawCacheBaseDir = 0;
192 int sawCacheBlocks = 0;
193 int sawDCacheSize = 0;
194 int sawBiod = 0;
195 char cacheMountDir[1024];               /*Mount directory for AFS*/
196 char rootVolume[64] = "root.afs";       /*AFS root volume name*/
197 afs_int32 cacheSetTime = 1;                     /*Keep checking time to avoid drift?*/
198 afs_int32 isHomeCell;                   /*Is current cell info for the home cell?*/
199 afs_int32 lookingForHomeCell;           /*Are we still looking for the home cell?*/
200 int createAndTrunc = O_CREAT | O_TRUNC; /*Create & truncate on open*/
201 int ownerRWmode = 0600;                 /*Read/write OK by owner*/
202 static int filesSet = 0;                /*True if number of files explicitly set*/
203 static int nDaemons = 2;                /* Number of background daemons */
204 static int chunkSize = 0;               /* 2^chunkSize bytes per chunk */
205 static int dCacheSize = 300;            /* # of dcache entries */
206 static int vCacheSize = 50;             /* # of volume cache entries */
207 static int rootVolSet = 0;              /*True if root volume name explicitly set*/
208 int addrNum;                            /*Cell server address index being printed*/
209 static int cacheFlags = 0;              /*Flags to cache manager*/
210 static int nBiods = 5;                  /* AIX3.1 only */
211 static int preallocs = 400;             /* Def # of allocated memory blocks */
212 static int enable_peer_stats = 0;       /* enable rx stats */
213 static int enable_process_stats = 0;    /* enable rx stats */
214 #ifdef notdef
215 static int inodes = 60;                 /* VERY conservative, but has to be */
216 #endif
217 int afsd_verbose = 0;                   /*Are we being chatty?*/
218 int afsd_debug = 0;                     /*Are we printing debugging info?*/
219 int afsd_CloseSynch = 0;                /*Are closes synchronous or not? */
220
221 #ifdef AFS_SGI62_ENV
222 #define AFSD_INO_T ino64_t
223 #else
224 #define AFSD_INO_T afs_uint32
225 #endif
226 AFSD_INO_T *inode_for_V;                /* Array of inodes for desired
227                                          * cache files */
228 int missing_DCacheFile  = 1;            /*Is the DCACHEFILE missing?*/
229 int missing_VolInfoFile = 1;            /*Is the VOLINFOFILE missing?*/
230 int afsd_rmtsys = 0;                            /* Default: don't support rmtsys */
231 struct afs_cacheParams cparams;          /* params passed to cache manager */
232
233 static int HandleMTab();
234
235 /* ParseArgs is now obsolete, being handled by cmd */
236
237 /*------------------------------------------------------------------------------
238   * ParseCacheInfoFile
239   *
240   * Description:
241   *     Open the file containing the description of the workstation's AFS cache
242   *     and pull out its contents.  The format of this file is as follows:
243   *
244   *         cacheMountDir:cacheBaseDir:cacheBlocks
245   *
246   * Arguments:
247   *     None.
248   *
249   * Returns:
250   *     0 if everything went well,
251   *     1 otherwise.
252   *
253   * Environment:
254   *     Nothing interesting.
255   *
256   *  Side Effects:
257   *     Sets globals.
258   *---------------------------------------------------------------------------*/
259
260 int ParseCacheInfoFile()
261 {
262     static char rn[]="ParseCacheInfoFile";      /*This routine's name*/
263     FILE *cachefd;                              /*Descriptor for cache info file*/
264     int parseResult;                            /*Result of our fscanf()*/
265     afs_int32 tCacheBlocks;
266     char tCacheBaseDir[1024], *tbd, tCacheMountDir[1024], *tmd;
267
268     if (afsd_debug)
269         printf("%s: Opening cache info file '%s'...\n",
270             rn, fullpn_CacheInfo);
271
272     cachefd = fopen(fullpn_CacheInfo, "r");
273     if (!cachefd) {
274         printf("%s: Can't read cache info file '%s'\n",
275                rn, fullpn_CacheInfo);
276         return(1);
277     }
278
279     /*
280      * Parse the contents of the cache info file.  All chars up to the first
281      * colon are the AFS mount directory, all chars to the next colon are the
282      * full path name of the workstation cache directory and all remaining chars
283      * represent the number of blocks in the cache.
284      */
285     tCacheMountDir[0] = tCacheBaseDir[0] = '\0';
286     parseResult = fscanf(cachefd,
287                           "%1024[^:]:%1024[^:]:%d",
288                           tCacheMountDir, tCacheBaseDir, &tCacheBlocks);
289
290     /*
291      * Regardless of how the parse went, we close the cache info file.
292      */
293     fclose(cachefd);
294
295     if (parseResult == EOF || parseResult < 3) {
296         printf("%s: Format error in cache info file!\n",
297                rn);
298         if (parseResult == EOF)
299             printf("\tEOF encountered before any field parsed.\n");
300         else
301             printf("\t%d out of 3 fields successfully parsed.\n",
302                    parseResult);
303
304         printf("\tcacheMountDir: '%s'\n\tcacheBaseDir: '%s'\n\tcacheBlocks: %d\n",
305                cacheMountDir, cacheBaseDir, cacheBlocks);
306         return(1);
307     }
308
309     for (tmd = tCacheMountDir; *tmd == '\n' || *tmd == ' ' || *tmd == '\t'; tmd++) ;
310     for (tbd = tCacheBaseDir; *tbd == '\n' || *tbd == ' ' || *tbd == '\t'; tbd++) ;
311     /* now copy in the fields not explicitly overridden by cmd args */
312     if (!sawCacheMountDir) 
313         strcpy(cacheMountDir, tmd);
314     if (!sawCacheBaseDir)
315         strcpy(cacheBaseDir, tbd);
316     if  (!sawCacheBlocks)
317         cacheBlocks = tCacheBlocks;
318
319     if (afsd_debug) {
320         printf("%s: Cache info file successfully parsed:\n",
321                rn);
322         printf("\tcacheMountDir: '%s'\n\tcacheBaseDir: '%s'\n\tcacheBlocks: %d\n",
323                tmd, tbd, tCacheBlocks);
324     }
325     if (! (cacheFlags & AFSCALL_INIT_MEMCACHE))
326         PartSizeOverflow(tbd, cacheBlocks);
327
328     return(0);
329 }
330
331 /*
332  * All failures to open the partition are ignored. Also if the cache dir 
333  * isn't a mounted partition it's also ignored since we can't guarantee 
334  * what will be stored afterwards. Too many if's. This is now purely
335  * advisory. ODS with over 2G partition also gives warning message.
336  */
337 PartSizeOverflow(path, cs)
338 char *path;
339 int cs;
340 {
341     int bsize=-1, totalblks, mint;
342 #if AFS_HAVE_STATVFS
343     struct statvfs statbuf;
344
345     if (statvfs(path, &statbuf) != 0) {  
346         if (afsd_debug) printf("statvfs failed on %s; skip checking for adequate partition space\n", path);
347         return 0;
348     }
349     totalblks = statbuf.f_blocks;
350     bsize = statbuf.f_frsize;
351 #else
352     struct statfs statbuf;
353
354     if (statfs(path, &statbuf) < 0) {
355         if (afsd_debug) printf("statfs failed on %s; skip checking for adequate partition space\n", path);
356         return 0;
357     }
358     totalblks = statbuf.f_blocks;
359     bsize = statbuf.f_bsize;
360 #endif
361     if (bsize == -1) return 0;  /* sucess */
362
363     /* now free and totalblks are in fragment units, but we want them in 1K units */
364     if (bsize >= 1024) {
365         totalblks *= (bsize / 1024);
366     } else {
367         totalblks /= (1024/bsize);
368     }
369
370     mint = totalblks - ((totalblks * 5) / 100);
371     if (cs > mint) {
372         printf("Cache size (%d) must be less than 95%% of partition size (which is %d). Lower cache size\n", 
373                cs, mint);
374     } 
375 }
376
377 /*-----------------------------------------------------------------------------
378   * GetVFileNumber
379   *
380   * Description:
381   *     Given the final component of a filename expected to be a data cache file,
382   *     return the integer corresponding to the file.  Note: we reject names that
383   *     are not a ``V'' followed by an integer.  We also reject those names having
384   *     the right format but lying outside the range [0..cacheFiles-1].
385   *
386   * Arguments:
387   *     fname : Char ptr to the filename to parse.
388   *
389   * Returns:
390   *     >= 0 iff the file is really a data cache file numbered from 0 to cacheFiles-1, or
391   *     -1      otherwise.
392   *
393   * Environment:
394   *     Nothing interesting.
395   *
396   * Side Effects:
397   *     None.
398   *---------------------------------------------------------------------------*/
399
400 int GetVFileNumber(fname)
401     char *fname;
402 {
403     int computedVNumber;    /*The computed file number we return*/
404     int filenameLen;        /*Number of chars in filename*/
405     int currDigit;          /*Current digit being processed*/
406
407     /*
408      * The filename must have at least two characters, the first of which must be a ``V''
409      * and the second of which cannot be a zero unless the file is exactly two chars long.
410      */
411     filenameLen = strlen(fname);
412     if (filenameLen < 2)
413         return(-1);
414     if (fname[0] != 'V')
415         return(-1);
416     if ((filenameLen > 2) && (fname[1] == '0'))
417         return(-1);
418
419     /*
420      * Scan through the characters in the given filename, failing immediately if a non-digit
421      * is found.
422      */
423     for (currDigit = 1; currDigit < filenameLen; currDigit++)
424         if (isdigit(fname[currDigit]) == 0)
425             return(-1);
426
427     /*
428      * All relevant characters are digits.  Pull out the decimal number they represent.
429      * Reject it if it's out of range, otherwise return it.
430      */
431     computedVNumber = atoi(++fname);
432     if (computedVNumber < cacheFiles)
433         return(computedVNumber);
434     else
435         return(-1);
436 }
437
438 /*-----------------------------------------------------------------------------
439   * CreateCacheFile
440   *
441   * Description:
442   *     Given a full pathname for a file we need to create for the workstation AFS
443   *     cache, go ahead and create the file.
444   *
445   * Arguments:
446   *     fname : Full pathname of file to create.
447   *
448   * Returns:
449   *     0   iff the file was created,
450   *     -1  otherwise.
451   *
452   * Environment:
453   *     The given cache file has been found to be missing.
454   *
455   * Side Effects:
456   *     As described.
457   *---------------------------------------------------------------------------*/
458
459 int CreateCacheFile(fname)
460     char *fname;
461 {
462     static char rn[] = "CreateCacheFile";   /*Routine name*/
463     int cfd;                                /*File descriptor to AFS cache file*/
464     int closeResult;                        /*Result of close()*/
465
466     if (afsd_verbose)
467         printf("%s: Creating cache file '%s'\n",
468                rn, fname);
469     cfd = open(fname, createAndTrunc, ownerRWmode);
470     if  (cfd <= 0) {
471         printf("%s: Can't create '%s', error return is %d (%d)\n",
472                rn, fname, cfd, errno);
473         return(-1);
474     }
475     closeResult = close(cfd);
476     if  (closeResult) {
477         printf("%s: Can't close newly-created AFS cache file '%s' (code %d)\n",
478                rn, fname, errno);
479         return(-1);
480     }
481
482     return(0);
483 }
484
485 /*-----------------------------------------------------------------------------
486   * SweepAFSCache
487   *
488   * Description:
489   *     Sweep through the AFS cache directory, recording the inode number for
490   *     each valid data cache file there.  Also, delete any file that doesn't beint32
491   *     in the cache directory during this sweep, and remember which of the other
492   *     residents of this directory were seen.  After the sweep, we create any data
493   *     cache files that were missing.
494   *
495   * Arguments:
496   *     vFilesFound : Set to the number of data cache files found.
497   *
498   * Returns:
499   *     0   if everything went well,
500   *     -1 otherwise.
501   *
502   * Environment:
503   *     This routine may be called several times.  If the number of data cache files
504   *     found is less than the global cacheFiles, then the caller will need to call it
505   *     again to record the inodes of the missing zero-length data cache files created
506   *     in the previous call.
507   *
508   * Side Effects:
509   *     Fills up the global inode_for_V array, may create and/or delete files as
510   *     explained above.
511   *---------------------------------------------------------------------------*/
512
513 int SweepAFSCache(vFilesFound)
514     int *vFilesFound;
515 {
516     static char rn[] = "SweepAFSCache"; /*Routine name*/
517     char fullpn_FileToDelete[1024];     /*File to be deleted from cache*/
518     char *fileToDelete;                 /*Ptr to last component of above*/
519     DIR *cdirp;                         /*Ptr to cache directory structure*/
520 #ifdef AFS_SGI62_ENV
521     struct dirent64 *currp;             /*Current directory entry*/
522 #else
523     struct dirent *currp;               /*Current directory entry*/
524 #endif
525     int vFileNum;                       /*Data cache file's associated number*/
526
527     if (cacheFlags & AFSCALL_INIT_MEMCACHE) {
528         if (afsd_debug)
529             printf("%s: Memory Cache, no cache sweep done\n", rn);
530         *vFilesFound = 0;
531         return 0;
532     }
533
534     if (afsd_debug)
535         printf("%s: Opening cache directory '%s'\n",
536                rn, cacheBaseDir);
537
538     if (chmod(cacheBaseDir, 0700)) {            /* force it to be 700 */
539         printf("%s: Can't 'chmod 0700' the cache dir, '%s'.\n",
540                rn, cacheBaseDir);
541         return (-1);
542     }
543     cdirp = opendir(cacheBaseDir);
544     if (cdirp == (DIR *)0) {
545         printf("%s: Can't open AFS cache directory, '%s'.\n",
546                rn, cacheBaseDir);
547         return(-1);
548     }
549
550     /*
551      * Scan the directory entries, remembering data cache file inodes and the existance
552      * of other important residents.  Delete all files that don't belong here.
553      */
554     *vFilesFound = 0;
555     sprintf(fullpn_FileToDelete, "%s/", cacheBaseDir);
556     fileToDelete = fullpn_FileToDelete + strlen(fullpn_FileToDelete);
557
558 #ifdef AFS_SGI62_ENV
559     for (currp = readdir64(cdirp); currp; currp = readdir64(cdirp))
560 #else
561     for (currp = readdir(cdirp); currp; currp = readdir(cdirp))
562 #endif
563         {
564         if (afsd_debug) {
565             printf("%s: Current directory entry:\n",
566                    rn);
567 #ifdef AFS_SGI62_ENV
568             printf("\tinode=%lld, reclen=%d, name='%s'\n",
569                    currp->d_ino, currp->d_reclen, currp->d_name);
570 #else
571             printf("\tinode=%d, reclen=%d, name='%s'\n",
572                    currp->d_ino, currp->d_reclen, currp->d_name);
573 #endif
574         }
575
576         /*
577          * Guess current entry is for a data cache file.
578          */
579         vFileNum = GetVFileNumber(currp->d_name);
580         if (vFileNum >= 0) {
581             /*
582              * Found a valid data cache filename.  Remember this file's inode and bump
583              * the number of files found.
584              */
585             inode_for_V[vFileNum] = currp->d_ino;
586             (*vFilesFound)++;
587         }
588         else if (strcmp(currp->d_name, DCACHEFILE) == 0) {
589             /*
590              * Found the file holding the dcache entries.
591              */
592             missing_DCacheFile = 0;
593         }
594         else if (strcmp(currp->d_name, VOLINFOFILE) == 0) {
595             /*
596              * Found the file holding the volume info.
597              */
598             missing_VolInfoFile = 0;
599         }
600         else  if ((strcmp(currp->d_name,          ".") == 0) ||
601                   (strcmp(currp->d_name,         "..") == 0) ||
602                   (strcmp(currp->d_name, "lost+found") == 0)) {
603             /*
604              * Don't do anything - this file is legit, and is to be left alone.
605              */
606         }
607         else {
608             /*
609              * This file doesn't belong in the cache.  Nuke it.
610              */
611             sprintf(fileToDelete, "%s", currp->d_name);
612             if (afsd_verbose)
613                 printf("%s: Deleting '%s'\n",
614                        rn, fullpn_FileToDelete);
615             if (unlink(fullpn_FileToDelete)) {
616                 printf("%s: Can't unlink '%s', errno is %d\n",
617                        rn, fullpn_FileToDelete, errno);
618             }
619         }
620     }
621
622     /*
623      * Create all the cache files that are missing.
624      */
625     if (missing_DCacheFile) {
626         if (afsd_verbose)
627             printf("%s: Creating '%s'\n",
628                    rn, fullpn_DCacheFile);
629         if (CreateCacheFile(fullpn_DCacheFile))
630             printf("%s: Can't create '%s'\n",
631                    rn, fullpn_DCacheFile);
632     }
633     if (missing_VolInfoFile) {
634         if (afsd_verbose)
635             printf("%s: Creating '%s'\n",
636                    rn, fullpn_VolInfoFile);
637         if (CreateCacheFile(fullpn_VolInfoFile))
638             printf("%s: Can't create '%s'\n",
639                    rn, fullpn_VolInfoFile);
640     }
641
642     if (*vFilesFound < cacheFiles) {
643         /*
644          * We came up short on the number of data cache files found.  Scan through the inode
645          * list and create all missing files.
646          */
647         for (vFileNum = 0; vFileNum < cacheFiles; vFileNum++)
648             if (inode_for_V[vFileNum] == (AFSD_INO_T)0) {
649                 sprintf(vFileNumber, "%d", vFileNum);
650                 if (afsd_verbose)
651                     printf("%s: Creating '%s'\n",
652                            rn, fullpn_VFile);
653                 if (CreateCacheFile(fullpn_VFile))
654                     printf("%s: Can't create '%s'\n",
655                            rn, fullpn_VFile);
656             }
657     }
658     
659     /*
660      * Close the directory, return success.
661      */
662     if (afsd_debug)
663         printf("%s: Closing cache directory.\n",
664                rn);
665     closedir(cdirp);
666     return(0);
667 }
668
669 static ConfigCell(aci, arock, adir)
670 register struct afsconf_cell *aci;
671 char *arock;
672 struct afsconf_dir *adir; {
673     register int isHomeCell;
674     register int i;
675     afs_int32 cellFlags;
676     afs_int32 hosts[MAXHOSTSPERCELL];
677     
678     /* figure out if this is the home cell */
679     isHomeCell = (strcmp(aci->name, LclCellName) == 0);
680     if (isHomeCell) {
681         lookingForHomeCell = 0;
682         cellFlags = 1;      /* home cell, suid is ok */
683     }
684     else {
685         cellFlags = 2;      /* not home, suid is forbidden */
686     }
687     
688     /* build address list */
689     for(i=0;i<MAXHOSTSPERCELL;i++)
690         memcpy(&hosts[i], &aci->hostAddr[i].sin_addr, sizeof(afs_int32));
691
692     if (aci->linkedCell) cellFlags |= 4; /* Flag that linkedCell arg exists,
693                                             for upwards compatibility */
694
695     /* configure one cell */
696     call_syscall(AFSOP_ADDCELL2,
697              hosts,                     /* server addresses */
698              aci->name,                 /* cell name */
699              cellFlags,                 /* is this the home cell? */
700              aci->linkedCell);          /* Linked cell, if any */
701     return 0;
702 }
703
704 #ifdef mac2
705 #include <sys/ioctl.h>
706 #endif /* mac2 */
707
708 #ifdef AFS_SGI65_ENV
709 #define SET_RTPRI(P) {  \
710     struct sched_param sp; \
711     sp.sched_priority = P; \
712     if (sched_setscheduler(0, SCHED_RR, &sp)<0) { \
713         perror("sched_setscheduler"); \
714     } \
715 }
716 #define SET_AFSD_RTPRI() SET_RTPRI(68)
717 #define SET_RX_RTPRI()   SET_RTPRI(199)
718 #else
719 #ifdef AFS_LINUX20_ENV
720 #define SET_AFSD_RTPRI()
721 #define SET_RX_RTPRI()  do { if (setpriority(PRIO_PROCESS, 0, -10)<0) \
722                            perror("setting rx priority"); \
723                          } while (0)
724 #else
725 #define SET_AFSD_RTPRI() 
726 #define SET_RX_RTPRI()   
727 #endif
728 #endif
729
730 mainproc(as, arock)
731   register struct cmd_syndesc *as;
732   char *arock;
733 {
734     static char rn[] = "afsd";      /*Name of this routine*/
735     register afs_int32 code;                /*Result of fork()*/
736     register int i;
737     int currVFile;                  /*Current AFS cache file number passed in*/
738     int mountFlags;                 /*Flags passed to mount()*/
739     int lookupResult;               /*Result of GetLocalCellName()*/
740     int cacheIteration;             /*How many times through cache verification*/
741     int vFilesFound;                /*How many data cache files were found in sweep*/
742     struct afsconf_dir *cdir;       /* config dir */
743     FILE *logfd;
744 #ifdef  AFS_SUN5_ENV
745     struct stat st;
746 #endif
747     afs_int32 vfs1_type = -1;
748 #ifdef AFS_SGI65_ENV
749     struct sched_param sp;
750 #endif
751
752 #ifdef AFS_SGI_VNODE_GLUE
753     if (afs_init_kernel_config(-1) <0) {
754         printf("Can't determine NUMA configuration, not starting AFS.\n");
755         exit(1);
756     }
757 #endif
758
759     /* call atoi on the appropriate parsed results */
760     if (as->parms[0].items) {
761         /* -blocks */
762         cacheBlocks = atoi(as->parms[0].items->data);
763         sawCacheBlocks = 1;
764     }
765     if (as->parms[1].items) {
766         /* -files */
767         cacheFiles = atoi(as->parms[1].items->data);
768         filesSet = 1;   /* set when spec'd on cmd line */
769     }
770     if (as->parms[2].items) {
771         /* -rootvol */
772         strcpy(rootVolume, as->parms[2].items->data);
773         rootVolSet = 1;
774     }
775     if (as->parms[3].items) {
776         /* -stat */
777         cacheStatEntries = atoi(as->parms[3].items->data);
778     }
779     if (as->parms[4].items) {
780         /* -memcache */
781         cacheBaseDir[0] = '\0';
782         sawCacheBaseDir = 1;
783         cacheFlags |= AFSCALL_INIT_MEMCACHE;
784         if (chunkSize == 0)
785             chunkSize = 13;
786     }
787     if (as->parms[5].items) {
788         /* -cachedir */
789         strcpy(cacheBaseDir, as->parms[5].items->data);
790         sawCacheBaseDir = 1;
791     }
792     if (as->parms[6].items) {
793         /* -mountdir */
794         strcpy(cacheMountDir, as->parms[6].items->data);
795         sawCacheMountDir = 1;
796     }
797     if (as->parms[7].items) {
798         /* -daemons */
799         nDaemons = atoi(as->parms[7].items->data);
800     }
801     if (as->parms[8].items) {
802         /* -nosettime */
803         cacheSetTime = FALSE;
804     }
805     if (as->parms[9].items) {
806         /* -verbose */
807         afsd_verbose = 1;
808     }
809     if (as->parms[10].items) {
810         /* -rmtsys */
811         afsd_rmtsys = 1;
812     }
813     if (as->parms[11].items) {
814         /* -debug */
815         afsd_debug = 1;
816         afsd_verbose = 1;
817     }
818     if (as->parms[12].items) {
819         /* -chunksize */
820         chunkSize = atoi(as->parms[12].items->data);
821         if (chunkSize < 0 || chunkSize > 30) {
822             printf("afsd:invalid chunk size spec'd, using default\n");
823             chunkSize = 0;
824         }
825     }
826     if (as->parms[13].items) {
827         /* -dcache */
828         dCacheSize = atoi(as->parms[13].items->data);
829         sawDCacheSize = 1;
830     }
831     if (as->parms[14].items) {
832         /* -volumes */
833         vCacheSize = atoi(as->parms[14].items->data);
834     }
835     if (as->parms[15].items) {
836         /* -biods */
837 #ifndef AFS_AIX32_ENV
838         printf("afsd: [-biods] currently only enabled for aix3.x VM supported systems\n");
839 #else
840         nBiods = atoi(as->parms[15].items->data);
841         sawBiod = 1;
842 #endif
843     }
844     if (as->parms[16].items) {
845         /* -prealloc */
846         preallocs = atoi(as->parms[16].items->data);
847     }
848 #ifdef notdef 
849     if (as->parms[17].items) {
850         /* -pininodes */
851         inodes = atoi(as->parms[17].items->data);
852     }
853 #endif
854     strcpy(confDir, AFSDIR_CLIENT_ETC_DIRPATH);
855     if (as->parms[17].items) {
856         /* -confdir */
857         strcpy(confDir, as->parms[17].items->data);
858     }
859     sprintf(fullpn_CacheInfo,  "%s/%s", confDir, CACHEINFOFILE);
860     sprintf(fullpn_AFSLogFile,  "%s/%s", confDir, AFSLOGFILE);
861     if (as->parms[18].items) {
862         /* -logfile */
863         strcpy(fullpn_AFSLogFile, as->parms[18].items->data);
864     }
865     if (as->parms[19].items) {
866       /* -waitclose */
867       afsd_CloseSynch = 1;
868     }
869     if (as->parms[20].items) {
870         /* -shutdown */
871         afs_shutdown = 1;
872         /* 
873          * Cold shutdown is the default
874          */
875         printf("afsd: Shutting down all afs processes and afs state\n");
876         call_syscall(AFSOP_SHUTDOWN, 1);
877         exit(0);
878     }
879     if (as->parms[21].items) {
880         /* -enable_peer_stats */
881         enable_peer_stats = 1;
882     }
883     if (as->parms[22].items) {
884         /* -enable_process_stats */
885         enable_process_stats = 1;
886     }
887     if (as->parms[23].items) {
888         /* -mem_alloc_sleep */
889         cacheFlags |= AFSCALL_INIT_MEMCACHE_SLEEP;
890     }
891
892     /*
893      * Pull out all the configuration info for the workstation's AFS cache and
894      * the cellular community we're willing to let our users see.
895      */
896     cdir = afsconf_Open(confDir);
897     if (!cdir) {
898         printf("afsd: some file missing or bad in %s\n", confDir);
899         exit(1);
900     }
901
902     lookupResult = afsconf_GetLocalCell(cdir, LclCellName, sizeof(LclCellName));
903     if (lookupResult) {
904         printf("%s: Can't get my home cell name!  [Error is %d]\n",
905                rn, lookupResult);
906     }
907     else {
908         if (afsd_verbose)
909             printf("%s: My home cell is '%s'\n",
910                    rn, LclCellName);
911     }
912
913     /* parse cacheinfo file if this is a diskcache */
914     if (ParseCacheInfoFile()) {
915         exit(1);
916     }
917
918     if ((logfd = fopen(fullpn_AFSLogFile,"r+")) == 0) {
919         if (afsd_verbose)  printf("%s: Creating '%s'\n",  rn, fullpn_AFSLogFile);
920         if (CreateCacheFile(fullpn_AFSLogFile)) {
921             printf("%s: Can't create '%s' (You may want to use the -logfile option)\n",  rn, fullpn_AFSLogFile);
922             exit(1);
923         }
924     } else
925         fclose(logfd);
926
927     /* do some random computations in memcache case to get things to work
928      * reasonably no matter which parameters you set.
929      */
930     if (cacheFlags & AFSCALL_INIT_MEMCACHE) {
931         /* memory cache: size described either as blocks or dcache entries, but
932          * not both.
933          */
934         if (sawDCacheSize) {
935             if (sawCacheBlocks) {
936                 printf("%s: can't set cache blocks and dcache size simultaneously when diskless.\n", rn);
937                 exit(1);
938             }
939             /* compute the cache size based on # of chunks times the chunk size */
940             i = (chunkSize == 0? 13 : chunkSize);
941             i = (1<<i); /* bytes per chunk */
942             cacheBlocks = i * dCacheSize;
943             sawCacheBlocks = 1; /* so that ParseCacheInfoFile doesn't overwrite */
944         }
945         else {
946             /* compute the dcache size from overall cache size and chunk size */
947             i = (chunkSize == 0? 13 : chunkSize);
948             /* dCacheSize = (cacheBlocks << 10) / (1<<i); */
949             if (i > 10) {
950                 dCacheSize = (cacheBlocks >> (i-10));
951             } else if (i < 10) {
952                 dCacheSize = (cacheBlocks << (10-i));
953             } else {
954                 dCacheSize = cacheBlocks;
955             }
956             /* don't have to set sawDCacheSize here since it isn't overwritten
957              * by ParseCacheInfoFile.
958              */
959         }
960         /* kernel computes # of dcache entries as min of cacheFiles and dCacheSize,
961          * so we now make them equal.
962          */
963         cacheFiles = dCacheSize;
964     }
965     else {
966         /* Disk cache:
967          * Compute the number of cache files based on cache size,
968          * but only if -files isn't given on the command line.
969          * Don't let # files be so small as to prevent full utilization 
970          * of the cache unless user has explicitly asked for it.
971          * average V-file is ~10K, according to tentative empirical studies.
972          */
973         if (!filesSet) {
974             cacheFiles = cacheBlocks / 10;       
975             if (cacheFiles <  100) cacheFiles =  100;
976             /* Always allow more files than chunks.  Presume average V-file 
977              * is ~67% of a chunk...  (another guess, perhaps Honeyman will
978              * have a grad student write a paper).  i is KILOBYTES.
979              */
980             i = 1 << (chunkSize == 0? 6 : (chunkSize<10 ? 0 : chunkSize -10));
981             cacheFiles = max(cacheFiles, 1.5 * (cacheBlocks / i));
982             /* never permit more files than blocks, while leaving space for
983              * VolumeInfo and CacheItems files.  VolumeInfo is usually 20K,
984              * CacheItems is 50 Bytes / file (== 1K/20)
985              */
986 #define VOLINFOSZ 20
987 #define CACHEITMSZ (cacheFiles / 20)
988 #ifdef AFS_AIX_ENV
989             cacheFiles= min(cacheFiles,(cacheBlocks -VOLINFOSZ -CACHEITMSZ)/4);
990 #else
991             cacheFiles = min(cacheFiles, cacheBlocks - VOLINFOSZ - CACHEITMSZ);
992 #endif
993             if (cacheFiles <  100) 
994               fprintf (stderr, "%s: WARNING: cache probably too small!\n", rn);
995         }
996         if (!sawDCacheSize) {
997             if ((cacheFiles / 2) > dCacheSize)
998                 dCacheSize = cacheFiles / 2;
999             if (dCacheSize > 2000)
1000                 dCacheSize = 2000;
1001         }
1002     }
1003
1004     /*
1005      * Create and zero the inode table for the desired cache files.
1006      */
1007     inode_for_V = (AFSD_INO_T *) malloc(cacheFiles * sizeof(AFSD_INO_T));
1008     if (inode_for_V == (AFSD_INO_T *)0) {
1009         printf("%s: malloc() failed for cache file inode table with %d entries.\n",
1010                rn, cacheFiles);
1011         exit(1);
1012     }
1013     memset(inode_for_V, '\0', (cacheFiles * sizeof(AFSD_INO_T)));
1014     if (afsd_debug)
1015         printf("%s: %d inode_for_V entries at 0x%x, %d bytes\n",
1016                rn, cacheFiles, inode_for_V,
1017                (cacheFiles * sizeof(AFSD_INO_T)));
1018
1019     /*
1020      * Set up all the pathnames we'll need for later.
1021      */
1022     sprintf(fullpn_DCacheFile,  "%s/%s", cacheBaseDir, DCACHEFILE);
1023     sprintf(fullpn_VolInfoFile, "%s/%s", cacheBaseDir, VOLINFOFILE);
1024     sprintf(fullpn_VFile,       "%s/V",  cacheBaseDir);
1025     vFileNumber = fullpn_VFile + strlen(fullpn_VFile);
1026
1027     fputs(AFS_GOVERNMENT_MESSAGE, stdout); 
1028     fflush(stdout);
1029
1030     /*
1031      * Set up all the kernel processes needed for AFS.
1032      */
1033 #ifdef mac2
1034     setpgrp(getpid(), 0);
1035 #endif /* mac2 */
1036
1037     /* Initialize RX daemons and services */
1038
1039     /* initialize the rx random number generator from user space */
1040     {
1041       /* parse multihomed address files */
1042       afs_int32 addrbuf[MAXIPADDRS],maskbuf[MAXIPADDRS],mtubuf[MAXIPADDRS];
1043       char reason[1024];
1044       code=parseNetFiles(addrbuf,maskbuf,mtubuf,MAXIPADDRS,reason,
1045                     AFSDIR_CLIENT_NETINFO_FILEPATH,
1046                     AFSDIR_CLIENT_NETRESTRICT_FILEPATH);
1047       if(code>0) 
1048         call_syscall(AFSOP_ADVISEADDR, code, addrbuf, maskbuf, mtubuf);
1049       else 
1050         printf("ADVISEADDR: Error in specifying interface addresses:%s\n",reason);
1051     }
1052
1053     /* Set realtime priority for most threads to same as for biod's. */
1054     SET_AFSD_RTPRI();
1055
1056 #ifdef  AFS_SGI53_ENV
1057 #ifdef AFS_SGI61_ENV
1058     set_staticaddrs();
1059 #else /* AFS_SGI61_ENV */
1060     code = get_nfsstaticaddr();
1061     if (code)
1062         call_syscall(AFSOP_NFSSTATICADDR, code);
1063 #endif /* AFS_SGI61_ENV */
1064 #endif /* AFS_SGI_53_ENV */
1065
1066     /* Start listener, then callback listener. Lastly, start rx event daemon.
1067      * Change in ordering is so that Linux port has socket fd in listener
1068      * process.
1069      * preallocs are passed for both listener and callback server. Only
1070      * the one which actually does the initialization uses them though.
1071      */
1072     if (preallocs < cacheStatEntries+50)
1073         preallocs = cacheStatEntries+50;
1074 #ifdef RXK_LISTENER_ENV
1075     if (afsd_verbose)
1076         printf("%s: Forking rx listener daemon.\n", rn);
1077     code = fork();
1078     if (code == 0) {
1079         /* Child */
1080         SET_RX_RTPRI(); /* max advised for non-interrupts */
1081         call_syscall(AFSOP_RXLISTENER_DAEMON,
1082                      preallocs,
1083                      enable_peer_stats,
1084                      enable_process_stats);
1085         exit(1);
1086     }
1087 #endif
1088     if (afsd_verbose)
1089         printf("%s: Forking rx callback listener.\n", rn);
1090     code = fork();
1091     if (code == 0) {
1092         /* Child */
1093         call_syscall(AFSOP_START_RXCALLBACK, preallocs);
1094         exit(1);
1095     }
1096 #if defined(AFS_SUN5_ENV) || defined(RXK_LISTENER_ENV)
1097     if (afsd_verbose)
1098         printf("%s: Forking rxevent daemon.\n", rn);
1099     code = fork();
1100     if (code == 0) {
1101         /* Child */
1102         SET_RX_RTPRI(); /* max advised for non-interrupts */
1103         call_syscall(AFSOP_RXEVENT_DAEMON);
1104         exit(1);
1105     }
1106 #endif
1107
1108     /* Initialize AFS daemon threads. */
1109     if (afsd_verbose)
1110         printf("%s: Forking AFS daemon.\n", rn);
1111     code = fork();
1112     if (code == 0) {
1113         /* Child */
1114         call_syscall(AFSOP_START_AFS);
1115         exit(1);
1116     }
1117
1118     if (afsd_verbose)
1119         printf("%s: Forking Check Server Daemon.\n", rn);
1120     code = fork();
1121     if (code == 0) {
1122         /* Child */
1123         code = call_syscall(AFSOP_START_CS);
1124         if (code)
1125             printf("%s: No check server daemon in client.\n", rn);
1126         exit(1);
1127     }
1128
1129     if (afsd_verbose)
1130         printf("%s: Forking %d background daemons.\n", rn, nDaemons);
1131 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1132     /* Add one because for sgi we always "steal" the first daemon for a
1133      * different task if we only have a 4K stack.
1134      */
1135     nDaemons++;
1136 #endif
1137     for (i=0;i<nDaemons;i++) {
1138         code = fork();
1139         if (code == 0) {
1140             /* Child */
1141 #ifdef  AFS_AIX32_ENV
1142             call_syscall(AFSOP_START_BKG, 0);
1143 #else
1144             call_syscall(AFSOP_START_BKG);
1145 #endif
1146             exit(1);
1147         }
1148     }
1149 #ifdef  AFS_AIX32_ENV
1150     if (!sawBiod) 
1151         nBiods = nDaemons * 2;
1152     if (nBiods < 5)
1153         nBiods = 5;
1154     for (i=0; i< nBiods;i++) {
1155         code = fork();
1156         if (code == 0) {        /* Child */
1157             call_syscall(AFSOP_START_BKG, nBiods);
1158             exit(1);
1159         }
1160     }
1161 #endif
1162
1163     /*
1164      * Tell the kernel about each cell in the configuration.
1165      */
1166     lookingForHomeCell = 1;
1167
1168     afsconf_CellApply(cdir, ConfigCell, (char *) 0);
1169
1170     /*
1171      * If we're still looking for the home cell after the whole cell configuration database
1172      * has been parsed, there's something wrong.
1173      */
1174     if (lookingForHomeCell) {
1175         printf("%s: Can't find information for home cell '%s' in cell database!\n",
1176                rn, LclCellName);
1177     }
1178
1179     /*
1180          * If the root volume has been explicitly set, tell the kernel.
1181          */
1182     if (rootVolSet) {
1183         if (afsd_verbose)
1184             printf("%s: Calling AFSOP_ROOTVOLUME with '%s'\n",
1185               rn, rootVolume);
1186         call_syscall(AFSOP_ROOTVOLUME, rootVolume);
1187     }
1188
1189     /*
1190      * Tell the kernel some basic information about the workstation's cache.
1191      */
1192     if (afsd_verbose)
1193         printf("%s: Calling AFSOP_CACHEINIT: %d stat cache entries, %d optimum cache files, %d blocks in the cache, flags = 0x%x, dcache entries %d\n",
1194                rn, cacheStatEntries, cacheFiles, cacheBlocks, cacheFlags,
1195                dCacheSize);
1196     memset(&cparams, '\0', sizeof(cparams));
1197     cparams.cacheScaches = cacheStatEntries;
1198     cparams.cacheFiles = cacheFiles;
1199     cparams.cacheBlocks = cacheBlocks;
1200     cparams.cacheDcaches = dCacheSize;
1201     cparams.cacheVolumes = vCacheSize;
1202     cparams.chunkSize = chunkSize;
1203     cparams.setTimeFlag = cacheSetTime;
1204     cparams.memCacheFlag = cacheFlags;
1205 #ifdef notdef
1206     cparams.inodes       = inodes;
1207 #endif
1208     call_syscall(AFSOP_CACHEINIT, &cparams);
1209     if (afsd_CloseSynch) 
1210       call_syscall(AFSOP_CLOSEWAIT);
1211
1212     /*
1213      * Sweep the workstation AFS cache directory, remembering the inodes of
1214      * valid files and deleting extraneous files.  Keep sweeping until we
1215      * have the right number of data cache files or we've swept too many
1216      * times.
1217      */
1218     if (afsd_verbose)
1219         printf("%s: Sweeping workstation's AFS cache directory.\n",
1220                rn);
1221     cacheIteration = 0;
1222     /* Memory-cache based system doesn't need any of this */
1223     if(!(cacheFlags & AFSCALL_INIT_MEMCACHE)) {
1224         do {
1225             cacheIteration++;
1226             if (SweepAFSCache(&vFilesFound)) {
1227                 printf("%s: Error on sweep %d of workstation AFS cache \
1228                        directory.\n", rn, cacheIteration);
1229                 exit(1);
1230             }
1231             if (afsd_verbose)
1232                 printf("%s: %d out of %d data cache files found in sweep %d.\n",
1233                        rn, vFilesFound, cacheFiles, cacheIteration);
1234         } while ((vFilesFound < cacheFiles) &&
1235                  (cacheIteration < MAX_CACHE_LOOPS));
1236     } else if(afsd_verbose)
1237         printf("%s: Using memory cache, not swept\n", rn);
1238
1239     /*
1240      * Pass the kernel the name of the workstation cache file holding the 
1241      * dcache entries.
1242      */
1243     if (afsd_debug)
1244         printf("%s: Calling AFSOP_CACHEINFO: dcache file is '%s'\n",
1245                rn, fullpn_DCacheFile);
1246     /* once again, meaningless for a memory-based cache. */
1247     if(!(cacheFlags & AFSCALL_INIT_MEMCACHE))
1248         call_syscall(AFSOP_CACHEINFO, fullpn_DCacheFile);
1249
1250     /*
1251      * Pass the kernel the name of the workstation cache file holding the
1252      * volume information.
1253      */
1254     if (afsd_debug)
1255         printf("%s: Calling AFSOP_VOLUMEINFO: volume info file is '%s'\n",
1256                rn, fullpn_VolInfoFile);
1257     call_syscall(AFSOP_VOLUMEINFO,fullpn_VolInfoFile);
1258
1259     /*
1260      * Pass the kernel the name of the afs logging file holding the volume
1261      * information.
1262      */
1263     if (afsd_debug)
1264         printf("%s: Calling AFSOP_AFSLOG: volume info file is '%s'\n",
1265                rn, fullpn_AFSLogFile);
1266 #if defined(AFS_SGI_ENV)
1267     /* permit explicit -logfile argument to enable logging on memcache systems */
1268     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE) || as->parms[18].items)
1269 #else
1270     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE)) /* ... nor this ... */
1271 #endif
1272         call_syscall(AFSOP_AFSLOG,fullpn_AFSLogFile);
1273
1274     /*
1275      * Give the kernel the names of the AFS files cached on the workstation's
1276      * disk.
1277      */
1278     if (afsd_debug)
1279         printf("%s: Calling AFSOP_CACHEINODE for each of the %d files in '%s'\n",
1280                rn, cacheFiles, cacheBaseDir);
1281     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE)) /* ... and again ... */
1282         for (currVFile = 0; currVFile < cacheFiles; currVFile++) {
1283 #ifdef AFS_SGI62_ENV
1284             call_syscall(AFSOP_CACHEINODE,
1285                          (afs_uint32)(inode_for_V[currVFile]>>32),
1286                          (afs_uint32)(inode_for_V[currVFile] & 0xffffffff));
1287 #else
1288             call_syscall(AFSOP_CACHEINODE, inode_for_V[currVFile]);
1289 #endif
1290         } /*end for*/
1291
1292
1293     /*
1294      * All the necessary info has been passed into the kernel to run an AFS
1295      * system.  Give the kernel our go-ahead.
1296      */
1297     if (afsd_debug)
1298          printf("%s: Calling AFSOP_GO with cacheSetTime = %d\n",
1299                 rn, cacheSetTime);
1300      call_syscall(AFSOP_GO, cacheSetTime);
1301
1302     /*
1303      * At this point, we have finished passing the kernel all the info 
1304      * it needs to set up the AFS.  Mount the AFS root.
1305      */
1306     printf("%s: All AFS daemons started.\n", rn);
1307
1308     if (afsd_verbose)
1309         printf("%s: Forking trunc-cache daemon.\n", rn);
1310     code = fork();
1311     if (code == 0) {
1312         /* Child */
1313         call_syscall(AFSOP_START_TRUNCDAEMON);
1314         exit(1);
1315     }
1316
1317     mountFlags = 0;     /* Read/write file system, can do setuid() */
1318 #if     defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
1319 #ifdef  AFS_SUN5_ENV
1320     mountFlags |= MS_DATA;
1321 #else
1322     mountFlags |= M_NEWTYPE; /* This searches by name in vfs_conf.c so don't need to recompile vfs.c because MOUNT_MAXTYPE has changed; it seems that Sun fixed this at last... */
1323 #endif
1324 #endif
1325
1326 #if defined(AFS_HPUX100_ENV)
1327         mountFlags |= MS_DATA;
1328 #endif
1329
1330     if (afsd_verbose)
1331         printf("%s: Mounting the AFS root on '%s', flags: %d.\n",
1332                rn, cacheMountDir, mountFlags);
1333 #ifdef AFS_DEC_ENV
1334     if ((mount("AFS",cacheMountDir,mountFlags,GT_AFS,(caddr_t) 0)) < 0) {
1335 #else
1336 #ifdef  AFS_AUX_ENV
1337     if ((fsmount(MOUNT_AFS,cacheMountDir,mountFlags,(caddr_t) 0)) < 0)  {
1338 #else
1339 #ifdef  AFS_AIX_ENV
1340     if (aix_vmount()) {
1341 #else
1342 #if defined(AFS_HPUX100_ENV)
1343     if ((mount("",cacheMountDir,mountFlags,"afs", (char *)0, 0)) < 0) {
1344 #else
1345 #ifdef  AFS_HPUX_ENV
1346 #if     defined(AFS_HPUX90_ENV)
1347     { 
1348         char buffer[80];
1349         int code;
1350
1351         strcpy(buffer, "afs");
1352         code = vfsmount(-1,cacheMountDir,mountFlags,(caddr_t) buffer);
1353         sscanf(buffer, "%d", &vfs1_type);
1354         if (code < 0) {
1355             printf("Can't find 'afs' type in the registered filesystem table!\n");
1356             exit(1);
1357         }
1358         sscanf(buffer, "%d", &vfs1_type);
1359         if (afsd_verbose)
1360             printf("AFS vfs slot number is %d\n", vfs1_type);
1361     }
1362     if ((vfsmount(vfs1_type,cacheMountDir,mountFlags,(caddr_t) 0)) < 0) {
1363 #else
1364     if (call_syscall(AFSOP_AFS_VFSMOUNT, MOUNT_AFS, cacheMountDir,
1365                      mountFlags, (caddr_t)NULL) < 0) {
1366 #endif
1367 #else
1368 #ifdef  AFS_SUN5_ENV
1369     if ((mount("",cacheMountDir,mountFlags,"afs", (char *)0, 0)) < 0) {
1370 #else
1371 #if defined(AFS_SGI_ENV)
1372     mountFlags = MS_FSS;
1373
1374     if ((mount(MOUNT_AFS,cacheMountDir,mountFlags,(caddr_t) MOUNT_AFS)) < 0) {
1375 #else
1376 #ifdef AFS_LINUX20_ENV
1377     if ((mount("AFS", cacheMountDir, MOUNT_AFS, 0, NULL))<0) {
1378 #else
1379 /* This is the standard mount used by the suns and rts */
1380     if ((mount(MOUNT_AFS,cacheMountDir,mountFlags,(caddr_t) 0)) < 0) {
1381 #endif /* AFS_LINUX20_ENV */
1382 #endif /* AFS_SGI_ENV */
1383 #endif /* AFS_SUN5_ENV */
1384 #endif /* AFS_HPUX100_ENV */
1385 #endif /* AFS_HPUX_ENV */
1386 #endif /* AFS_AIX_ENV */
1387 #endif /* AFS_AUX_ENV */
1388 #endif /* AFS_DEC_ENV */
1389          printf("%s: Can't mount AFS on %s(%d)\n",
1390                    rn, cacheMountDir, errno);
1391          exit(1);
1392     }
1393
1394     HandleMTab();
1395
1396     if (afsd_rmtsys) {
1397         if (afsd_verbose)
1398             printf("%s: Forking 'rmtsys' daemon.\n", rn);
1399         code = fork();
1400         if (code == 0) {
1401             /* Child */
1402             rmtsysd();
1403             exit(1);
1404         }
1405     }
1406     /*
1407      * Exit successfully.
1408      */
1409     exit(0);
1410 }
1411
1412 #include "AFS_component_version_number.c"
1413
1414
1415
1416 main(argc, argv)
1417 int argc;
1418 char **argv; {
1419     register struct cmd_syndesc *ts;
1420
1421     ts = cmd_CreateSyntax((char *) 0, mainproc, (char *) 0, "start AFS");
1422     cmd_AddParm(ts, "-blocks", CMD_SINGLE, CMD_OPTIONAL, "1024 byte blocks in cache");
1423     cmd_AddParm(ts, "-files", CMD_SINGLE, CMD_OPTIONAL, "files in cache");
1424     cmd_AddParm(ts, "-rootvol", CMD_SINGLE, CMD_OPTIONAL, "name of AFS root volume");
1425     cmd_AddParm(ts, "-stat", CMD_SINGLE, CMD_OPTIONAL, "number of stat entries");
1426     cmd_AddParm(ts, "-memcache", CMD_FLAG, CMD_OPTIONAL, "run diskless");
1427     cmd_AddParm(ts, "-cachedir", CMD_SINGLE, CMD_OPTIONAL, "cache directory");
1428     cmd_AddParm(ts, "-mountdir", CMD_SINGLE, CMD_OPTIONAL, "mount location");
1429     cmd_AddParm(ts, "-daemons", CMD_SINGLE, CMD_OPTIONAL, "number of daemons to use");
1430     cmd_AddParm(ts, "-nosettime", CMD_FLAG, CMD_OPTIONAL, "don't set the time");
1431     cmd_AddParm(ts, "-verbose", CMD_FLAG, CMD_OPTIONAL, "display lots of information");
1432     cmd_AddParm(ts, "-rmtsys", CMD_FLAG, CMD_OPTIONAL, "start NFS rmtsysd program");
1433     cmd_AddParm(ts, "-debug", CMD_FLAG, CMD_OPTIONAL, "display debug info");
1434     cmd_AddParm(ts, "-chunksize", CMD_SINGLE, CMD_OPTIONAL, "log(2) of chunk size");
1435     cmd_AddParm(ts, "-dcache", CMD_SINGLE, CMD_OPTIONAL, "number of dcache entries");
1436     cmd_AddParm(ts, "-volumes", CMD_SINGLE, CMD_OPTIONAL, "number of volume entries");
1437     cmd_AddParm(ts, "-biods", CMD_SINGLE, CMD_OPTIONAL, "number of bkg I/O daemons (aix vm)");
1438
1439     cmd_AddParm(ts, "-prealloc", CMD_SINGLE, CMD_OPTIONAL, "number of 'small' preallocated blocks");
1440 #ifdef notdef
1441     cmd_AddParm(ts, "-pininodes", CMD_SINGLE, CMD_OPTIONAL, "number of inodes to hog"); 
1442 #endif
1443     cmd_AddParm(ts, "-confdir", CMD_SINGLE, CMD_OPTIONAL, "configuration directory");
1444     cmd_AddParm(ts, "-logfile", CMD_SINGLE, CMD_OPTIONAL, "Place to keep the CM log");
1445     cmd_AddParm(ts, "-waitclose", CMD_FLAG, CMD_OPTIONAL, "make close calls synchronous");
1446     cmd_AddParm(ts, "-shutdown", CMD_FLAG, CMD_OPTIONAL, "Shutdown all afs state");
1447     cmd_AddParm(ts, "-enable_peer_stats", CMD_FLAG, CMD_OPTIONAL|CMD_HIDE, "Collect rpc statistics by peer");
1448     cmd_AddParm(ts, "-enable_process_stats", CMD_FLAG, CMD_OPTIONAL|CMD_HIDE, "Collect rpc statistics for this process");
1449     cmd_AddParm(ts, "-mem_alloc_sleep", CMD_FLAG, (CMD_OPTIONAL | CMD_HIDE), "Allow sleeps when allocating memory cache");
1450     return (cmd_Dispatch(argc, argv));
1451 }
1452
1453
1454 #ifdef  AFS_HPUX_ENV
1455 #define MOUNTED_TABLE   MNT_MNTTAB
1456 #else
1457 #ifdef  AFS_SUN5_ENV
1458 #define MOUNTED_TABLE   MNTTAB
1459 #else
1460 #define MOUNTED_TABLE   MOUNTED
1461 #endif
1462 #endif
1463
1464 static int HandleMTab() {
1465 #if defined (AFS_SUN_ENV) || defined (AFS_HPUX_ENV) || defined(AFS_SUN5_ENV) || defined(AFS_SGI_ENV) || defined(AFS_LINUX20_ENV)
1466     FILE *tfilep;
1467 #ifdef  AFS_SUN5_ENV
1468     char tbuf[16];
1469     struct mnttab tmntent;
1470
1471     memset(&tmntent, '\0', sizeof(struct mnttab));
1472     if (!(tfilep = fopen(MOUNTED_TABLE, "a+"))) {
1473         printf("Can't open %s\n", MOUNTED_TABLE);
1474         perror(MNTTAB);
1475         exit(-1);
1476     }
1477     tmntent.mnt_special = "AFS";
1478     tmntent.mnt_mountp = cacheMountDir;
1479     tmntent.mnt_fstype = "xx";
1480     tmntent.mnt_mntopts = "rw";
1481     sprintf(tbuf, "%ld", (long)time((time_t *)0));
1482     tmntent.mnt_time = tbuf;
1483     putmntent(tfilep, &tmntent);
1484     fclose(tfilep);
1485 #else
1486 #if defined(AFS_SGI_ENV) || defined(AFS_LINUX20_ENV)
1487     struct mntent tmntent;
1488
1489     tfilep = setmntent("/etc/mtab", "a+");
1490     tmntent.mnt_fsname = "AFS";
1491     tmntent.mnt_dir = cacheMountDir;
1492     tmntent.mnt_type = "afs";
1493     tmntent.mnt_opts = "rw";
1494     tmntent.mnt_freq = 1;
1495     tmntent.mnt_passno = 3;
1496     addmntent(tfilep, &tmntent);
1497     endmntent(tfilep);
1498 #else
1499     struct mntent tmntent;
1500
1501     memset(&tmntent, '\0', sizeof(struct mntent));
1502     tfilep = setmntent(MOUNTED_TABLE, "a+");
1503     if (!tfilep) {
1504         printf("Can't open %s for write; Not adding afs entry to it\n",
1505                MOUNTED_TABLE);
1506         return 1;
1507     }
1508     tmntent.mnt_fsname = "AFS";
1509     tmntent.mnt_dir = cacheMountDir;
1510     tmntent.mnt_type = "xx";
1511     tmntent.mnt_opts = "rw";
1512     tmntent.mnt_freq = 1;
1513     tmntent.mnt_passno = 3;
1514 #ifdef  AFS_HPUX_ENV
1515     tmntent.mnt_time = time(0);
1516     tmntent.mnt_cnode = 0;
1517 #endif
1518     addmntent(tfilep, &tmntent);
1519     endmntent(tfilep);
1520 #endif  /* AFS_SGI_ENV */
1521 #endif  /* AFS_SUN5_ENV */
1522 #endif  /* unreasonable systems */
1523     return 0;
1524 }
1525
1526 #if !defined(AFS_SGI_ENV) && !defined(AFS_AIX32_ENV)
1527 call_syscall(param1, param2, param3, param4, param5, param6, param7)
1528 long param1, param2, param3, param4, param5, param6, param7;
1529 {
1530     int error;
1531
1532     error = syscall(AFS_SYSCALL, AFSCALL_CALL, param1, param2, param3, param4, param5, param6, param7);
1533     if (afsd_verbose) printf("SScall(%d, %d)=%d ", AFS_SYSCALL, AFSCALL_CALL, error);
1534     return (error);
1535 }
1536 #else   /* AFS_AIX32_ENV */
1537 #if defined(AFS_SGI_ENV)
1538 call_syscall(call, parm0, parm1, parm2, parm3, parm4)
1539 {
1540
1541         int error;
1542
1543         error = afs_syscall(call, parm0, parm1, parm2, parm3, parm4);
1544         if (afsd_verbose) printf("SScall(%d, %d)=%d ", call, parm0, error);
1545
1546         return error;
1547 }
1548 #else
1549 call_syscall(call, parm0, parm1, parm2, parm3, parm4, parm5, parm6) {
1550
1551     return syscall(AFSCALL_CALL, call, parm0, parm1, parm2, parm3, parm4, parm5, parm6);
1552 }
1553 #endif /* AFS_SGI_ENV */
1554 #endif /* AFS_AIX32_ENV */
1555
1556
1557 #ifdef  AFS_AIX_ENV
1558 /* Special handling for AIX's afs mount operation since they require much more miscl. information before making the vmount(2) syscall */
1559 #include <sys/vfs.h>
1560
1561 #define ROUNDUP(x)  (((x) + 3) & ~3)
1562
1563 aix_vmount() {
1564     struct vmount   *vmountp;
1565     int size, error;
1566
1567     size = sizeof(struct vmount) + ROUNDUP(strlen(cacheMountDir)+1) + 5*4;
1568     /* Malloc the vmount structure */
1569     if ((vmountp = (struct vmount *)malloc(size)) == (struct vmount *)NULL) {
1570          printf("Can't allocate space for the vmount structure (AIX)\n");
1571          exit(1);
1572     }
1573
1574     /* zero out the vmount structure */
1575     memset(vmountp, '\0', size);
1576  
1577     /* transfer info into the vmount structure */
1578     vmountp->vmt_revision = VMT_REVISION;
1579     vmountp->vmt_length = size;
1580     vmountp->vmt_fsid.fsid_dev = 0;
1581     vmountp->vmt_fsid.fsid_type = AFS_MOUNT_AFS;
1582     vmountp->vmt_vfsnumber = 0;
1583     vmountp->vmt_time = 0;/* We'll put the time soon! */
1584     vmountp->vmt_flags = VFS_DEVMOUNT;  /* read/write permission */
1585     vmountp->vmt_gfstype = AFS_MOUNT_AFS;
1586     vmountdata(vmountp, "AFS", cacheMountDir, "", "", "", "rw");
1587     
1588     /* Do the actual mount system call */
1589     error = vmount(vmountp, size);
1590     free(vmountp);
1591     return(error);
1592 }
1593
1594 vmountdata(vmtp, obj, stub, host, hostsname, info, args)
1595 struct vmount   *vmtp;
1596 char    *obj, *stub, *host, *hostsname, *info, *args;
1597 {
1598         register struct data {
1599                                 short   vmt_off;
1600                                 short   vmt_size;
1601                         } *vdp, *vdprev;
1602         register int    size;
1603
1604         vdp = (struct data *)vmtp->vmt_data;
1605         vdp->vmt_off = sizeof(struct vmount);
1606         size = ROUNDUP(strlen(obj) + 1);
1607         vdp->vmt_size = size;
1608         strcpy(vmt2dataptr(vmtp, VMT_OBJECT), obj);
1609
1610         vdprev = vdp;
1611         vdp++;
1612         vdp->vmt_off =  vdprev->vmt_off + size;
1613         size = ROUNDUP(strlen(stub) + 1);
1614         vdp->vmt_size = size;
1615         strcpy(vmt2dataptr(vmtp, VMT_STUB), stub);
1616
1617         vdprev = vdp;
1618         vdp++;
1619         vdp->vmt_off = vdprev->vmt_off + size;
1620         size = ROUNDUP(strlen(host) + 1);
1621         vdp->vmt_size = size;
1622         strcpy(vmt2dataptr(vmtp, VMT_HOST), host);
1623
1624         vdprev = vdp;
1625         vdp++;
1626         vdp->vmt_off = vdprev->vmt_off + size;
1627         size = ROUNDUP(strlen(hostsname) + 1);
1628         vdp->vmt_size = size;
1629         strcpy(vmt2dataptr(vmtp, VMT_HOSTNAME), hostsname);
1630
1631
1632         vdprev = vdp;
1633         vdp++;
1634         vdp->vmt_off =  vdprev->vmt_off + size;
1635         size = ROUNDUP(strlen(info) + 1);
1636         vdp->vmt_size = size;
1637         strcpy(vmt2dataptr(vmtp, VMT_INFO), info);
1638
1639         vdprev = vdp;
1640         vdp++;
1641         vdp->vmt_off =  vdprev->vmt_off + size;
1642         size = ROUNDUP(strlen(args) + 1);
1643         vdp->vmt_size = size;
1644         strcpy(vmt2dataptr(vmtp, VMT_ARGS), args);
1645 }
1646 #endif /* AFS_AIX_ENV */
1647
1648 #ifdef  AFS_SGI53_ENV
1649 #ifdef AFS_SGI61_ENV
1650 /* The dwarf structures are searched to find entry points of static functions
1651  * and the addresses of static variables. The file name as well as the
1652  * sybmol name is reaquired.
1653  */
1654
1655 /* Contains list of names to find in given file. */
1656 typedef struct {
1657     char *name;         /* Name of variable or function. */
1658     afs_hyper_t addr;   /* Address of function, undefined if not found. */
1659     Dwarf_Half type; /* DW_AT_location for vars, DW_AT_lowpc for func's */
1660     char found;         /* set if found. */
1661 } staticAddrList;
1662
1663 typedef struct  {
1664     char *file;                 /* Name of file containing vars or funcs */
1665     staticAddrList *addrList;   /* List of vars and/or funcs. */
1666     int nAddrs;                 /* # of addrList's */
1667     int found;                  /* set if we've found this file already. */
1668 } staticNameList;
1669
1670 /* routines used to find addresses in /unix */
1671 #if defined(AFS_SGI62_ENV) && !defined(AFS_SGI65_ENV)
1672 void findMDebugStaticAddresses(staticNameList *, int, int);
1673 #endif
1674 void findDwarfStaticAddresses(staticNameList *, int);
1675 void findElfAddresses(Dwarf_Debug, Dwarf_Die, staticNameList *);
1676 void getElfAddress(Dwarf_Debug, Dwarf_Die, staticAddrList *);
1677
1678 #if defined(AFS_SGI62_ENV) && !defined(AFS_SGI65_ENV)
1679 #define AFS_N_FILELISTS 2
1680 #define AFS_SYMS_NEEDED 3
1681 #else /* AFS_SGI62_ENV */
1682 #define AFS_N_FILELISTS 1
1683 #endif /* AFS_SGI62_ENV */
1684
1685
1686
1687 void set_staticaddrs(void)
1688 {
1689     staticNameList fileList[AFS_N_FILELISTS];
1690
1691     fileList[0].addrList = (staticAddrList*)calloc(1, sizeof(staticAddrList));
1692     if (!fileList[0].addrList) {
1693         printf("set_staticaddrs: Can't calloc fileList[0].addrList\n");
1694         return;
1695     }
1696     fileList[0].file = "nfs_server.c";
1697     fileList[0].found = 0;
1698     fileList[0].nAddrs = 1;
1699     fileList[0].addrList[0].name = "rfsdisptab_v2";
1700     fileList[0].addrList[0].type = DW_AT_location;
1701     fileList[0].addrList[0].found = 0;
1702
1703 #if defined(AFS_SGI62_ENV) && !defined(AFS_SGI65_ENV)
1704     fileList[1].addrList = (staticAddrList*)calloc(2, sizeof(staticAddrList));
1705     if (!fileList[1].addrList) {
1706         printf("set_staticaddrs: Can't malloc fileList[1].addrList\n");
1707         return;
1708     }
1709     fileList[1].file = "uipc_socket.c";
1710     fileList[1].found = 0;
1711     fileList[1].nAddrs = 2;
1712     fileList[1].addrList[0].name = "sblock";
1713     fileList[1].addrList[0].type = DW_AT_low_pc;
1714     fileList[1].addrList[0].found = 0;
1715     fileList[1].addrList[1].name = "sbunlock";
1716     fileList[1].addrList[1].type = DW_AT_low_pc;
1717     fileList[1].addrList[1].found = 0;
1718
1719     if (64 != sysconf(_SC_KERN_POINTERS))
1720         findMDebugStaticAddresses(fileList, AFS_N_FILELISTS, AFS_SYMS_NEEDED);
1721     else
1722 #endif /* AFS_SGI62_ENV */
1723         findDwarfStaticAddresses(fileList, AFS_N_FILELISTS);
1724
1725     if (fileList[0].addrList[0].found) {
1726         call_syscall(AFSOP_NFSSTATICADDR2, fileList[0].addrList[0].addr.high,
1727                      fileList[0].addrList[0].addr.low);
1728     }
1729     else {
1730         if (afsd_verbose)
1731             printf("NFS V2 is not present in the kernel.\n");
1732     }
1733     free(fileList[0].addrList);
1734 #if defined(AFS_SGI62_ENV) && !defined(AFS_SGI65_ENV)
1735     if (fileList[1].addrList[0].found && fileList[1].addrList[1].found) {
1736         call_syscall(AFSOP_SBLOCKSTATICADDR2,
1737                      fileList[1].addrList[0].addr.high,
1738                      fileList[1].addrList[0].addr.low,
1739                      fileList[1].addrList[1].addr.high,
1740                      fileList[1].addrList[1].addr.low);
1741     }
1742     else {
1743         if (!fileList[1].addrList[0].found)
1744             printf("Can't find %s in kernel. Exiting.\n",
1745                    fileList[1].addrList[0].name);
1746         if (!fileList[1].addrList[0].found)
1747             printf("Can't find %s in kernel. Exiting.\n",
1748                    fileList[1].addrList[1].name);
1749         exit(1);
1750     }
1751     free(fileList[1].addrList);
1752 #endif /* AFS_SGI62_ENV */
1753 }
1754
1755
1756 /* Find addresses for static variables and functions. */
1757 void
1758 findDwarfStaticAddresses(staticNameList * nameList, int nLists)
1759 {
1760     int fd;
1761     int i;
1762     int found = 0;
1763     int code;
1764     char *s;
1765     char *hname = (char*)0;
1766     Dwarf_Unsigned dwarf_access = O_RDONLY;
1767     Dwarf_Debug dwarf_debug;
1768     Dwarf_Error dwarf_error;
1769     Dwarf_Unsigned dwarf_cu_header_length;
1770     Dwarf_Unsigned dwarf_abbrev_offset;
1771     Dwarf_Half dwarf_address_size;
1772     Dwarf_Unsigned next_cu_header;
1773     Dwarf_Die dwarf_die;
1774     Dwarf_Die dwarf_next_die;
1775     Dwarf_Die dwarf_child_die;
1776
1777     if (elf_version(EV_CURRENT) == EV_NONE) {
1778         printf("findDwarfStaticAddresses: Bad elf version.\n");
1779         return;
1780     }
1781
1782     if ((fd=open("/unix", O_RDONLY,0))<0) {
1783         printf("findDwarfStaticAddresses: Failed to open /unix.\n");
1784         return;
1785     }
1786     code = dwarf_init(fd, dwarf_access, NULL, NULL, &dwarf_debug,
1787                       &dwarf_error);
1788     if (code != DW_DLV_OK) {
1789         /* Nope hope for the elves and dwarves, try intermediate code. */
1790         close(fd);
1791         return;
1792     }
1793
1794     found = 0;
1795     while (1) {
1796         /* Run through the headers until we find ones for files we've
1797          * specified in nameList.
1798          */
1799         code = dwarf_next_cu_header(dwarf_debug,
1800                                     &dwarf_cu_header_length, NULL,
1801                                     &dwarf_abbrev_offset,
1802                                     &dwarf_address_size,
1803                                     &next_cu_header,
1804                                     &dwarf_error);
1805         if (code == DW_DLV_NO_ENTRY) {
1806             break;
1807         }
1808         else if (code == DW_DLV_ERROR) {
1809             printf("findDwarfStaticAddresses: Error reading headers: %s\n",
1810                    dwarf_errmsg(dwarf_error));
1811             break;
1812         }
1813
1814         code = dwarf_siblingof(dwarf_debug, NULL, &dwarf_die, &dwarf_error);
1815         if (code != DW_DLV_OK) {
1816             printf("findDwarfStaticAddresses: Can't get first die. %s\n",
1817                    (code == DW_DLV_ERROR) ? dwarf_errmsg(dwarf_error) : "");
1818             break;
1819         }
1820
1821         /* This is the header, test the name. */
1822         code = dwarf_diename(dwarf_die, &hname, &dwarf_error);
1823         if (code == DW_DLV_OK) {
1824             s = strrchr(hname, '/');
1825             for (i=0; i<nLists; i++) {
1826                 if (s && !strcmp(s+1, nameList[i].file)) {
1827                     findElfAddresses(dwarf_debug, dwarf_die, &nameList[i]);
1828                     found ++;
1829                     break;
1830                 }
1831             }
1832         }
1833         else {
1834             printf("findDwarfStaticAddresses: Can't get name of current header. %s\n",
1835                    (code == DW_DLV_ERROR) ? dwarf_errmsg(dwarf_error) : "");
1836             break;
1837         }
1838         dwarf_dealloc(dwarf_debug, hname, DW_DLA_STRING);
1839         hname = (char*)0;
1840         if (found >= nLists) { /* we're done */
1841             break;
1842         }
1843     }
1844
1845      /* Frees up all allocated space. */
1846     (void) dwarf_finish(dwarf_debug, &dwarf_error);
1847     close(fd);
1848 }
1849
1850 void
1851 findElfAddresses(Dwarf_Debug dwarf_debug, Dwarf_Die dwarf_die,
1852                  staticNameList * nameList)
1853 {
1854     int i;
1855     Dwarf_Error dwarf_error;
1856     Dwarf_Die dwarf_next_die;
1857     Dwarf_Die dwarf_child_die;
1858     Dwarf_Attribute dwarf_return_attr;
1859     char *vname = (char*)0;
1860     int found = 0;
1861     int code;
1862     
1863     /* Drop into this die to find names in addrList. */
1864     code = dwarf_child(dwarf_die, &dwarf_child_die, &dwarf_error);
1865     if (code != DW_DLV_OK) {
1866         printf("findElfAddresses: Can't get child die. %s\n",
1867                (code == DW_DLV_ERROR) ? dwarf_errmsg(dwarf_error) : "");
1868         return;
1869     }
1870
1871     /* Try to find names in each sibling. */
1872     dwarf_next_die = (Dwarf_Die)0;
1873     do {
1874         code = dwarf_diename(dwarf_child_die, &vname,
1875                              &dwarf_error);
1876         /* It's possible that some siblings don't have names. */
1877         if (code == DW_DLV_OK) {
1878             for (i=0; i<nameList->nAddrs; i++) {
1879                 if (!nameList->addrList[i].found) {
1880                     if (!strcmp(vname, nameList->addrList[i].name)) {
1881                         getElfAddress(dwarf_debug, dwarf_child_die,
1882                                           &(nameList->addrList[i]));
1883                         found ++;
1884                         break;
1885                     }
1886                 }
1887             }
1888         }
1889         if (dwarf_next_die)
1890             dwarf_dealloc(dwarf_debug, dwarf_next_die, DW_DLA_DIE);
1891
1892         if (found >= nameList->nAddrs) { /* we're done. */
1893             break;
1894         }
1895
1896         dwarf_next_die = dwarf_child_die;
1897         code = dwarf_siblingof(dwarf_debug, dwarf_next_die,
1898                                &dwarf_child_die,
1899                                &dwarf_error);
1900      
1901     } while(code == DW_DLV_OK);
1902 }
1903
1904 /* Get address out of current die. */
1905 void
1906 getElfAddress(Dwarf_Debug dwarf_debug,
1907               Dwarf_Die dwarf_child_die, staticAddrList *addrList)
1908 {
1909     int i;
1910     Dwarf_Error dwarf_error;
1911     Dwarf_Attribute dwarf_return_attr;
1912     Dwarf_Bool dwarf_return_bool;
1913     Dwarf_Locdesc *llbuf = NULL;
1914     Dwarf_Signed listlen;
1915     off64_t addr = (off64_t)0;
1916     int code;
1917
1918     code = dwarf_hasattr(dwarf_child_die, addrList->type,
1919                          &dwarf_return_bool, &dwarf_error);
1920     if ((code !=  DW_DLV_OK) || (!dwarf_return_bool)) {
1921         printf("getElfAddress: no address given for %s. %s\n",
1922                addrList->name, (code == DW_DLV_ERROR) ? dwarf_errmsg(dwarf_error) : "");
1923         return;
1924     }
1925     code = dwarf_attr(dwarf_child_die, addrList->type,
1926                       &dwarf_return_attr,  &dwarf_error);
1927     if (code !=  DW_DLV_OK) {
1928         printf("getElfAddress: Can't get attribute. %s\n",
1929                (code == DW_DLV_ERROR) ? dwarf_errmsg(dwarf_error) : "");
1930         return;
1931     }
1932
1933     switch (addrList->type) {
1934     case DW_AT_location:
1935         code = dwarf_loclist(dwarf_return_attr, &llbuf,
1936                              &listlen, &dwarf_error);
1937         if (code !=   DW_DLV_OK) {
1938             printf("getElfAddress: Can't get location for %s. %s\n",
1939                    addrList->name,
1940                    (code == DW_DLV_ERROR) ? dwarf_errmsg(dwarf_error) : "");
1941             return;
1942         }
1943         if ((listlen != 1) || (llbuf[0].ld_cents != 1)) {
1944             printf("getElfAddress: %s has more than one address.\n",
1945                    addrList->name);
1946             return;
1947         }
1948         addr = llbuf[0].ld_s[0].lr_number;
1949         break;
1950
1951     case DW_AT_low_pc:
1952         code = dwarf_lowpc(dwarf_child_die, (Dwarf_Addr*)&addr, &dwarf_error);
1953         if ( code !=  DW_DLV_OK) {
1954             printf("getElfAddress: Can't get lowpc for %s. %s\n",
1955                    addrList->name,
1956                    (code == DW_DLV_ERROR) ? dwarf_errmsg(dwarf_error) : "");
1957             return;
1958         }
1959         break;
1960         
1961     default:
1962         printf("getElfAddress: Bad case %d in switch.\n", addrList->type);
1963         return;
1964     }
1965
1966     addrList->addr.high = (addr>>32) & 0xffffffff;
1967     addrList->addr.low  = addr & 0xffffffff;
1968     addrList->found = 1;
1969 }
1970
1971 #if defined(AFS_SGI62_ENV) && !defined(AFS_SGI65_ENV)
1972 /* Find symbols in the .mdebug section for 32 bit kernels. */
1973 /*
1974  * do_mdebug()
1975  * On 32bit platforms, we're still using the ucode compilers to build
1976  * the kernel, so we need to get our static text/data from the .mdebug
1977  * section instead of the .dwarf sections.
1978  */
1979 /* SearchNameList searches our bizarre structs for the given string.
1980  * If found, sets the found bit and the address and returns 1.
1981  * Not found returns 0.
1982  */
1983 int SearchNameList(char *name, afs_uint32 addr, staticNameList *nameList,
1984                    int nLists)
1985 {
1986     int i, j;                   
1987     for (i=0; i<nLists; i++) {
1988         for (j=0; j<nameList[i].nAddrs; j++) {
1989             if (nameList[i].addrList[j].found)
1990                 continue;
1991             if (!strcmp(name, nameList[i].addrList[j].name)) {
1992                 nameList[i].addrList[j].addr.high = 0;
1993                 nameList[i].addrList[j].addr.low = addr;
1994                 nameList[i].addrList[j].found = 1;
1995                 return 1;
1996             }
1997         }
1998     }
1999     return 0;
2000 }
2001                                         
2002 static void
2003 SearchMDebug(Elf_Scn *scnp, Elf32_Shdr *shdrp, staticNameList * nameList,
2004              int nLists, int needed)
2005 {
2006     long *buf = (long *)(elf_getdata(scnp, NULL)->d_buf); 
2007     u_long addr, mdoff = shdrp->sh_offset;
2008     HDRR *hdrp;
2009     SYMR *symbase, *symp, *symend;
2010     FDR *fdrbase, *fdrp;
2011     int i, j;
2012     char *strbase, *str;
2013     int ifd;
2014     int nFound = 0;
2015     
2016     /* get header */
2017     addr = (__psunsigned_t)buf;
2018     hdrp = (HDRR *)addr;
2019     
2020     /* setup base addresses */
2021     addr = (u_long)buf + (u_long)(hdrp->cbFdOffset - mdoff);
2022     fdrbase = (FDR *)addr;
2023     addr = (u_long)buf + (u_long)(hdrp->cbSymOffset - mdoff);
2024     symbase = (SYMR *)addr;
2025     addr = (u_long)buf + (u_long)(hdrp->cbSsOffset - mdoff);
2026     strbase = (char *)addr;
2027     
2028 #define KEEPER(a,b)     ((a == stStaticProc && b == scText) || \
2029                          (a == stStatic && (b == scData || b == scBss || \
2030                                             b == scSBss || b == scSData)))
2031         
2032     for (fdrp = fdrbase; fdrp < &fdrbase[hdrp->ifdMax]; fdrp++) {
2033         str = strbase + fdrp->issBase + fdrp->rss;
2034         
2035         /* local symbols for each fd */
2036         for (symp = &symbase[fdrp->isymBase];
2037              symp < &symbase[fdrp->isymBase+fdrp->csym];
2038              symp++) {
2039             if (KEEPER(symp->st, symp->sc)) {
2040                 if (symp->value == 0)
2041                     continue;
2042                 
2043                 str = strbase + fdrp->issBase + symp->iss;
2044                 /* Look for AFS symbols of interest */
2045                 if (SearchNameList(str, symp->value,
2046                                    nameList, nLists)) {
2047                     nFound ++;
2048                     if (nFound >= needed)
2049                         return;
2050                 }
2051             }
2052         }
2053     }
2054 }
2055     
2056 /*
2057  * returns section with the name of scn_name, & puts its header in shdr64 or
2058  * shdr32 based on elf's file type
2059  *
2060  */
2061 Elf_Scn *
2062 findMDebugSection(Elf *elf, char *scn_name)
2063 {
2064         Elf64_Ehdr *ehdr64;
2065         Elf32_Ehdr *ehdr32;
2066         Elf_Scn *scn = NULL;
2067         Elf64_Shdr *shdr64;
2068         Elf32_Shdr *shdr32;
2069
2070         if ((ehdr32 = elf32_getehdr(elf)) == NULL)
2071                 return(NULL);
2072         do {
2073                 if ((scn = elf_nextscn(elf, scn)) == NULL)
2074                         break;
2075                 if ((shdr32 = elf32_getshdr(scn)) == NULL)
2076                         return(NULL);
2077         } while (strcmp(scn_name, elf_strptr(elf, ehdr32->e_shstrndx,
2078                                                   shdr32->sh_name)));
2079
2080         return(scn);    
2081 }
2082
2083
2084 void findMDebugStaticAddresses(staticNameList * nameList, int nLists,
2085                                int needed)
2086 {
2087     int fd;
2088     Elf *elf;
2089     Elf_Scn *mdebug_scn;
2090     Elf32_Shdr *mdebug_shdr;
2091     char *names;
2092
2093     if ((fd = open("/unix", O_RDONLY)) == -1) {
2094         printf("findMDebugStaticAddresses: Failed to open /unix.\n");
2095         return;
2096     }
2097
2098     (void)elf_version(EV_CURRENT);
2099     if((elf = elf_begin(fd, ELF_C_READ, NULL)) == NULL) {
2100         printf("findMDebugStaticAddresses: /unix doesn't seem to be an elf file\n");
2101         close(fd);
2102         return;
2103     }
2104     mdebug_scn = findMDebugSection(elf, ".mdebug");
2105     if (!mdebug_scn) {
2106         printf("findMDebugStaticAddresses: Can't find .mdebug section.\n");
2107         goto find_end;
2108     }
2109     mdebug_shdr = elf32_getshdr(mdebug_scn);
2110     if (!mdebug_shdr) {
2111         printf("findMDebugStaticAddresses: Can't find .mdebug header.\n");
2112         goto find_end;
2113     }
2114
2115     (void) SearchMDebug(mdebug_scn, mdebug_shdr, nameList, nLists, needed);
2116
2117  find_end:
2118     elf_end(elf);
2119     close(fd);
2120 }
2121 #endif /* AFS_SGI62_ENV */
2122
2123 #else /* AFS_SGI61_ENV */
2124 #include <nlist.h>
2125 struct  nlist nlunix[] = {
2126    { "rfsdisptab_v2" },
2127    { 0 },
2128 };
2129
2130 get_nfsstaticaddr() {
2131     int i, j, kmem, count;
2132
2133     if ((kmem = open("/dev/kmem", O_RDONLY)) < 0) {
2134         printf("Warning: can't open /dev/kmem\n");
2135         return 0;
2136     }
2137     if ((j = nlist("/unix", nlunix)) < 0) {
2138         printf("Warning: can't nlist /unix\n");
2139         return 0;
2140     }
2141     i = nlunix[0].n_value;
2142     if (lseek(kmem, i, L_SET/*0*/) != i) {
2143         printf("Warning: can't lseek to %x\n", i);      
2144         return 0;
2145     }
2146     if ((j = read(kmem, &count, sizeof count)) != sizeof count) {
2147         printf("WARNING: kmem read at %x failed\n", i);
2148         return 0;
2149     }
2150     return i;
2151 }
2152 #endif /* AFS_SGI61_ENV */
2153 #endif /* AFS_SGI53_ENV */