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