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