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