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