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