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