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