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