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