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