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