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