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