Initial OpenBSD support. Most of user space builds. No kernel module yet.
[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         code = afsconf_GetAfsdbInfo(acellName, 0, &acellInfo);
1071         if (code) {
1072             kernelMsg[0] = 0;
1073             kernelMsg[1] = 0;
1074         } else {
1075             kernelMsg[0] = acellInfo.numServers;
1076             if (acellInfo.timeout)
1077                 kernelMsg[1] = acellInfo.timeout - time(0);
1078             else
1079                 kernelMsg[1] = 0;
1080             for (i=0; i<acellInfo.numServers; i++)
1081                 kernelMsg[i+2] = acellInfo.hostAddr[i].sin_addr.s_addr;
1082         }    
1083     }
1084 }
1085 #endif
1086
1087 #ifdef mac2
1088 #include <sys/ioctl.h>
1089 #endif /* mac2 */
1090
1091 #ifdef AFS_SGI65_ENV
1092 #define SET_RTPRI(P) {  \
1093     struct sched_param sp; \
1094     sp.sched_priority = P; \
1095     if (sched_setscheduler(0, SCHED_RR, &sp)<0) { \
1096         perror("sched_setscheduler"); \
1097     } \
1098 }
1099 #define SET_AFSD_RTPRI() SET_RTPRI(68)
1100 #define SET_RX_RTPRI()   SET_RTPRI(199)
1101 #else
1102 #ifdef AFS_LINUX20_ENV
1103 #define SET_AFSD_RTPRI()
1104 #define SET_RX_RTPRI()  do { if (setpriority(PRIO_PROCESS, 0, -10)<0) \
1105                            perror("setting rx priority"); \
1106                          } while (0)
1107 #else
1108 #define SET_AFSD_RTPRI() 
1109 #define SET_RX_RTPRI()   
1110 #endif
1111 #endif
1112
1113 mainproc(as, arock)
1114   register struct cmd_syndesc *as;
1115   char *arock;
1116 {
1117     static char rn[] = "afsd";      /*Name of this routine*/
1118     register afs_int32 code;                /*Result of fork()*/
1119     register int i;
1120     int currVFile;                  /*Current AFS cache file number passed in*/
1121     int mountFlags;                 /*Flags passed to mount()*/
1122     int lookupResult;               /*Result of GetLocalCellName()*/
1123     int cacheIteration;             /*How many times through cache verification*/
1124     int vFilesFound;                /*How many data cache files were found in sweep*/
1125     struct afsconf_dir *cdir;       /* config dir */
1126     FILE *logfd;
1127 #ifdef  AFS_SUN5_ENV
1128     struct stat st;
1129 #endif
1130     afs_int32 vfs1_type = -1;
1131 #ifdef AFS_SGI65_ENV
1132     struct sched_param sp;
1133 #endif
1134
1135 #ifdef AFS_SGI_VNODE_GLUE
1136     if (afs_init_kernel_config(-1) <0) {
1137         printf("Can't determine NUMA configuration, not starting AFS.\n");
1138         exit(1);
1139     }
1140 #endif
1141
1142     /* call atoi on the appropriate parsed results */
1143     if (as->parms[0].items) {
1144         /* -blocks */
1145         cacheBlocks = atoi(as->parms[0].items->data);
1146         sawCacheBlocks = 1;
1147     }
1148     if (as->parms[1].items) {
1149         /* -files */
1150         cacheFiles = atoi(as->parms[1].items->data);
1151         filesSet = 1;   /* set when spec'd on cmd line */
1152     }
1153     if (as->parms[2].items) {
1154         /* -rootvol */
1155         strcpy(rootVolume, as->parms[2].items->data);
1156         rootVolSet = 1;
1157     }
1158     if (as->parms[3].items) {
1159         /* -stat */
1160         cacheStatEntries = atoi(as->parms[3].items->data);
1161     }
1162     if (as->parms[4].items) {
1163         /* -memcache */
1164         cacheBaseDir[0] = '\0';
1165         sawCacheBaseDir = 1;
1166         cacheFlags |= AFSCALL_INIT_MEMCACHE;
1167         if (chunkSize == 0)
1168             chunkSize = 13;
1169     }
1170     if (as->parms[5].items) {
1171         /* -cachedir */
1172         strcpy(cacheBaseDir, as->parms[5].items->data);
1173         sawCacheBaseDir = 1;
1174     }
1175     if (as->parms[6].items) {
1176         /* -mountdir */
1177         strcpy(cacheMountDir, as->parms[6].items->data);
1178         sawCacheMountDir = 1;
1179     }
1180     if (as->parms[7].items) {
1181         /* -daemons */
1182         nDaemons = atoi(as->parms[7].items->data);
1183     }
1184     if (as->parms[8].items) {
1185         /* -nosettime */
1186         cacheSetTime = FALSE;
1187     }
1188     if (as->parms[9].items) {
1189         /* -verbose */
1190         afsd_verbose = 1;
1191     }
1192     if (as->parms[10].items) {
1193         /* -rmtsys */
1194         afsd_rmtsys = 1;
1195     }
1196     if (as->parms[11].items) {
1197         /* -debug */
1198         afsd_debug = 1;
1199         afsd_verbose = 1;
1200     }
1201     if (as->parms[12].items) {
1202         /* -chunksize */
1203         chunkSize = atoi(as->parms[12].items->data);
1204         if (chunkSize < 0 || chunkSize > 30) {
1205             printf("afsd:invalid chunk size spec'd, using default\n");
1206             chunkSize = 0;
1207         }
1208     }
1209     if (as->parms[13].items) {
1210         /* -dcache */
1211         dCacheSize = atoi(as->parms[13].items->data);
1212         sawDCacheSize = 1;
1213     }
1214     if (as->parms[14].items) {
1215         /* -volumes */
1216         vCacheSize = atoi(as->parms[14].items->data);
1217     }
1218     if (as->parms[15].items) {
1219         /* -biods */
1220 #ifndef AFS_AIX32_ENV
1221         printf("afsd: [-biods] currently only enabled for aix3.x VM supported systems\n");
1222 #else
1223         nBiods = atoi(as->parms[15].items->data);
1224         sawBiod = 1;
1225 #endif
1226     }
1227     if (as->parms[16].items) {
1228         /* -prealloc */
1229         preallocs = atoi(as->parms[16].items->data);
1230     }
1231 #ifdef notdef 
1232     if (as->parms[17].items) {
1233         /* -pininodes */
1234         inodes = atoi(as->parms[17].items->data);
1235     }
1236 #endif
1237     strcpy(confDir, AFSDIR_CLIENT_ETC_DIRPATH);
1238     if (as->parms[17].items) {
1239         /* -confdir */
1240         strcpy(confDir, as->parms[17].items->data);
1241     }
1242     sprintf(fullpn_CacheInfo,  "%s/%s", confDir, CACHEINFOFILE);
1243     sprintf(fullpn_AFSLogFile,  "%s/%s", confDir, AFSLOGFILE);
1244     if (as->parms[18].items) {
1245         /* -logfile */
1246         strcpy(fullpn_AFSLogFile, as->parms[18].items->data);
1247     }
1248     if (as->parms[19].items) {
1249       /* -waitclose */
1250       afsd_CloseSynch = 1;
1251     }
1252     if (as->parms[20].items) {
1253         /* -shutdown */
1254         afs_shutdown = 1;
1255         /* 
1256          * Cold shutdown is the default
1257          */
1258         printf("afsd: Shutting down all afs processes and afs state\n");
1259         call_syscall(AFSOP_SHUTDOWN, 1);
1260         exit(0);
1261     }
1262     if (as->parms[21].items) {
1263         /* -enable_peer_stats */
1264         enable_peer_stats = 1;
1265     }
1266     if (as->parms[22].items) {
1267         /* -enable_process_stats */
1268         enable_process_stats = 1;
1269     }
1270     if (as->parms[23].items) {
1271         /* -mem_alloc_sleep */
1272         cacheFlags |= AFSCALL_INIT_MEMCACHE_SLEEP;
1273     }
1274     if (as->parms[24].items) {
1275         /* -afsdb */
1276 #ifdef AFS_AFSDB_ENV
1277         enable_afsdb = 1;
1278 #else
1279         printf("afsd: No AFSDB support; ignoring -afsdb");
1280 #endif
1281     }
1282     if (as->parms[25].items) {
1283         /* -files_per_subdir */
1284         int res = atoi(as->parms[25].items->data);
1285         if ( res < 10 || res > 2^30) {
1286             printf("afsd:invalid number of files per subdir, \"%s\". Ignored\n", as->parms[25].items->data);
1287         } else {
1288             nFilesPerDir = res;
1289         }
1290     }
1291
1292     /*
1293      * Pull out all the configuration info for the workstation's AFS cache and
1294      * the cellular community we're willing to let our users see.
1295      */
1296     cdir = afsconf_Open(confDir);
1297     if (!cdir) {
1298         printf("afsd: some file missing or bad in %s\n", confDir);
1299         exit(1);
1300     }
1301
1302     lookupResult = afsconf_GetLocalCell(cdir, LclCellName, sizeof(LclCellName));
1303     if (lookupResult) {
1304         printf("%s: Can't get my home cell name!  [Error is %d]\n",
1305                rn, lookupResult);
1306     }
1307     else {
1308         if (afsd_verbose)
1309             printf("%s: My home cell is '%s'\n",
1310                    rn, LclCellName);
1311     }
1312
1313     /* parse cacheinfo file if this is a diskcache */
1314     if (ParseCacheInfoFile()) {
1315         exit(1);
1316     }
1317
1318     if ((logfd = fopen(fullpn_AFSLogFile,"r+")) == 0) {
1319         if (afsd_verbose)  printf("%s: Creating '%s'\n",  rn, fullpn_AFSLogFile);
1320         if (CreateCacheFile(fullpn_AFSLogFile, NULL)) {
1321             printf("%s: Can't create '%s' (You may want to use the -logfile option)\n",  rn, fullpn_AFSLogFile);
1322             exit(1);
1323         }
1324     } else
1325         fclose(logfd);
1326
1327     /* do some random computations in memcache case to get things to work
1328      * reasonably no matter which parameters you set.
1329      */
1330     if (cacheFlags & AFSCALL_INIT_MEMCACHE) {
1331         /* memory cache: size described either as blocks or dcache entries, but
1332          * not both.
1333          */
1334         if (sawDCacheSize) {
1335             if (sawCacheBlocks) {
1336                 printf("%s: can't set cache blocks and dcache size simultaneously when diskless.\n", rn);
1337                 exit(1);
1338             }
1339             /* compute the cache size based on # of chunks times the chunk size */
1340             i = (chunkSize == 0? 13 : chunkSize);
1341             i = (1<<i); /* bytes per chunk */
1342             cacheBlocks = i * dCacheSize;
1343             sawCacheBlocks = 1; /* so that ParseCacheInfoFile doesn't overwrite */
1344         }
1345         else {
1346             /* compute the dcache size from overall cache size and chunk size */
1347             i = (chunkSize == 0? 13 : chunkSize);
1348             /* dCacheSize = (cacheBlocks << 10) / (1<<i); */
1349             if (i > 10) {
1350                 dCacheSize = (cacheBlocks >> (i-10));
1351             } else if (i < 10) {
1352                 dCacheSize = (cacheBlocks << (10-i));
1353             } else {
1354                 dCacheSize = cacheBlocks;
1355             }
1356             /* don't have to set sawDCacheSize here since it isn't overwritten
1357              * by ParseCacheInfoFile.
1358              */
1359         }
1360         /* kernel computes # of dcache entries as min of cacheFiles and dCacheSize,
1361          * so we now make them equal.
1362          */
1363         cacheFiles = dCacheSize;
1364     }
1365     else {
1366         /* Disk cache:
1367          * Compute the number of cache files based on cache size,
1368          * but only if -files isn't given on the command line.
1369          * Don't let # files be so small as to prevent full utilization 
1370          * of the cache unless user has explicitly asked for it.
1371          * average V-file is ~10K, according to tentative empirical studies.
1372          */
1373         if (!filesSet) {
1374             cacheFiles = cacheBlocks / 10;       
1375             if (cacheFiles <  100) cacheFiles =  100;
1376             /* Always allow more files than chunks.  Presume average V-file 
1377              * is ~67% of a chunk...  (another guess, perhaps Honeyman will
1378              * have a grad student write a paper).  i is KILOBYTES.
1379              */
1380             i = 1 << (chunkSize == 0? 6 : (chunkSize<10 ? 0 : chunkSize -10));
1381             cacheFiles = max(cacheFiles, 1.5 * (cacheBlocks / i));
1382             /* never permit more files than blocks, while leaving space for
1383              * VolumeInfo and CacheItems files.  VolumeInfo is usually 20K,
1384              * CacheItems is 50 Bytes / file (== 1K/20)
1385              */
1386 #define VOLINFOSZ 20
1387 #define CACHEITMSZ (cacheFiles / 20)
1388 #ifdef AFS_AIX_ENV
1389             cacheFiles= min(cacheFiles,(cacheBlocks -VOLINFOSZ -CACHEITMSZ)/4);
1390 #else
1391             cacheFiles = min(cacheFiles, cacheBlocks - VOLINFOSZ - CACHEITMSZ);
1392 #endif
1393             if (cacheFiles <  100) 
1394               fprintf (stderr, "%s: WARNING: cache probably too small!\n", rn);
1395         }
1396         if (!sawDCacheSize) {
1397             if ((cacheFiles / 2) > dCacheSize)
1398                 dCacheSize = cacheFiles / 2;
1399             if (dCacheSize > 2000)
1400                 dCacheSize = 2000;
1401         }
1402     }
1403
1404     /*
1405      * Create and zero the inode table for the desired cache files.
1406      */
1407     inode_for_V = (AFSD_INO_T *) malloc(cacheFiles * sizeof(AFSD_INO_T));
1408     if (inode_for_V == (AFSD_INO_T *)0) {
1409         printf("%s: malloc() failed for cache file inode table with %d entries.\n",
1410                rn, cacheFiles);
1411         exit(1);
1412     }
1413     memset(inode_for_V, '\0', (cacheFiles * sizeof(AFSD_INO_T)));
1414     if (afsd_debug)
1415         printf("%s: %d inode_for_V entries at 0x%x, %d bytes\n",
1416                rn, cacheFiles, inode_for_V,
1417                (cacheFiles * sizeof(AFSD_INO_T)));
1418
1419     /*
1420      * Set up all the pathnames we'll need for later.
1421      */
1422     sprintf(fullpn_DCacheFile,  "%s/%s", cacheBaseDir, DCACHEFILE);
1423     sprintf(fullpn_VolInfoFile, "%s/%s", cacheBaseDir, VOLINFOFILE);
1424     sprintf(fullpn_VFile,       "%s/",  cacheBaseDir);
1425     vFilePtr = fullpn_VFile + strlen(fullpn_VFile);
1426
1427 #if 0
1428     fputs(AFS_GOVERNMENT_MESSAGE, stdout); 
1429     fflush(stdout);
1430 #endif
1431
1432     /*
1433      * Set up all the kernel processes needed for AFS.
1434      */
1435 #ifdef mac2
1436     setpgrp(getpid(), 0);
1437 #endif /* mac2 */
1438
1439     /* Initialize RX daemons and services */
1440
1441     /* initialize the rx random number generator from user space */
1442     {
1443       /* parse multihomed address files */
1444       afs_int32 addrbuf[MAXIPADDRS],maskbuf[MAXIPADDRS],mtubuf[MAXIPADDRS];
1445       char reason[1024];
1446       code=parseNetFiles(addrbuf,maskbuf,mtubuf,MAXIPADDRS,reason,
1447                     AFSDIR_CLIENT_NETINFO_FILEPATH,
1448                     AFSDIR_CLIENT_NETRESTRICT_FILEPATH);
1449       if(code>0) 
1450         call_syscall(AFSOP_ADVISEADDR, code, addrbuf, maskbuf, mtubuf);
1451       else 
1452         printf("ADVISEADDR: Error in specifying interface addresses:%s\n",reason);
1453     }
1454
1455     /* Set realtime priority for most threads to same as for biod's. */
1456     SET_AFSD_RTPRI();
1457
1458 #ifdef  AFS_SGI53_ENV
1459 #ifdef AFS_SGI61_ENV
1460     set_staticaddrs();
1461 #else /* AFS_SGI61_ENV */
1462     code = get_nfsstaticaddr();
1463     if (code)
1464         call_syscall(AFSOP_NFSSTATICADDR, code);
1465 #endif /* AFS_SGI61_ENV */
1466 #endif /* AFS_SGI_53_ENV */
1467
1468     /* Start listener, then callback listener. Lastly, start rx event daemon.
1469      * Change in ordering is so that Linux port has socket fd in listener
1470      * process.
1471      * preallocs are passed for both listener and callback server. Only
1472      * the one which actually does the initialization uses them though.
1473      */
1474     if (preallocs < cacheStatEntries+50)
1475         preallocs = cacheStatEntries+50;
1476 #ifdef RXK_LISTENER_ENV
1477     if (afsd_verbose)
1478         printf("%s: Forking rx listener daemon.\n", rn);
1479     code = fork();
1480     if (code == 0) {
1481         /* Child */
1482         SET_RX_RTPRI(); /* max advised for non-interrupts */
1483         call_syscall(AFSOP_RXLISTENER_DAEMON,
1484                      preallocs,
1485                      enable_peer_stats,
1486                      enable_process_stats);
1487         exit(1);
1488     }
1489 #endif
1490     if (afsd_verbose)
1491         printf("%s: Forking rx callback listener.\n", rn);
1492     code = fork();
1493     if (code == 0) {
1494         /* Child */
1495         call_syscall(AFSOP_START_RXCALLBACK, preallocs);
1496         exit(1);
1497     }
1498 #if defined(AFS_SUN5_ENV) || defined(RXK_LISTENER_ENV)
1499     if (afsd_verbose)
1500         printf("%s: Forking rxevent daemon.\n", rn);
1501     code = fork();
1502     if (code == 0) {
1503         /* Child */
1504         SET_RX_RTPRI(); /* max advised for non-interrupts */
1505         call_syscall(AFSOP_RXEVENT_DAEMON);
1506         exit(1);
1507     }
1508 #endif
1509
1510 #ifdef AFS_AFSDB_ENV
1511     if (enable_afsdb) {
1512         if (afsd_verbose)
1513             printf("%s: Forking AFSDB lookup handler.\n", rn);
1514         code = fork();
1515         if (code == 0) {
1516             AfsdbLookupHandler();
1517             exit(1);
1518         }
1519     }
1520 #endif
1521
1522     /* Initialize AFS daemon threads. */
1523     if (afsd_verbose)
1524         printf("%s: Forking AFS daemon.\n", rn);
1525     code = fork();
1526     if (code == 0) {
1527         /* Child */
1528         call_syscall(AFSOP_START_AFS);
1529         exit(1);
1530     }
1531
1532     if (afsd_verbose)
1533         printf("%s: Forking Check Server Daemon.\n", rn);
1534     code = fork();
1535     if (code == 0) {
1536         /* Child */
1537         code = call_syscall(AFSOP_START_CS);
1538         if (code)
1539             printf("%s: No check server daemon in client.\n", rn);
1540         exit(1);
1541     }
1542
1543     if (afsd_verbose)
1544         printf("%s: Forking %d background daemons.\n", rn, nDaemons);
1545 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1546     /* Add one because for sgi we always "steal" the first daemon for a
1547      * different task if we only have a 4K stack.
1548      */
1549     nDaemons++;
1550 #endif
1551     for (i=0;i<nDaemons;i++) {
1552         code = fork();
1553         if (code == 0) {
1554             /* Child */
1555 #ifdef  AFS_AIX32_ENV
1556             call_syscall(AFSOP_START_BKG, 0);
1557 #else
1558             call_syscall(AFSOP_START_BKG);
1559 #endif
1560             exit(1);
1561         }
1562     }
1563 #ifdef  AFS_AIX32_ENV
1564     if (!sawBiod) 
1565         nBiods = nDaemons * 2;
1566     if (nBiods < 5)
1567         nBiods = 5;
1568     for (i=0; i< nBiods;i++) {
1569         code = fork();
1570         if (code == 0) {        /* Child */
1571             call_syscall(AFSOP_START_BKG, nBiods);
1572             exit(1);
1573         }
1574     }
1575 #endif
1576
1577     /*
1578      * Tell the kernel about each cell in the configuration.
1579      */
1580     lookingForHomeCell = 1;
1581
1582     afsconf_CellApply(cdir, ConfigCell, (char *) 0);
1583
1584     /*
1585      * If we're still looking for the home cell after the whole cell configuration database
1586      * has been parsed, there's something wrong.
1587      */
1588     if (lookingForHomeCell) {
1589         printf("%s: Can't find information for home cell '%s' in cell database!\n",
1590                rn, LclCellName);
1591     }
1592
1593     /*
1594      * If the root volume has been explicitly set, tell the kernel.
1595      */
1596     if (rootVolSet) {
1597         if (afsd_verbose)
1598             printf("%s: Calling AFSOP_ROOTVOLUME with '%s'\n",
1599               rn, rootVolume);
1600         call_syscall(AFSOP_ROOTVOLUME, rootVolume);
1601     }
1602
1603     /*
1604      * Tell the kernel some basic information about the workstation's cache.
1605      */
1606     if (afsd_verbose)
1607         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",
1608                rn, cacheStatEntries, cacheFiles, cacheBlocks, cacheFlags,
1609                dCacheSize);
1610     memset(&cparams, '\0', sizeof(cparams));
1611     cparams.cacheScaches = cacheStatEntries;
1612     cparams.cacheFiles = cacheFiles;
1613     cparams.cacheBlocks = cacheBlocks;
1614     cparams.cacheDcaches = dCacheSize;
1615     cparams.cacheVolumes = vCacheSize;
1616     cparams.chunkSize = chunkSize;
1617     cparams.setTimeFlag = cacheSetTime;
1618     cparams.memCacheFlag = cacheFlags;
1619 #ifdef notdef
1620     cparams.inodes       = inodes;
1621 #endif
1622     call_syscall(AFSOP_CACHEINIT, &cparams);
1623     if (afsd_CloseSynch) 
1624       call_syscall(AFSOP_CLOSEWAIT);
1625
1626     /*
1627      * Sweep the workstation AFS cache directory, remembering the inodes of
1628      * valid files and deleting extraneous files.  Keep sweeping until we
1629      * have the right number of data cache files or we've swept too many
1630      * times.
1631      */
1632     if (afsd_verbose)
1633         printf("%s: Sweeping workstation's AFS cache directory.\n",
1634                rn);
1635     cacheIteration = 0;
1636     /* Memory-cache based system doesn't need any of this */
1637     if(!(cacheFlags & AFSCALL_INIT_MEMCACHE)) {
1638         do {
1639             cacheIteration++;
1640             if (SweepAFSCache(&vFilesFound)) {
1641                 printf("%s: Error on sweep %d of workstation AFS cache \
1642                        directory.\n", rn, cacheIteration);
1643                 exit(1);
1644             }
1645             if (afsd_verbose)
1646                 printf("%s: %d out of %d data cache files found in sweep %d.\n",
1647                        rn, vFilesFound, cacheFiles, cacheIteration);
1648         } while ((vFilesFound < cacheFiles) &&
1649                  (cacheIteration < MAX_CACHE_LOOPS));
1650     } else if(afsd_verbose)
1651         printf("%s: Using memory cache, not swept\n", rn);
1652
1653     /*
1654      * Pass the kernel the name of the workstation cache file holding the 
1655      * dcache entries.
1656      */
1657     if (afsd_debug)
1658         printf("%s: Calling AFSOP_CACHEINFO: dcache file is '%s'\n",
1659                rn, fullpn_DCacheFile);
1660     /* once again, meaningless for a memory-based cache. */
1661     if(!(cacheFlags & AFSCALL_INIT_MEMCACHE))
1662         call_syscall(AFSOP_CACHEINFO, fullpn_DCacheFile);
1663
1664     /*
1665      * Pass the kernel the name of the workstation cache file holding the
1666      * volume information.
1667      */
1668     if (afsd_debug)
1669         printf("%s: Calling AFSOP_VOLUMEINFO: volume info file is '%s'\n",
1670                rn, fullpn_VolInfoFile);
1671     call_syscall(AFSOP_VOLUMEINFO,fullpn_VolInfoFile);
1672
1673     /*
1674      * Pass the kernel the name of the afs logging file holding the volume
1675      * information.
1676      */
1677     if (afsd_debug)
1678         printf("%s: Calling AFSOP_AFSLOG: volume info file is '%s'\n",
1679                rn, fullpn_AFSLogFile);
1680 #if defined(AFS_SGI_ENV)
1681     /* permit explicit -logfile argument to enable logging on memcache systems */
1682     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE) || as->parms[18].items)
1683 #else
1684     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE)) /* ... nor this ... */
1685 #endif
1686         call_syscall(AFSOP_AFSLOG,fullpn_AFSLogFile);
1687
1688     /*
1689      * Give the kernel the names of the AFS files cached on the workstation's
1690      * disk.
1691      */
1692     if (afsd_debug)
1693         printf("%s: Calling AFSOP_CACHEINODE for each of the %d files in '%s'\n",
1694                rn, cacheFiles, cacheBaseDir);
1695     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE)) /* ... and again ... */
1696         for (currVFile = 0; currVFile < cacheFiles; currVFile++) {
1697 #ifdef AFS_SGI62_ENV
1698             call_syscall(AFSOP_CACHEINODE,
1699                          (afs_uint32)(inode_for_V[currVFile]>>32),
1700                          (afs_uint32)(inode_for_V[currVFile] & 0xffffffff));
1701 #else
1702             call_syscall(AFSOP_CACHEINODE, inode_for_V[currVFile]);
1703 #endif
1704         } /*end for*/
1705
1706
1707     /*
1708      * All the necessary info has been passed into the kernel to run an AFS
1709      * system.  Give the kernel our go-ahead.
1710      */
1711     if (afsd_debug)
1712          printf("%s: Calling AFSOP_GO with cacheSetTime = %d\n",
1713                 rn, cacheSetTime);
1714      call_syscall(AFSOP_GO, cacheSetTime);
1715
1716     /*
1717      * At this point, we have finished passing the kernel all the info 
1718      * it needs to set up the AFS.  Mount the AFS root.
1719      */
1720     printf("%s: All AFS daemons started.\n", rn);
1721
1722     if (afsd_verbose)
1723         printf("%s: Forking trunc-cache daemon.\n", rn);
1724     code = fork();
1725     if (code == 0) {
1726         /* Child */
1727         call_syscall(AFSOP_START_TRUNCDAEMON);
1728         exit(1);
1729     }
1730
1731     mountFlags = 0;     /* Read/write file system, can do setuid() */
1732 #if     defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
1733 #ifdef  AFS_SUN5_ENV
1734     mountFlags |= MS_DATA;
1735 #else
1736     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... */
1737 #endif
1738 #endif
1739
1740 #if defined(AFS_HPUX100_ENV)
1741         mountFlags |= MS_DATA;
1742 #endif
1743
1744     if (afsd_verbose)
1745         printf("%s: Mounting the AFS root on '%s', flags: %d.\n",
1746                rn, cacheMountDir, mountFlags);
1747 #ifdef AFS_DEC_ENV
1748     if ((mount("AFS",cacheMountDir,mountFlags,GT_AFS,(caddr_t) 0)) < 0) {
1749 #else
1750 #ifdef AFS_FBSD_ENV
1751     if ((mount("AFS",cacheMountDir,mountFlags,(caddr_t) 0)) < 0) {
1752 #else
1753 #ifdef  AFS_AUX_ENV
1754     if ((fsmount(MOUNT_AFS,cacheMountDir,mountFlags,(caddr_t) 0)) < 0)  {
1755 #else
1756 #ifdef  AFS_AIX_ENV
1757     if (aix_vmount()) {
1758 #else
1759 #if defined(AFS_HPUX100_ENV)
1760     if ((mount("",cacheMountDir,mountFlags,"afs", (char *)0, 0)) < 0) {
1761 #else
1762 #ifdef  AFS_HPUX_ENV
1763 #if     defined(AFS_HPUX90_ENV)
1764     { 
1765         char buffer[80];
1766         int code;
1767
1768         strcpy(buffer, "afs");
1769         code = vfsmount(-1,cacheMountDir,mountFlags,(caddr_t) buffer);
1770         sscanf(buffer, "%d", &vfs1_type);
1771         if (code < 0) {
1772             printf("Can't find 'afs' type in the registered filesystem table!\n");
1773             exit(1);
1774         }
1775         sscanf(buffer, "%d", &vfs1_type);
1776         if (afsd_verbose)
1777             printf("AFS vfs slot number is %d\n", vfs1_type);
1778     }
1779     if ((vfsmount(vfs1_type,cacheMountDir,mountFlags,(caddr_t) 0)) < 0) {
1780 #else
1781     if (call_syscall(AFSOP_AFS_VFSMOUNT, MOUNT_AFS, cacheMountDir,
1782                      mountFlags, (caddr_t)NULL) < 0) {
1783 #endif
1784 #else
1785 #ifdef  AFS_SUN5_ENV
1786     if ((mount("AFS",cacheMountDir,mountFlags,"afs", (char *)0, 0)) < 0) {
1787 #else
1788 #if defined(AFS_SGI_ENV)
1789     mountFlags = MS_FSS;
1790     if ((mount(MOUNT_AFS,cacheMountDir,mountFlags,(caddr_t) MOUNT_AFS)) < 0) {
1791 #else
1792 #ifdef AFS_LINUX20_ENV
1793     if ((mount("AFS", cacheMountDir, MOUNT_AFS, 0, NULL))<0) {
1794 #else
1795 /* This is the standard mount used by the suns and rts */
1796     if ((mount(MOUNT_AFS,cacheMountDir,mountFlags,(caddr_t) 0)) < 0) {
1797 #endif /* AFS_LINUX20_ENV */
1798 #endif /* AFS_SGI_ENV */
1799 #endif /* AFS_SUN5_ENV */
1800 #endif /* AFS_HPUX100_ENV */
1801 #endif /* AFS_HPUX_ENV */
1802 #endif /* AFS_AIX_ENV */
1803 #endif /* AFS_AUX_ENV */
1804 #endif /* AFS_FBSD_ENV */
1805 #endif /* AFS_DEC_ENV */
1806          printf("%s: Can't mount AFS on %s(%d)\n",
1807                    rn, cacheMountDir, errno);
1808          exit(1);
1809     }
1810
1811     HandleMTab();
1812
1813     if (afsd_rmtsys) {
1814         if (afsd_verbose)
1815             printf("%s: Forking 'rmtsys' daemon.\n", rn);
1816         code = fork();
1817         if (code == 0) {
1818             /* Child */
1819             rmtsysd();
1820             exit(1);
1821         }
1822     }
1823     /*
1824      * Exit successfully.
1825      */
1826     exit(0);
1827 }
1828
1829 #include "AFS_component_version_number.c"
1830
1831
1832
1833 main(argc, argv)
1834 int argc;
1835 char **argv; {
1836     register struct cmd_syndesc *ts;
1837
1838     ts = cmd_CreateSyntax((char *) 0, mainproc, (char *) 0, "start AFS");
1839     cmd_AddParm(ts, "-blocks", CMD_SINGLE, CMD_OPTIONAL, "1024 byte blocks in cache");
1840     cmd_AddParm(ts, "-files", CMD_SINGLE, CMD_OPTIONAL, "files in cache");
1841     cmd_AddParm(ts, "-rootvol", CMD_SINGLE, CMD_OPTIONAL, "name of AFS root volume");
1842     cmd_AddParm(ts, "-stat", CMD_SINGLE, CMD_OPTIONAL, "number of stat entries");
1843     cmd_AddParm(ts, "-memcache", CMD_FLAG, CMD_OPTIONAL, "run diskless");
1844     cmd_AddParm(ts, "-cachedir", CMD_SINGLE, CMD_OPTIONAL, "cache directory");
1845     cmd_AddParm(ts, "-mountdir", CMD_SINGLE, CMD_OPTIONAL, "mount location");
1846     cmd_AddParm(ts, "-daemons", CMD_SINGLE, CMD_OPTIONAL, "number of daemons to use");
1847     cmd_AddParm(ts, "-nosettime", CMD_FLAG, CMD_OPTIONAL, "don't set the time");
1848     cmd_AddParm(ts, "-verbose", CMD_FLAG, CMD_OPTIONAL, "display lots of information");
1849     cmd_AddParm(ts, "-rmtsys", CMD_FLAG, CMD_OPTIONAL, "start NFS rmtsysd program");
1850     cmd_AddParm(ts, "-debug", CMD_FLAG, CMD_OPTIONAL, "display debug info");
1851     cmd_AddParm(ts, "-chunksize", CMD_SINGLE, CMD_OPTIONAL, "log(2) of chunk size");
1852     cmd_AddParm(ts, "-dcache", CMD_SINGLE, CMD_OPTIONAL, "number of dcache entries");
1853     cmd_AddParm(ts, "-volumes", CMD_SINGLE, CMD_OPTIONAL, "number of volume entries");
1854     cmd_AddParm(ts, "-biods", CMD_SINGLE, CMD_OPTIONAL, "number of bkg I/O daemons (aix vm)");
1855
1856     cmd_AddParm(ts, "-prealloc", CMD_SINGLE, CMD_OPTIONAL, "number of 'small' preallocated blocks");
1857 #ifdef notdef
1858     cmd_AddParm(ts, "-pininodes", CMD_SINGLE, CMD_OPTIONAL, "number of inodes to hog"); 
1859 #endif
1860     cmd_AddParm(ts, "-confdir", CMD_SINGLE, CMD_OPTIONAL, "configuration directory");
1861     cmd_AddParm(ts, "-logfile", CMD_SINGLE, CMD_OPTIONAL, "Place to keep the CM log");
1862     cmd_AddParm(ts, "-waitclose", CMD_FLAG, CMD_OPTIONAL, "make close calls synchronous");
1863     cmd_AddParm(ts, "-shutdown", CMD_FLAG, CMD_OPTIONAL, "Shutdown all afs state");
1864     cmd_AddParm(ts, "-enable_peer_stats", CMD_FLAG, CMD_OPTIONAL|CMD_HIDE, "Collect rpc statistics by peer");
1865     cmd_AddParm(ts, "-enable_process_stats", CMD_FLAG, CMD_OPTIONAL|CMD_HIDE, "Collect rpc statistics for this process");
1866     cmd_AddParm(ts, "-mem_alloc_sleep", CMD_FLAG, (CMD_OPTIONAL | CMD_HIDE), "Allow sleeps when allocating memory cache");
1867     cmd_AddParm(ts, "-afsdb", CMD_FLAG, (CMD_OPTIONAL
1868 #ifndef AFS_AFSDB_ENV
1869                 | CMD_HIDE
1870 #endif
1871                 ), "Enable AFSDB support");
1872     cmd_AddParm(ts, "-files_per_subdir", CMD_SINGLE, CMD_OPTIONAL, "log(2) of the number of cache files per cache subdirectory");
1873     return (cmd_Dispatch(argc, argv));
1874 }
1875
1876
1877 #ifdef  AFS_HPUX_ENV
1878 #define MOUNTED_TABLE   MNT_MNTTAB
1879 #else
1880 #ifdef  AFS_SUN5_ENV
1881 #define MOUNTED_TABLE   MNTTAB
1882 #else
1883 #define MOUNTED_TABLE   MOUNTED
1884 #endif
1885 #endif
1886
1887 static int HandleMTab() {
1888 #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)
1889     FILE *tfilep;
1890 #ifdef  AFS_SUN5_ENV
1891     char tbuf[16];
1892     struct mnttab tmntent;
1893
1894     memset(&tmntent, '\0', sizeof(struct mnttab));
1895     if (!(tfilep = fopen(MOUNTED_TABLE, "a+"))) {
1896         printf("Can't open %s\n", MOUNTED_TABLE);
1897         perror(MNTTAB);
1898         exit(-1);
1899     }
1900     tmntent.mnt_special = "AFS";
1901     tmntent.mnt_mountp = cacheMountDir;
1902     tmntent.mnt_fstype = "xx";
1903     tmntent.mnt_mntopts = "rw";
1904     sprintf(tbuf, "%ld", (long)time((time_t *)0));
1905     tmntent.mnt_time = tbuf;
1906     putmntent(tfilep, &tmntent);
1907     fclose(tfilep);
1908 #else
1909 #if defined(AFS_SGI_ENV) || defined(AFS_LINUX20_ENV)
1910     struct mntent tmntent;
1911
1912     tfilep = setmntent("/etc/mtab", "a+");
1913     tmntent.mnt_fsname = "AFS";
1914     tmntent.mnt_dir = cacheMountDir;
1915     tmntent.mnt_type = "afs";
1916     tmntent.mnt_opts = "rw";
1917     tmntent.mnt_freq = 1;
1918     tmntent.mnt_passno = 3;
1919     addmntent(tfilep, &tmntent);
1920     endmntent(tfilep);
1921 #else
1922     struct mntent tmntent;
1923
1924     memset(&tmntent, '\0', sizeof(struct mntent));
1925     tfilep = setmntent(MOUNTED_TABLE, "a+");
1926     if (!tfilep) {
1927         printf("Can't open %s for write; Not adding afs entry to it\n",
1928                MOUNTED_TABLE);
1929         return 1;
1930     }
1931     tmntent.mnt_fsname = "AFS";
1932     tmntent.mnt_dir = cacheMountDir;
1933     tmntent.mnt_type = "xx";
1934     tmntent.mnt_opts = "rw";
1935     tmntent.mnt_freq = 1;
1936     tmntent.mnt_passno = 3;
1937 #ifdef  AFS_HPUX_ENV
1938     tmntent.mnt_time = time(0);
1939     tmntent.mnt_cnode = 0;
1940 #endif
1941     addmntent(tfilep, &tmntent);
1942     endmntent(tfilep);
1943 #endif  /* AFS_SGI_ENV */
1944 #endif  /* AFS_SUN5_ENV */
1945 #endif  /* unreasonable systems */
1946     return 0;
1947 }
1948
1949 #if !defined(AFS_SGI_ENV) && !defined(AFS_AIX32_ENV)
1950 call_syscall(param1, param2, param3, param4, param5, param6, param7)
1951 long param1, param2, param3, param4, param5, param6, param7;
1952 {
1953     int error;
1954
1955     error = syscall(AFS_SYSCALL, AFSCALL_CALL, param1, param2, param3, param4, param5, param6, param7);
1956     if (afsd_verbose) printf("SScall(%d, %d)=%d ", AFS_SYSCALL, AFSCALL_CALL, error);
1957     return (error);
1958 }
1959 #else   /* AFS_AIX32_ENV */
1960 #if defined(AFS_SGI_ENV)
1961 call_syscall(call, parm0, parm1, parm2, parm3, parm4)
1962 {
1963
1964         int error;
1965
1966         error = afs_syscall(call, parm0, parm1, parm2, parm3, parm4);
1967         if (afsd_verbose) printf("SScall(%d, %d)=%d ", call, parm0, error);
1968
1969         return error;
1970 }
1971 #else
1972 call_syscall(call, parm0, parm1, parm2, parm3, parm4, parm5, parm6) {
1973
1974     return syscall(AFSCALL_CALL, call, parm0, parm1, parm2, parm3, parm4, parm5, parm6);
1975 }
1976 #endif /* AFS_SGI_ENV */
1977 #endif /* AFS_AIX32_ENV */
1978
1979
1980 #ifdef  AFS_AIX_ENV
1981 /* Special handling for AIX's afs mount operation since they require much more miscl. information before making the vmount(2) syscall */
1982 #include <sys/vfs.h>
1983
1984 #define ROUNDUP(x)  (((x) + 3) & ~3)
1985
1986 aix_vmount() {
1987     struct vmount   *vmountp;
1988     int size, error;
1989
1990     size = sizeof(struct vmount) + ROUNDUP(strlen(cacheMountDir)+1) + 5*4;
1991     /* Malloc the vmount structure */
1992     if ((vmountp = (struct vmount *)malloc(size)) == (struct vmount *)NULL) {
1993          printf("Can't allocate space for the vmount structure (AIX)\n");
1994          exit(1);
1995     }
1996
1997     /* zero out the vmount structure */
1998     memset(vmountp, '\0', size);
1999  
2000     /* transfer info into the vmount structure */
2001     vmountp->vmt_revision = VMT_REVISION;
2002     vmountp->vmt_length = size;
2003     vmountp->vmt_fsid.fsid_dev = 0;
2004     vmountp->vmt_fsid.fsid_type = AFS_MOUNT_AFS;
2005     vmountp->vmt_vfsnumber = 0;
2006     vmountp->vmt_time = 0;/* We'll put the time soon! */
2007     vmountp->vmt_flags = VFS_DEVMOUNT;  /* read/write permission */
2008     vmountp->vmt_gfstype = AFS_MOUNT_AFS;
2009     vmountdata(vmountp, "AFS", cacheMountDir, "", "", "", "rw");
2010     
2011     /* Do the actual mount system call */
2012     error = vmount(vmountp, size);
2013     free(vmountp);
2014     return(error);
2015 }
2016
2017 vmountdata(vmtp, obj, stub, host, hostsname, info, args)
2018 struct vmount   *vmtp;
2019 char    *obj, *stub, *host, *hostsname, *info, *args;
2020 {
2021         register struct data {
2022                                 short   vmt_off;
2023                                 short   vmt_size;
2024                         } *vdp, *vdprev;
2025         register int    size;
2026
2027         vdp = (struct data *)vmtp->vmt_data;
2028         vdp->vmt_off = sizeof(struct vmount);
2029         size = ROUNDUP(strlen(obj) + 1);
2030         vdp->vmt_size = size;
2031         strcpy(vmt2dataptr(vmtp, VMT_OBJECT), obj);
2032
2033         vdprev = vdp;
2034         vdp++;
2035         vdp->vmt_off =  vdprev->vmt_off + size;
2036         size = ROUNDUP(strlen(stub) + 1);
2037         vdp->vmt_size = size;
2038         strcpy(vmt2dataptr(vmtp, VMT_STUB), stub);
2039
2040         vdprev = vdp;
2041         vdp++;
2042         vdp->vmt_off = vdprev->vmt_off + size;
2043         size = ROUNDUP(strlen(host) + 1);
2044         vdp->vmt_size = size;
2045         strcpy(vmt2dataptr(vmtp, VMT_HOST), host);
2046
2047         vdprev = vdp;
2048         vdp++;
2049         vdp->vmt_off = vdprev->vmt_off + size;
2050         size = ROUNDUP(strlen(hostsname) + 1);
2051         vdp->vmt_size = size;
2052         strcpy(vmt2dataptr(vmtp, VMT_HOSTNAME), hostsname);
2053
2054
2055         vdprev = vdp;
2056         vdp++;
2057         vdp->vmt_off =  vdprev->vmt_off + size;
2058         size = ROUNDUP(strlen(info) + 1);
2059         vdp->vmt_size = size;
2060         strcpy(vmt2dataptr(vmtp, VMT_INFO), info);
2061
2062         vdprev = vdp;
2063         vdp++;
2064         vdp->vmt_off =  vdprev->vmt_off + size;
2065         size = ROUNDUP(strlen(args) + 1);
2066         vdp->vmt_size = size;
2067         strcpy(vmt2dataptr(vmtp, VMT_ARGS), args);
2068 }
2069 #endif /* AFS_AIX_ENV */
2070
2071 #ifdef  AFS_SGI53_ENV
2072 #ifdef AFS_SGI61_ENV
2073 /* The dwarf structures are searched to find entry points of static functions
2074  * and the addresses of static variables. The file name as well as the
2075  * sybmol name is reaquired.
2076  */
2077
2078 /* Contains list of names to find in given file. */
2079 typedef struct {
2080     char *name;         /* Name of variable or function. */
2081     afs_hyper_t addr;   /* Address of function, undefined if not found. */
2082     Dwarf_Half type; /* DW_AT_location for vars, DW_AT_lowpc for func's */
2083     char found;         /* set if found. */
2084 } staticAddrList;
2085
2086 typedef struct  {
2087     char *file;                 /* Name of file containing vars or funcs */
2088     staticAddrList *addrList;   /* List of vars and/or funcs. */
2089     int nAddrs;                 /* # of addrList's */
2090     int found;                  /* set if we've found this file already. */
2091 } staticNameList;
2092
2093 /* routines used to find addresses in /unix */
2094 #if defined(AFS_SGI62_ENV) && !defined(AFS_SGI65_ENV)
2095 void findMDebugStaticAddresses(staticNameList *, int, int);
2096 #endif
2097 void findDwarfStaticAddresses(staticNameList *, int);
2098 void findElfAddresses(Dwarf_Debug, Dwarf_Die, staticNameList *);
2099 void getElfAddress(Dwarf_Debug, Dwarf_Die, staticAddrList *);
2100
2101 #if defined(AFS_SGI62_ENV) && !defined(AFS_SGI65_ENV)
2102 #define AFS_N_FILELISTS 2
2103 #define AFS_SYMS_NEEDED 3
2104 #else /* AFS_SGI62_ENV */
2105 #define AFS_N_FILELISTS 1
2106 #endif /* AFS_SGI62_ENV */
2107
2108
2109
2110 void set_staticaddrs(void)
2111 {
2112     staticNameList fileList[AFS_N_FILELISTS];
2113
2114     fileList[0].addrList = (staticAddrList*)calloc(1, sizeof(staticAddrList));
2115     if (!fileList[0].addrList) {
2116         printf("set_staticaddrs: Can't calloc fileList[0].addrList\n");
2117         return;
2118     }
2119     fileList[0].file = "nfs_server.c";
2120     fileList[0].found = 0;
2121     fileList[0].nAddrs = 1;
2122     fileList[0].addrList[0].name = "rfsdisptab_v2";
2123     fileList[0].addrList[0].type = DW_AT_location;
2124     fileList[0].addrList[0].found = 0;
2125
2126 #if defined(AFS_SGI62_ENV) && !defined(AFS_SGI65_ENV)
2127     fileList[1].addrList = (staticAddrList*)calloc(2, sizeof(staticAddrList));
2128     if (!fileList[1].addrList) {
2129         printf("set_staticaddrs: Can't malloc fileList[1].addrList\n");
2130         return;
2131     }
2132     fileList[1].file = "uipc_socket.c";
2133     fileList[1].found = 0;
2134     fileList[1].nAddrs = 2;
2135     fileList[1].addrList[0].name = "sblock";
2136     fileList[1].addrList[0].type = DW_AT_low_pc;
2137     fileList[1].addrList[0].found = 0;
2138     fileList[1].addrList[1].name = "sbunlock";
2139     fileList[1].addrList[1].type = DW_AT_low_pc;
2140     fileList[1].addrList[1].found = 0;
2141
2142     if (64 != sysconf(_SC_KERN_POINTERS))
2143         findMDebugStaticAddresses(fileList, AFS_N_FILELISTS, AFS_SYMS_NEEDED);
2144     else
2145 #endif /* AFS_SGI62_ENV */
2146         findDwarfStaticAddresses(fileList, AFS_N_FILELISTS);
2147
2148     if (fileList[0].addrList[0].found) {
2149         call_syscall(AFSOP_NFSSTATICADDR2, fileList[0].addrList[0].addr.high,
2150                      fileList[0].addrList[0].addr.low);
2151     }
2152     else {
2153         if (afsd_verbose)
2154             printf("NFS V2 is not present in the kernel.\n");
2155     }
2156     free(fileList[0].addrList);
2157 #if defined(AFS_SGI62_ENV) && !defined(AFS_SGI65_ENV)
2158     if (fileList[1].addrList[0].found && fileList[1].addrList[1].found) {
2159         call_syscall(AFSOP_SBLOCKSTATICADDR2,
2160                      fileList[1].addrList[0].addr.high,
2161                      fileList[1].addrList[0].addr.low,
2162                      fileList[1].addrList[1].addr.high,
2163                      fileList[1].addrList[1].addr.low);
2164     }
2165     else {
2166         if (!fileList[1].addrList[0].found)
2167             printf("Can't find %s in kernel. Exiting.\n",
2168                    fileList[1].addrList[0].name);
2169         if (!fileList[1].addrList[0].found)
2170             printf("Can't find %s in kernel. Exiting.\n",
2171                    fileList[1].addrList[1].name);
2172         exit(1);
2173     }
2174     free(fileList[1].addrList);
2175 #endif /* AFS_SGI62_ENV */
2176 }
2177
2178
2179 /* Find addresses for static variables and functions. */
2180 void
2181 findDwarfStaticAddresses(staticNameList * nameList, int nLists)
2182 {
2183     int fd;
2184     int i;
2185     int found = 0;
2186     int code;
2187     char *s;
2188     char *hname = (char*)0;
2189     Dwarf_Unsigned dwarf_access = O_RDONLY;
2190     Dwarf_Debug dwarf_debug;
2191     Dwarf_Error dwarf_error;
2192     Dwarf_Unsigned dwarf_cu_header_length;
2193     Dwarf_Unsigned dwarf_abbrev_offset;
2194     Dwarf_Half dwarf_address_size;
2195     Dwarf_Unsigned next_cu_header;
2196     Dwarf_Die dwarf_die;
2197     Dwarf_Die dwarf_next_die;
2198     Dwarf_Die dwarf_child_die;
2199
2200     if (elf_version(EV_CURRENT) == EV_NONE) {
2201         printf("findDwarfStaticAddresses: Bad elf version.\n");
2202         return;
2203     }
2204
2205     if ((fd=open("/unix", O_RDONLY,0))<0) {
2206         printf("findDwarfStaticAddresses: Failed to open /unix.\n");
2207         return;
2208     }
2209     code = dwarf_init(fd, dwarf_access, NULL, NULL, &dwarf_debug,
2210                       &dwarf_error);
2211     if (code != DW_DLV_OK) {
2212         /* Nope hope for the elves and dwarves, try intermediate code. */
2213         close(fd);
2214         return;
2215     }
2216
2217     found = 0;
2218     while (1) {
2219         /* Run through the headers until we find ones for files we've
2220          * specified in nameList.
2221          */
2222         code = dwarf_next_cu_header(dwarf_debug,
2223                                     &dwarf_cu_header_length, NULL,
2224                                     &dwarf_abbrev_offset,
2225                                     &dwarf_address_size,
2226                                     &next_cu_header,
2227                                     &dwarf_error);
2228         if (code == DW_DLV_NO_ENTRY) {
2229             break;
2230         }
2231         else if (code == DW_DLV_ERROR) {
2232             printf("findDwarfStaticAddresses: Error reading headers: %s\n",
2233                    dwarf_errmsg(dwarf_error));
2234             break;
2235         }
2236
2237         code = dwarf_siblingof(dwarf_debug, NULL, &dwarf_die, &dwarf_error);
2238         if (code != DW_DLV_OK) {
2239             printf("findDwarfStaticAddresses: Can't get first die. %s\n",
2240                    (code == DW_DLV_ERROR) ? dwarf_errmsg(dwarf_error) : "");
2241             break;
2242         }
2243
2244         /* This is the header, test the name. */
2245         code = dwarf_diename(dwarf_die, &hname, &dwarf_error);
2246         if (code == DW_DLV_OK) {
2247             s = strrchr(hname, '/');
2248             for (i=0; i<nLists; i++) {
2249                 if (s && !strcmp(s+1, nameList[i].file)) {
2250                     findElfAddresses(dwarf_debug, dwarf_die, &nameList[i]);
2251                     found ++;
2252                     break;
2253                 }
2254             }
2255         }
2256         else {
2257             printf("findDwarfStaticAddresses: Can't get name of current header. %s\n",
2258                    (code == DW_DLV_ERROR) ? dwarf_errmsg(dwarf_error) : "");
2259             break;
2260         }
2261         dwarf_dealloc(dwarf_debug, hname, DW_DLA_STRING);
2262         hname = (char*)0;
2263         if (found >= nLists) { /* we're done */
2264             break;
2265         }
2266     }
2267
2268      /* Frees up all allocated space. */
2269     (void) dwarf_finish(dwarf_debug, &dwarf_error);
2270     close(fd);
2271 }
2272
2273 void
2274 findElfAddresses(Dwarf_Debug dwarf_debug, Dwarf_Die dwarf_die,
2275                  staticNameList * nameList)
2276 {
2277     int i;
2278     Dwarf_Error dwarf_error;
2279     Dwarf_Die dwarf_next_die;
2280     Dwarf_Die dwarf_child_die;
2281     Dwarf_Attribute dwarf_return_attr;
2282     char *vname = (char*)0;
2283     int found = 0;
2284     int code;
2285     
2286     /* Drop into this die to find names in addrList. */
2287     code = dwarf_child(dwarf_die, &dwarf_child_die, &dwarf_error);
2288     if (code != DW_DLV_OK) {
2289         printf("findElfAddresses: Can't get child die. %s\n",
2290                (code == DW_DLV_ERROR) ? dwarf_errmsg(dwarf_error) : "");
2291         return;
2292     }
2293
2294     /* Try to find names in each sibling. */
2295     dwarf_next_die = (Dwarf_Die)0;
2296     do {
2297         code = dwarf_diename(dwarf_child_die, &vname,
2298                              &dwarf_error);
2299         /* It's possible that some siblings don't have names. */
2300         if (code == DW_DLV_OK) {
2301             for (i=0; i<nameList->nAddrs; i++) {
2302                 if (!nameList->addrList[i].found) {
2303                     if (!strcmp(vname, nameList->addrList[i].name)) {
2304                         getElfAddress(dwarf_debug, dwarf_child_die,
2305                                           &(nameList->addrList[i]));
2306                         found ++;
2307                         break;
2308                     }
2309                 }
2310             }
2311         }
2312         if (dwarf_next_die)
2313             dwarf_dealloc(dwarf_debug, dwarf_next_die, DW_DLA_DIE);
2314
2315         if (found >= nameList->nAddrs) { /* we're done. */
2316             break;
2317         }
2318
2319         dwarf_next_die = dwarf_child_die;
2320         code = dwarf_siblingof(dwarf_debug, dwarf_next_die,
2321                                &dwarf_child_die,
2322                                &dwarf_error);
2323      
2324     } while(code == DW_DLV_OK);
2325 }
2326
2327 /* Get address out of current die. */
2328 void
2329 getElfAddress(Dwarf_Debug dwarf_debug,
2330               Dwarf_Die dwarf_child_die, staticAddrList *addrList)
2331 {
2332     int i;
2333     Dwarf_Error dwarf_error;
2334     Dwarf_Attribute dwarf_return_attr;
2335     Dwarf_Bool dwarf_return_bool;
2336     Dwarf_Locdesc *llbuf = NULL;
2337     Dwarf_Signed listlen;
2338     off64_t addr = (off64_t)0;
2339     int code;
2340
2341     code = dwarf_hasattr(dwarf_child_die, addrList->type,
2342                          &dwarf_return_bool, &dwarf_error);
2343     if ((code !=  DW_DLV_OK) || (!dwarf_return_bool)) {
2344         printf("getElfAddress: no address given for %s. %s\n",
2345                addrList->name, (code == DW_DLV_ERROR) ? dwarf_errmsg(dwarf_error) : "");
2346         return;
2347     }
2348     code = dwarf_attr(dwarf_child_die, addrList->type,
2349                       &dwarf_return_attr,  &dwarf_error);
2350     if (code !=  DW_DLV_OK) {
2351         printf("getElfAddress: Can't get attribute. %s\n",
2352                (code == DW_DLV_ERROR) ? dwarf_errmsg(dwarf_error) : "");
2353         return;
2354     }
2355
2356     switch (addrList->type) {
2357     case DW_AT_location:
2358         code = dwarf_loclist(dwarf_return_attr, &llbuf,
2359                              &listlen, &dwarf_error);
2360         if (code !=   DW_DLV_OK) {
2361             printf("getElfAddress: Can't get location for %s. %s\n",
2362                    addrList->name,
2363                    (code == DW_DLV_ERROR) ? dwarf_errmsg(dwarf_error) : "");
2364             return;
2365         }
2366         if ((listlen != 1) || (llbuf[0].ld_cents != 1)) {
2367             printf("getElfAddress: %s has more than one address.\n",
2368                    addrList->name);
2369             return;
2370         }
2371         addr = llbuf[0].ld_s[0].lr_number;
2372         break;
2373
2374     case DW_AT_low_pc:
2375         code = dwarf_lowpc(dwarf_child_die, (Dwarf_Addr*)&addr, &dwarf_error);
2376         if ( code !=  DW_DLV_OK) {
2377             printf("getElfAddress: Can't get lowpc for %s. %s\n",
2378                    addrList->name,
2379                    (code == DW_DLV_ERROR) ? dwarf_errmsg(dwarf_error) : "");
2380             return;
2381         }
2382         break;
2383         
2384     default:
2385         printf("getElfAddress: Bad case %d in switch.\n", addrList->type);
2386         return;
2387     }
2388
2389     addrList->addr.high = (addr>>32) & 0xffffffff;
2390     addrList->addr.low  = addr & 0xffffffff;
2391     addrList->found = 1;
2392 }
2393
2394 #if defined(AFS_SGI62_ENV) && !defined(AFS_SGI65_ENV)
2395 /* Find symbols in the .mdebug section for 32 bit kernels. */
2396 /*
2397  * do_mdebug()
2398  * On 32bit platforms, we're still using the ucode compilers to build
2399  * the kernel, so we need to get our static text/data from the .mdebug
2400  * section instead of the .dwarf sections.
2401  */
2402 /* SearchNameList searches our bizarre structs for the given string.
2403  * If found, sets the found bit and the address and returns 1.
2404  * Not found returns 0.
2405  */
2406 int SearchNameList(char *name, afs_uint32 addr, staticNameList *nameList,
2407                    int nLists)
2408 {
2409     int i, j;                   
2410     for (i=0; i<nLists; i++) {
2411         for (j=0; j<nameList[i].nAddrs; j++) {
2412             if (nameList[i].addrList[j].found)
2413                 continue;
2414             if (!strcmp(name, nameList[i].addrList[j].name)) {
2415                 nameList[i].addrList[j].addr.high = 0;
2416                 nameList[i].addrList[j].addr.low = addr;
2417                 nameList[i].addrList[j].found = 1;
2418                 return 1;
2419             }
2420         }
2421     }
2422     return 0;
2423 }
2424                                         
2425 static void
2426 SearchMDebug(Elf_Scn *scnp, Elf32_Shdr *shdrp, staticNameList * nameList,
2427              int nLists, int needed)
2428 {
2429     long *buf = (long *)(elf_getdata(scnp, NULL)->d_buf); 
2430     u_long addr, mdoff = shdrp->sh_offset;
2431     HDRR *hdrp;
2432     SYMR *symbase, *symp, *symend;
2433     FDR *fdrbase, *fdrp;
2434     int i, j;
2435     char *strbase, *str;
2436     int ifd;
2437     int nFound = 0;
2438     
2439     /* get header */
2440     addr = (__psunsigned_t)buf;
2441     hdrp = (HDRR *)addr;
2442     
2443     /* setup base addresses */
2444     addr = (u_long)buf + (u_long)(hdrp->cbFdOffset - mdoff);
2445     fdrbase = (FDR *)addr;
2446     addr = (u_long)buf + (u_long)(hdrp->cbSymOffset - mdoff);
2447     symbase = (SYMR *)addr;
2448     addr = (u_long)buf + (u_long)(hdrp->cbSsOffset - mdoff);
2449     strbase = (char *)addr;
2450     
2451 #define KEEPER(a,b)     ((a == stStaticProc && b == scText) || \
2452                          (a == stStatic && (b == scData || b == scBss || \
2453                                             b == scSBss || b == scSData)))
2454         
2455     for (fdrp = fdrbase; fdrp < &fdrbase[hdrp->ifdMax]; fdrp++) {
2456         str = strbase + fdrp->issBase + fdrp->rss;
2457         
2458         /* local symbols for each fd */
2459         for (symp = &symbase[fdrp->isymBase];
2460              symp < &symbase[fdrp->isymBase+fdrp->csym];
2461              symp++) {
2462             if (KEEPER(symp->st, symp->sc)) {
2463                 if (symp->value == 0)
2464                     continue;
2465                 
2466                 str = strbase + fdrp->issBase + symp->iss;
2467                 /* Look for AFS symbols of interest */
2468                 if (SearchNameList(str, symp->value,
2469                                    nameList, nLists)) {
2470                     nFound ++;
2471                     if (nFound >= needed)
2472                         return;
2473                 }
2474             }
2475         }
2476     }
2477 }
2478     
2479 /*
2480  * returns section with the name of scn_name, & puts its header in shdr64 or
2481  * shdr32 based on elf's file type
2482  *
2483  */
2484 Elf_Scn *
2485 findMDebugSection(Elf *elf, char *scn_name)
2486 {
2487         Elf64_Ehdr *ehdr64;
2488         Elf32_Ehdr *ehdr32;
2489         Elf_Scn *scn = NULL;
2490         Elf64_Shdr *shdr64;
2491         Elf32_Shdr *shdr32;
2492
2493         if ((ehdr32 = elf32_getehdr(elf)) == NULL)
2494                 return(NULL);
2495         do {
2496                 if ((scn = elf_nextscn(elf, scn)) == NULL)
2497                         break;
2498                 if ((shdr32 = elf32_getshdr(scn)) == NULL)
2499                         return(NULL);
2500         } while (strcmp(scn_name, elf_strptr(elf, ehdr32->e_shstrndx,
2501                                                   shdr32->sh_name)));
2502
2503         return(scn);    
2504 }
2505
2506
2507 void findMDebugStaticAddresses(staticNameList * nameList, int nLists,
2508                                int needed)
2509 {
2510     int fd;
2511     Elf *elf;
2512     Elf_Scn *mdebug_scn;
2513     Elf32_Shdr *mdebug_shdr;
2514     char *names;
2515
2516     if ((fd = open("/unix", O_RDONLY)) == -1) {
2517         printf("findMDebugStaticAddresses: Failed to open /unix.\n");
2518         return;
2519     }
2520
2521     (void)elf_version(EV_CURRENT);
2522     if((elf = elf_begin(fd, ELF_C_READ, NULL)) == NULL) {
2523         printf("findMDebugStaticAddresses: /unix doesn't seem to be an elf file\n");
2524         close(fd);
2525         return;
2526     }
2527     mdebug_scn = findMDebugSection(elf, ".mdebug");
2528     if (!mdebug_scn) {
2529         printf("findMDebugStaticAddresses: Can't find .mdebug section.\n");
2530         goto find_end;
2531     }
2532     mdebug_shdr = elf32_getshdr(mdebug_scn);
2533     if (!mdebug_shdr) {
2534         printf("findMDebugStaticAddresses: Can't find .mdebug header.\n");
2535         goto find_end;
2536     }
2537
2538     (void) SearchMDebug(mdebug_scn, mdebug_shdr, nameList, nLists, needed);
2539
2540  find_end:
2541     elf_end(elf);
2542     close(fd);
2543 }
2544 #endif /* AFS_SGI62_ENV */
2545
2546 #else /* AFS_SGI61_ENV */
2547 #include <nlist.h>
2548 struct  nlist nlunix[] = {
2549    { "rfsdisptab_v2" },
2550    { 0 },
2551 };
2552
2553 get_nfsstaticaddr() {
2554     int i, j, kmem, count;
2555
2556     if ((kmem = open("/dev/kmem", O_RDONLY)) < 0) {
2557         printf("Warning: can't open /dev/kmem\n");
2558         return 0;
2559     }
2560     if ((j = nlist("/unix", nlunix)) < 0) {
2561         printf("Warning: can't nlist /unix\n");
2562         return 0;
2563     }
2564     i = nlunix[0].n_value;
2565     if (lseek(kmem, i, L_SET/*0*/) != i) {
2566         printf("Warning: can't lseek to %x\n", i);      
2567         return 0;
2568     }
2569     if ((j = read(kmem, &count, sizeof count)) != sizeof count) {
2570         printf("WARNING: kmem read at %x failed\n", i);
2571         return 0;
2572     }
2573     return i;
2574 }
2575 #endif /* AFS_SGI61_ENV */
2576 #endif /* AFS_SGI53_ENV */