afsd: Detect -dcache presence correctly
[openafs.git] / src / afsd / afsd.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /*
11   *         Information Technology Center
12   *         October 1987
13   *
14   * Description:
15   *     The Andrew File System startup process.  It is responsible for
16   * reading and parsing the various configuration files, starting up
17   * the kernel processes required by AFS and feeding the configuration
18   * information to the kernel.
19   *
20   * Recognized flags are:
21   *     -blocks     The number of blocks available in the workstation cache.
22   *     -files      The target number of files in the workstation cache (Default:
23   *                 1000).
24   *     -rootvol            The name of the root volume to use.
25   *     -stat       The number of stat cache entries.
26   *     -hosts      List of servers to check for volume location info FOR THE
27   *                 HOME CELL.
28   *     -memcache   Use an in-memory cache rather than disk.
29   *     -cachedir    The base directory for the workstation cache.
30   *     -mountdir   The directory on which the AFS is to be mounted.
31   *     -confdir    The configuration directory .
32   *     -nosettime  Don't keep checking the time to avoid drift (default).
33   *     -settime    Keep checking the time to avoid drift.
34   *     -rxmaxmtu   Set the max mtu to help with VPN issues.
35   *     -verbose     Be chatty.
36   *     -disable-dynamic-vcaches     Disable the use of -stat value as the starting size of
37   *                          the size of the vcache/stat cache pool,
38   *                          but increase that pool dynamically as needed.
39   *     -debug     Print out additional debugging info.
40   *     -kerndev    [OBSOLETE] The kernel device for AFS.
41   *     -dontfork   [OBSOLETE] Don't fork off as a new process.
42   *     -daemons   The number of background daemons to start (Default: 2).
43   *     -rmtsys    Also fires up an afs remote sys call (e.g. pioctl, setpag)
44   *                support daemon
45   *     -chunksize [n]   2^n is the chunksize to be used.  0 is default.
46   *     -dcache    The number of data cache entries.
47   *     -biods     Number of bkg I/O daemons (AIX3.1 only)
48   *     -prealloc  Number of preallocated "small" memory blocks
49   *     -logfile   [OBSOLETE] Place where to put the logfile (default in
50   *                <cache>/etc/AFSLog.
51   *     -waitclose make close calls always synchronous (slows em down, tho)
52   *     -files_per_subdir [n]   number of files per cache subdir. (def=2048)
53   *     -shutdown  Shutdown afs daemons
54   *---------------------------------------------------------------------------*/
55
56 #include <afsconfig.h>
57 #include <afs/param.h>
58 #include <roken.h>
59
60 #ifdef IGNORE_SOME_GCC_WARNINGS
61 # pragma GCC diagnostic warning "-Wdeprecated-declarations"
62 #endif
63
64 #define VFS 1
65
66 #include <afs/stds.h>
67 #include <afs/opr.h>
68 #include <afs/opr_assert.h>
69
70 #include <afs/cmd.h>
71
72 #include "afsd.h"
73
74 #include <afs/afsutil.h>
75
76 #include <sys/file.h>
77 #include <sys/wait.h>
78
79 /* darwin dirent.h doesn't give us the prototypes we want if KERNEL is
80  * defined */
81 #if defined(UKERNEL) && defined(AFS_USR_DARWIN_ENV)
82 # undef KERNEL
83 # include <dirent.h>
84 # define KERNEL
85 #else
86 # include <dirent.h>
87 #endif
88
89 #ifdef HAVE_SYS_FS_TYPES_H
90 #include <sys/fs_types.h>
91 #endif
92
93 #if defined(HAVE_SYS_MOUNT_H) && !defined(AFS_ARM_DARWIN_ENV)
94 #include <sys/mount.h>
95 #endif
96
97 #ifdef HAVE_SYS_FCNTL_H
98 #include <sys/fcntl.h>
99 #endif
100
101 #ifdef HAVE_SYS_MNTTAB_H
102 #include <sys/mnttab.h>
103 #endif
104
105 #ifdef HAVE_SYS_MNTENT_H
106 #include <sys/mntent.h>
107 #endif
108
109 #ifdef HAVE_MNTENT_H
110 #include <mntent.h>
111 #endif
112
113 #ifdef HAVE_SYS_VFS_H
114 #include <sys/vfs.h>
115 #endif
116
117 #ifdef HAVE_SYS_FSTYP_H
118 #include <sys/fstyp.h>
119 #endif
120
121 #include <ctype.h>
122
123 #include <afs/afs_args.h>
124 #include <afs/cellconfig.h>
125 #include <afs/afssyscalls.h>
126 #include <afs/afsutil.h>
127 #include <afs/sys_prototypes.h>
128
129 #if defined(AFS_SGI62_ENV) && !defined(AFS_SGI65_ENV)
130 #include <sym.h>
131 #include <symconst.h>
132 #endif
133 #ifdef AFS_SGI65_ENV
134 #include <sched.h>
135 #endif
136
137 #ifdef AFS_DARWIN_ENV
138 #ifdef AFS_DARWIN80_ENV
139 #include <sys/xattr.h>
140 #endif
141 #include <CoreFoundation/CoreFoundation.h>
142
143 #include <SystemConfiguration/SystemConfiguration.h>
144 #include <SystemConfiguration/SCDynamicStore.h>
145
146 #ifndef AFS_ARM_DARWIN_ENV
147 #include <IOKit/pwr_mgt/IOPMLib.h>
148 #include <IOKit/IOMessage.h>
149
150 static io_connect_t root_port;
151 static IONotificationPortRef notify;
152 static io_object_t iterator;
153 #endif
154
155 static CFRunLoopSourceRef source;
156
157 static int event_pid;
158
159 #endif /* AFS_DARWIN_ENV */
160
161 #if AFS_HAVE_STATVFS || defined(HAVE_SYS_STATVFS_H)
162 #include <sys/statvfs.h>
163 #else
164 #if defined(AFS_SUN_ENV)
165 #include <sys/vfs.h>
166 #else
167 #ifdef HAVE_SYS_STATFS_H
168 #include <sys/statfs.h>
169 #endif
170 #endif
171 #endif
172
173 #undef  VIRTUE
174 #undef  VICE
175
176
177 #define CACHEINFOFILE   "cacheinfo"
178 #define DCACHEFILE      "CacheItems"
179 #define VOLINFOFILE     "VolumeItems"
180 #define CELLINFOFILE    "CellItems"
181
182 #define MAXIPADDRS 1024
183
184 char LclCellName[64];
185
186 #define MAX_CACHE_LOOPS 4
187
188
189 /*
190  * Internet address (old style... should be updated).  This was pulled out of the old 4.2
191  * version of <netinet/in.h>, since it's still useful.
192  */
193 struct in_addr_42 {
194     union {
195         struct {
196             u_char s_b1, s_b2, s_b3, s_b4;
197         } S_un_b;
198         struct {
199             u_short s_w1, s_w2;
200         } S_un_w;
201         afs_uint32 S_addr;
202     } S_un;
203 };
204
205 #define mPrintIPAddr(ipaddr)  printf("[%d.%d.%d.%d] ",          \
206       ((struct in_addr_42 *) &(ipaddr))->S_un.S_un_b.s_b1,      \
207       ((struct in_addr_42 *) &(ipaddr))->S_un.S_un_b.s_b2,      \
208       ((struct in_addr_42 *) &(ipaddr))->S_un.S_un_b.s_b3,      \
209       ((struct in_addr_42 *) &(ipaddr))->S_un.S_un_b.s_b4)
210
211 /*
212  * Global configuration variables.
213  */
214 static afs_int32 enable_rxbind = 0;
215 static afs_int32 afs_shutdown = 0;
216 static afs_int32 cacheBlocks;           /*Num blocks in the cache */
217 static afs_int32 cacheFiles;            /*Optimal # of files in workstation cache */
218 static afs_int32 rwpct = 0;
219 static afs_int32 ropct = 0;
220 static afs_int32 cacheStatEntries;      /*Number of stat cache entries */
221 static char *cacheBaseDir;              /*Where the workstation AFS cache lives */
222 static char *confDir;                   /*Where the workstation AFS configuration lives */
223 static char fullpn_DCacheFile[1024];    /*Full pathname of DCACHEFILE */
224 static char fullpn_VolInfoFile[1024];   /*Full pathname of VOLINFOFILE */
225 static char fullpn_CellInfoFile[1024];  /*Full pathanem of CELLINFOFILE */
226 static char fullpn_CacheInfo[1024];     /*Full pathname of CACHEINFO */
227 static char fullpn_VFile[1024]; /*Full pathname of data cache files */
228 static char *vFilePtr;                  /*Ptr to the number part of above pathname */
229 static int sawCacheMountDir = 0;        /* from cmd line */
230 static int sawCacheBaseDir = 0;
231 static int sawCacheBlocks = 0;
232 static int sawDCacheSize = 0;
233 #ifdef AFS_AIX32_ENV
234 static int sawBiod = 0;
235 #endif
236 static int sawCacheStatEntries = 0;
237 char *afsd_cacheMountDir;
238 static char *rootVolume = NULL;
239 #ifdef AFS_XBSD_ENV
240 static int createAndTrunc = O_RDWR | O_CREAT | O_TRUNC; /*Create & truncate on open */
241 #else
242 static int createAndTrunc = O_CREAT | O_TRUNC;  /*Create & truncate on open */
243 #endif
244 static int ownerRWmode = 0600;          /*Read/write OK by owner */
245 static int filesSet = 0;        /*True if number of files explicitly set */
246 static int nFilesPerDir = 2048; /* # files per cache dir */
247 #if defined(AFS_CACHE_BYPASS)
248 #define AFSD_NDAEMONS 4
249 #else
250 #define AFSD_NDAEMONS 2
251 #endif
252 static int nDaemons = AFSD_NDAEMONS;    /* Number of background daemons */
253 static int chunkSize = 0;       /* 2^chunkSize bytes per chunk */
254 static int dCacheSize;          /* # of dcache entries */
255 static int vCacheSize = 200;    /* # of volume cache entries */
256 static int rootVolSet = 0;      /*True if root volume name explicitly set */
257 int addrNum;                    /*Cell server address index being printed */
258 static int cacheFlags = 0;      /*Flags to cache manager */
259 #ifdef AFS_AIX32_ENV
260 static int nBiods = 5;          /* AIX3.1 only */
261 #endif
262 static int preallocs = 400;     /* Def # of allocated memory blocks */
263 static int enable_peer_stats = 0;       /* enable rx stats */
264 static int enable_process_stats = 0;    /* enable rx stats */
265 static int enable_afsdb = 0;    /* enable AFSDB support */
266 static int enable_dynroot = 0;  /* enable dynroot support */
267 static int enable_fakestat = 0; /* enable fakestat support */
268 static int enable_backuptree = 0;       /* enable backup tree support */
269 static int enable_nomount = 0;  /* do not mount */
270 static int enable_splitcache = 0;
271 static int afsd_dynamic_vcaches = 0;    /* Enable dynamic-vcache support */
272 int afsd_verbose = 0;           /*Are we being chatty? */
273 int afsd_debug = 0;             /*Are we printing debugging info? */
274 static int afsd_CloseSynch = 0; /*Are closes synchronous or not? */
275 static int rxmaxmtu = 0;       /* Are we forcing a limit on the mtu? */
276 static int rxmaxfrags = 0;      /* Are we forcing a limit on frags? */
277
278 #ifdef AFS_SGI62_ENV
279 #define AFSD_INO_T ino64_t
280 #else
281 #define AFSD_INO_T afs_uint32
282 #endif
283 struct afsd_file_list {
284     int fileNum;
285     struct afsd_file_list *next;
286 };
287 struct afsd_file_list **cache_dir_filelist = NULL;
288 int *cache_dir_list = NULL;     /* Array of cache subdirs */
289 int *dir_for_V = NULL;          /* Array: dir of each cache file.
290                                  * -1: file does not exist
291                                  * -2: file exists in top-level
292                                  * >=0: file exists in Dxxx
293                                  */
294 #if !defined(AFS_CACHE_VNODE_PATH) && !defined(AFS_LINUX26_ENV)
295 AFSD_INO_T *inode_for_V;        /* Array of inodes for desired
296                                  * cache files */
297 #endif
298 int missing_DCacheFile = 1;     /*Is the DCACHEFILE missing? */
299 int missing_VolInfoFile = 1;    /*Is the VOLINFOFILE missing? */
300 int missing_CellInfoFile = 1;   /*Is the CELLINFOFILE missing? */
301 int afsd_rmtsys = 0;            /* Default: don't support rmtsys */
302 struct afs_cacheParams cparams; /* params passed to cache manager */
303
304 int PartSizeOverflow(char *path, int cs);
305
306 #if defined(AFS_SUN510_ENV) && defined(RXK_LISTENER_ENV)
307 static void fork_rx_syscall_wait();
308 #endif
309 static void fork_rx_syscall();
310 static void fork_syscall();
311
312 enum optionsList {
313     OPT_blocks,
314     OPT_files,
315     OPT_rootvol,
316     OPT_stat,
317     OPT_memcache,
318     OPT_cachedir,
319     OPT_mountdir,
320     OPT_daemons,
321     OPT_nosettime,
322     OPT_verbose,
323     OPT_rmtsys,
324     OPT_debug,
325     OPT_chunksize,
326     OPT_dcache,
327     OPT_volumes,
328     OPT_biods,
329     OPT_prealloc,
330     OPT_confdir,
331     OPT_logfile,
332     OPT_waitclose,
333     OPT_shutdown,
334     OPT_peerstats,
335     OPT_processstats,
336     OPT_memallocsleep,
337     OPT_afsdb,
338     OPT_filesdir,
339     OPT_dynroot,
340     OPT_fakestat,
341     OPT_fakestatall,
342     OPT_nomount,
343     OPT_backuptree,
344     OPT_rxbind,
345     OPT_settime,
346     OPT_rxpck,
347     OPT_splitcache,
348     OPT_nodynvcache,
349     OPT_rxmaxmtu,
350     OPT_dynrootsparse,
351     OPT_rxmaxfrags,
352 };
353
354 #if defined(AFS_DARWIN_ENV) && !defined(AFS_ARM_DARWIN_ENV)
355 static void
356 afsd_sleep_callback(void * refCon, io_service_t service,
357                     natural_t messageType, void * messageArgument )
358 {
359     switch (messageType) {
360     case kIOMessageCanSystemSleep:
361         /* Idle sleep is about to kick in; can
362            prevent sleep by calling IOCancelPowerChange, otherwise
363            if we don't ack in 30s the system sleeps anyway */
364
365         /* allow it */
366         IOAllowPowerChange(root_port, (long)messageArgument);
367         break;
368
369     case kIOMessageSystemWillSleep:
370         /* The system WILL go to sleep. Ack or suffer delay */
371
372         IOAllowPowerChange(root_port, (long)messageArgument);
373         break;
374
375     case kIOMessageSystemWillRestart:
376         /* The system WILL restart. Ack or suffer delay */
377
378         IOAllowPowerChange(root_port, (long)messageArgument);
379         break;
380
381     case kIOMessageSystemWillPowerOn:
382     case kIOMessageSystemHasPoweredOn:
383         /* coming back from sleep */
384
385         IOAllowPowerChange(root_port, (long)messageArgument);
386         break;
387
388     default:
389         IOAllowPowerChange(root_port, (long)messageArgument);
390         break;
391     }
392 }
393
394 static void
395 afsd_update_addresses(CFRunLoopTimerRef timer, void *info)
396 {
397     /* parse multihomed address files */
398     afs_uint32 addrbuf[MAXIPADDRS], maskbuf[MAXIPADDRS],
399         mtubuf[MAXIPADDRS];
400     char reason[1024];
401     afs_int32 code;
402
403     code =
404         parseNetFiles(addrbuf, maskbuf, mtubuf, MAXIPADDRS, reason,
405                       AFSDIR_CLIENT_NETINFO_FILEPATH,
406                       AFSDIR_CLIENT_NETRESTRICT_FILEPATH);
407
408     if (code > 0) {
409         /* Note we're refreshing */
410         code = code | 0x40000000;
411         afsd_call_syscall(AFSOP_ADVISEADDR, code, addrbuf, maskbuf, mtubuf);
412     } else
413         printf("ADVISEADDR: Error in specifying interface addresses:%s\n",
414                reason);
415
416     /* Since it's likely this means our DNS server changed, reinit now */
417     if (enable_afsdb)
418         res_init();
419 }
420
421 /* This function is called when the system's ip addresses may have changed. */
422 static void
423 afsd_ipaddr_callback (SCDynamicStoreRef store, CFArrayRef changed_keys, void *info)
424 {
425       CFRunLoopTimerRef timer;
426
427       timer = CFRunLoopTimerCreate (NULL, CFAbsoluteTimeGetCurrent () + 1.0,
428                                     0.0, 0, 0, afsd_update_addresses, NULL);
429       CFRunLoopAddTimer (CFRunLoopGetCurrent (), timer,
430                          kCFRunLoopDefaultMode);
431       CFRelease (timer);
432 }
433
434 static void
435 afsd_event_cleanup(int signo) {
436
437     CFRunLoopRemoveSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
438     CFRelease (source);
439     IODeregisterForSystemPower(&iterator);
440     IOServiceClose(root_port);
441     IONotificationPortDestroy(notify);
442     exit(0);
443 }
444
445 /* Adapted from "Living in a Dynamic TCP/IP Environment" technote. */
446 static void
447 afsd_install_events(void)
448 {
449     SCDynamicStoreContext ctx = {0};
450     SCDynamicStoreRef store;
451
452     root_port = IORegisterForSystemPower(0,&notify,afsd_sleep_callback,&iterator);
453
454     if (root_port) {
455         CFRunLoopAddSource(CFRunLoopGetCurrent(),
456                            IONotificationPortGetRunLoopSource(notify),
457                            kCFRunLoopDefaultMode);
458     }
459
460
461     store = SCDynamicStoreCreate (NULL,
462                                   CFSTR ("AddIPAddressListChangeCallbackSCF"),
463                                   afsd_ipaddr_callback, &ctx);
464
465     if (store) {
466         const void *keys[1];
467
468         /* Request IPV4 address change notification */
469         keys[0] = (SCDynamicStoreKeyCreateNetworkServiceEntity
470                    (NULL, kSCDynamicStoreDomainState,
471                     kSCCompAnyRegex, kSCEntNetIPv4));
472
473 #if 0
474         /* This should tell us when the hostname(s) change. do we care? */
475         keys[N] = SCDynamicStoreKeyCreateHostNames (NULL);
476 #endif
477
478         if (keys[0] != NULL) {
479             CFArrayRef pattern_array;
480
481             pattern_array = CFArrayCreate (NULL, keys, 1,
482                                            &kCFTypeArrayCallBacks);
483
484             if (pattern_array != NULL)
485             {
486                 SCDynamicStoreSetNotificationKeys (store, NULL, pattern_array);
487                 source = SCDynamicStoreCreateRunLoopSource (NULL, store, 0);
488
489                 CFRelease (pattern_array);
490             }
491
492             if (keys[0] != NULL)
493                 CFRelease (keys[0]);
494         }
495
496         CFRelease (store);
497     }
498
499     if (source != NULL) {
500         CFRunLoopAddSource (CFRunLoopGetCurrent(),
501                             source, kCFRunLoopDefaultMode);
502     }
503
504     signal(SIGTERM, afsd_event_cleanup);
505
506     CFRunLoopRun();
507 }
508 #endif
509
510 /* ParseArgs is now obsolete, being handled by cmd */
511
512 /*------------------------------------------------------------------------------
513   * ParseCacheInfoFile
514   *
515   * Description:
516   *     Open the file containing the description of the workstation's AFS cache
517   *     and pull out its contents.  The format of this file is as follows:
518   *
519   *         cacheMountDir:cacheBaseDir:cacheBlocks
520   *
521   * Arguments:
522   *     None.
523   *
524   * Returns:
525   *     0 if everything went well,
526   *     1 otherwise.
527   *
528   * Environment:
529   *     Nothing interesting.
530   *
531   *  Side Effects:
532   *     Sets globals.
533   *---------------------------------------------------------------------------*/
534
535 int
536 ParseCacheInfoFile(void)
537 {
538     static char rn[] = "ParseCacheInfoFile";    /*This routine's name */
539     FILE *cachefd;              /*Descriptor for cache info file */
540     int parseResult;            /*Result of our fscanf() */
541     afs_int32 tCacheBlocks;
542     char tCacheBaseDir[1024], *tbd, tCacheMountDir[1024], *tmd;
543
544     if (afsd_debug)
545         printf("%s: Opening cache info file '%s'...\n", rn, fullpn_CacheInfo);
546
547     cachefd = fopen(fullpn_CacheInfo, "r");
548     if (!cachefd) {
549         printf("%s: Can't read cache info file '%s'\n", rn, fullpn_CacheInfo);
550         return (1);
551     }
552
553     /*
554      * Parse the contents of the cache info file.  All chars up to the first
555      * colon are the AFS mount directory, all chars to the next colon are the
556      * full path name of the workstation cache directory and all remaining chars
557      * represent the number of blocks in the cache.
558      */
559     tCacheMountDir[0] = tCacheBaseDir[0] = '\0';
560     parseResult =
561         fscanf(cachefd, "%1024[^:]:%1024[^:]:%d", tCacheMountDir,
562                tCacheBaseDir, &tCacheBlocks);
563
564     /*
565      * Regardless of how the parse went, we close the cache info file.
566      */
567     fclose(cachefd);
568
569     if (parseResult == EOF || parseResult < 3) {
570         printf("%s: Format error in cache info file!\n", rn);
571         if (parseResult == EOF)
572             printf("\tEOF encountered before any field parsed.\n");
573         else
574             printf("\t%d out of 3 fields successfully parsed.\n",
575                    parseResult);
576
577         return (1);
578     }
579
580     for (tmd = tCacheMountDir; *tmd == '\n' || *tmd == ' ' || *tmd == '\t';
581          tmd++);
582     for (tbd = tCacheBaseDir; *tbd == '\n' || *tbd == ' ' || *tbd == '\t';
583          tbd++);
584     /* now copy in the fields not explicitly overridden by cmd args */
585     if (!sawCacheMountDir)
586         afsd_cacheMountDir = strdup(tmd);
587     if (!sawCacheBaseDir)
588         cacheBaseDir = strdup(tbd);
589     if (!sawCacheBlocks)
590         cacheBlocks = tCacheBlocks;
591
592     if (afsd_debug) {
593         printf("%s: Cache info file successfully parsed:\n", rn);
594         printf
595             ("\tcacheMountDir: '%s'\n\tcacheBaseDir: '%s'\n\tcacheBlocks: %d\n",
596              tmd, tbd, tCacheBlocks);
597     }
598     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE)) {
599         return (PartSizeOverflow(tbd, cacheBlocks));
600     }
601
602     return (0);
603 }
604
605 /*
606  * All failures to open the partition are ignored. Also if the cache dir
607  * isn't a mounted partition it's also ignored since we can't guarantee
608  * what will be stored afterwards. Too many if's. This is now purely
609  * advisory. ODS with over 2G partition also gives warning message.
610  *
611  * Returns:
612  *      0 if everything went well,
613  *      1 otherwise.
614  */
615 int
616 PartSizeOverflow(char *path, int cs)
617 {
618   int bsize = -1;
619   afs_int64 totalblks, mint;
620 #if AFS_HAVE_STATVFS || defined(HAVE_SYS_STATVFS_H)
621     struct statvfs statbuf;
622
623     if (statvfs(path, &statbuf) != 0) {
624         if (afsd_debug)
625             printf
626                 ("statvfs failed on %s; skip checking for adequate partition space\n",
627                  path);
628         return 0;
629     }
630     totalblks = statbuf.f_blocks;
631     bsize = statbuf.f_frsize;
632 #if AFS_AIX51_ENV
633     if (strcmp(statbuf.f_basetype, "jfs")) {
634         fprintf(stderr, "Cache filesystem '%s' must be jfs (now %s)\n",
635                 path, statbuf.f_basetype);
636         return 1;
637     }
638 #endif /* AFS_AIX51_ENV */
639
640 #else /* AFS_HAVE_STATVFS */
641     struct statfs statbuf;
642
643     if (statfs(path, &statbuf) < 0) {
644         if (afsd_debug)
645             printf
646                 ("statfs failed on %s; skip checking for adequate partition space\n",
647                  path);
648         return 0;
649     }
650     totalblks = statbuf.f_blocks;
651     bsize = statbuf.f_bsize;
652 #endif
653     if (bsize == -1)
654         return 0;               /* success */
655
656     /* now free and totalblks are in fragment units, but we want them in 1K units */
657     if (bsize >= 1024) {
658         totalblks *= (bsize / 1024);
659     } else {
660         totalblks /= (1024 / bsize);
661     }
662
663     mint = totalblks / 100 * 95;
664     if (cs > mint) {
665         printf
666             ("Cache size (%d) must be less than 95%% of partition size (which is %lld). Lower cache size\n",
667              cs, mint);
668         return 1;
669     }
670
671     return 0;
672 }
673
674 /*-----------------------------------------------------------------------------
675   * GetVFileNumber
676   *
677   * Description:
678   *     Given the final component of a filename expected to be a data cache file,
679   *     return the integer corresponding to the file.  Note: we reject names that
680   *     are not a ``V'' followed by an integer.  We also reject those names having
681   *     the right format but lying outside the range [0..cacheFiles-1].
682   *
683   * Arguments:
684   *     fname : Char ptr to the filename to parse.
685   *     max   : integer for the highest number to accept
686   *
687   * Returns:
688   *     >= 0 iff the file is really a data cache file numbered from 0 to cacheFiles-1, or
689   *     -1      otherwise.
690   *
691   * Environment:
692   *     Nothing interesting.
693   *
694   * Side Effects:
695   *     None.
696   *---------------------------------------------------------------------------*/
697
698 static int
699 doGetXFileNumber(char *fname, char filechar, int maxNum)
700 {
701     int computedVNumber;        /*The computed file number we return */
702     int filenameLen;            /*Number of chars in filename */
703     int currDigit;              /*Current digit being processed */
704
705     /*
706      * The filename must have at least two characters, the first of which must be a ``filechar''
707      * and the second of which cannot be a zero unless the file is exactly two chars long.
708      */
709     filenameLen = strlen(fname);
710     if (filenameLen < 2)
711         return (-1);
712     if (fname[0] != filechar)
713         return (-1);
714     if ((filenameLen > 2) && (fname[1] == '0'))
715         return (-1);
716
717     /*
718      * Scan through the characters in the given filename, failing immediately if a non-digit
719      * is found.
720      */
721     for (currDigit = 1; currDigit < filenameLen; currDigit++)
722         if (isdigit(fname[currDigit]) == 0)
723             return (-1);
724
725     /*
726      * All relevant characters are digits.  Pull out the decimal number they represent.
727      * Reject it if it's out of range, otherwise return it.
728      */
729     computedVNumber = atoi(++fname);
730     if (computedVNumber < cacheFiles)
731         return (computedVNumber);
732     else
733         return (-1);
734 }
735
736 int
737 GetVFileNumber(char *fname, int maxFile)
738 {
739     return doGetXFileNumber(fname, 'V', maxFile);
740 }
741
742 int
743 GetDDirNumber(char *fname, int maxDir)
744 {
745     return doGetXFileNumber(fname, 'D', maxDir);
746 }
747
748
749 /*-----------------------------------------------------------------------------
750   * CreateCacheFile
751   *
752   * Description:
753   *     Given a full pathname for a file we need to create for the workstation AFS
754   *     cache, go ahead and create the file.
755   *
756   * Arguments:
757   *     fname : Full pathname of file to create.
758   *     statp : A pointer to a stat buffer which, if NON-NULL, will be
759   *             filled by fstat()
760   *
761   * Returns:
762   *     0   iff the file was created,
763   *     -1  otherwise.
764   *
765   * Environment:
766   *     The given cache file has been found to be missing.
767   *
768   * Side Effects:
769   *     As described.
770   *---------------------------------------------------------------------------*/
771
772 static int
773 CreateCacheSubDir(char *basename, int dirNum)
774 {
775     static char rn[] = "CreateCacheSubDir";     /* Routine Name */
776     char dir[1024];
777     int ret;
778
779     /* Build the new cache subdirectory */
780     sprintf(dir, "%s/D%d", basename, dirNum);
781
782     if (afsd_debug)
783         printf("%s: Creating cache subdir '%s'\n", rn, dir);
784
785     if ((ret = mkdir(dir, 0700)) != 0) {
786         printf("%s: Can't create '%s', error return is %d (%d)\n", rn, dir,
787                ret, errno);
788         if (errno != EEXIST)
789             return (-1);
790     }
791
792     /* Mark this directory as created */
793     cache_dir_list[dirNum] = 0;
794
795     /* And return success */
796     return (0);
797 }
798
799 static void
800 SetNoBackupAttr(char *fullpn)
801 {
802 #ifdef AFS_DARWIN80_ENV
803     int ret;
804
805     ret = setxattr(fullpn, "com.apple.metadata:com_apple_backup_excludeItem",
806                    "com.apple.backupd", strlen("com.apple.backupd"), 0,
807                    XATTR_CREATE);
808     if(ret < 0)
809     {
810         if(errno != EEXIST)
811             fprintf(stderr, "afsd: Warning: failed to set attribute to preclude cache backup: %s\n", strerror(errno));
812     }
813 #endif
814     return;
815 }
816
817 static int
818 MoveCacheFile(char *basename, int fromDir, int toDir, int cacheFile,
819               int maxDir)
820 {
821     static char rn[] = "MoveCacheFile";
822     char from[1024], to[1024];
823     int ret;
824
825     if (cache_dir_list[toDir] < 0
826         && (ret = CreateCacheSubDir(basename, toDir))) {
827         printf("%s: Can't create directory '%s/D%d'\n", rn, basename, toDir);
828         return ret;
829     }
830
831     /* Build the from,to dir */
832     if (fromDir < 0) {
833         /* old-style location */
834         snprintf(from, sizeof(from), "%s/V%d", basename, cacheFile);
835     } else {
836         snprintf(from, sizeof(from), "%s/D%d/V%d", basename, fromDir,
837                  cacheFile);
838     }
839
840     snprintf(to, sizeof(from), "%s/D%d/V%d", basename, toDir, cacheFile);
841
842     if (afsd_verbose)
843         printf("%s: Moving cacheFile from '%s' to '%s'\n", rn, from, to);
844
845     if ((ret = rename(from, to)) != 0) {
846         printf("%s: Can't rename '%s' to '%s', error return is %d (%d)\n", rn,
847                from, to, ret, errno);
848         return -1;
849     }
850     SetNoBackupAttr(to);
851
852     /* Reset directory pointer; fix file counts */
853     dir_for_V[cacheFile] = toDir;
854     cache_dir_list[toDir]++;
855     if (fromDir < maxDir && fromDir >= 0)
856         cache_dir_list[fromDir]--;
857
858     return 0;
859 }
860
861 int
862 CreateCacheFile(char *fname, struct stat *statp)
863 {
864     static char rn[] = "CreateCacheFile";       /*Routine name */
865     int cfd;                    /*File descriptor to AFS cache file */
866     int closeResult;            /*Result of close() */
867
868     if (afsd_debug)
869         printf("%s: Creating cache file '%s'\n", rn, fname);
870     cfd = open(fname, createAndTrunc, ownerRWmode);
871     if (cfd <= 0) {
872         printf("%s: Can't create '%s', error return is %d (%d)\n", rn, fname,
873                cfd, errno);
874         return (-1);
875     }
876     if (statp != NULL) {
877         closeResult = fstat(cfd, statp);
878         if (closeResult) {
879             printf
880                 ("%s: Can't stat newly-created AFS cache file '%s' (code %d)\n",
881                  rn, fname, errno);
882             return (-1);
883         }
884     }
885     closeResult = close(cfd);
886     if (closeResult) {
887         printf
888             ("%s: Can't close newly-created AFS cache file '%s' (code %d)\n",
889              rn, fname, errno);
890         return (-1);
891     }
892
893     return (0);
894 }
895
896 static void
897 CreateFileIfMissing(char *fullpn, int missing)
898 {
899     if (missing) {
900         if (CreateCacheFile(fullpn, NULL))
901             printf("CreateFileIfMissing: Can't create '%s'\n", fullpn);
902     }
903 }
904
905 static void
906 UnlinkUnwantedFile(char *rn, char *fullpn_FileToDelete, char *fileToDelete)
907 {
908     if (unlink(fullpn_FileToDelete)) {
909         if ((errno == EISDIR || errno == EPERM) && *fileToDelete == 'D') {
910             if (rmdir(fullpn_FileToDelete)) {
911                 printf("%s: Can't rmdir '%s', errno is %d\n", rn,
912                        fullpn_FileToDelete, errno);
913             }
914         } else
915             printf("%s: Can't unlink '%s', errno is %d\n", rn,
916                    fullpn_FileToDelete, errno);
917     }
918 }
919
920 /*-----------------------------------------------------------------------------
921   * SweepAFSCache
922   *
923   * Description:
924   *     Sweep through the AFS cache directory, recording the inode number for
925   *     each valid data cache file there.  Also, delete any file that doesn't belong
926   *     in the cache directory during this sweep, and remember which of the other
927   *     residents of this directory were seen.  After the sweep, we create any data
928   *     cache files that were missing.
929   *
930   * Arguments:
931   *     vFilesFound : Set to the number of data cache files found.
932   *
933   * Returns:
934   *     0   if everything went well,
935   *     -1 otherwise.
936   *
937   * Environment:
938   *     This routine may be called several times.  If the number of data cache files
939   *     found is less than the global cacheFiles, then the caller will need to call it
940   *     again to record the inodes of the missing zero-length data cache files created
941   *     in the previous call.
942   *
943   * Side Effects:
944   *     Fills up the global inode_for_V array, may create and/or delete files as
945   *     explained above.
946   *---------------------------------------------------------------------------*/
947
948
949 static int
950 doSweepAFSCache(int *vFilesFound,
951                 char *directory,        /* /path/to/cache/directory */
952                 int dirNum,             /* current directory number */
953                 int maxDir)             /* maximum directory number */
954 {
955     static char rn[] = "doSweepAFSCache";       /* Routine Name */
956     char fullpn_FileToDelete[1024];     /*File to be deleted from cache */
957     char *fileToDelete;         /*Ptr to last component of above */
958     DIR *cdirp;                 /*Ptr to cache directory structure */
959 #ifdef AFS_SGI62_ENV
960     struct dirent64 *currp;     /*Current directory entry */
961 #else
962     struct dirent *currp;       /*Current directory entry */
963 #endif
964     int vFileNum;               /*Data cache file's associated number */
965     int thisDir;                /* A directory number */
966     int highDir = 0;
967
968     if (afsd_debug)
969         printf("%s: Opening cache directory '%s'\n", rn, directory);
970
971     if (chmod(directory, 0700)) {       /* force it to be 700 */
972         printf("%s: Can't 'chmod 0700' the cache dir, '%s'.\n", rn,
973                directory);
974         return (-1);
975     }
976     cdirp = opendir(directory);
977     if (cdirp == (DIR *) 0) {
978         printf("%s: Can't open AFS cache directory, '%s'.\n", rn, directory);
979         return (-1);
980     }
981
982     /*
983      * Scan the directory entries, remembering data cache file inodes
984      * and the existance of other important residents.  Recurse into
985      * the data subdirectories.
986      *
987      * Delete all files and directories that don't belong here.
988      */
989     sprintf(fullpn_FileToDelete, "%s/", directory);
990     fileToDelete = fullpn_FileToDelete + strlen(fullpn_FileToDelete);
991
992 #ifdef AFS_SGI62_ENV
993     for (currp = readdir64(cdirp); currp; currp = readdir64(cdirp))
994 #else
995     for (currp = readdir(cdirp); currp; currp = readdir(cdirp))
996 #endif
997     {
998         if (afsd_debug) {
999             printf("%s: Current directory entry:\n", rn);
1000 #if defined(AFS_SGI62_ENV) || defined(AFS_DARWIN90_ENV)
1001             printf("\tinode=%" AFS_INT64_FMT ", reclen=%d, name='%s'\n", currp->d_ino,
1002                    currp->d_reclen, currp->d_name);
1003 #elif defined(AFS_DFBSD_ENV) || defined(AFS_USR_DFBSD_ENV)
1004             printf("\tinode=%ld, name='%s'\n", (long)currp->d_ino, currp->d_name);
1005 #else
1006             printf("\tinode=%ld, reclen=%d, name='%s'\n", (long)currp->d_ino,
1007                    currp->d_reclen, currp->d_name);
1008 #endif
1009         }
1010
1011         /*
1012          * If dirNum < 0, we are a top-level cache directory and should
1013          * only contain sub-directories and other sundry files.  Therefore,
1014          * V-files are valid only if dirNum >= 0, and Directories are only
1015          * valid if dirNum < 0.
1016          */
1017
1018         if (*(currp->d_name) == 'V'
1019             && ((vFileNum = GetVFileNumber(currp->d_name, cacheFiles)) >=
1020                 0)) {
1021             /*
1022              * Found a valid data cache filename.  Remember this
1023              * file's inode, directory, and bump the number of files found
1024              * total and in this directory.
1025              */
1026 #if !defined(AFS_CACHE_VNODE_PATH) && !defined(AFS_LINUX26_ENV)
1027             inode_for_V[vFileNum] = currp->d_ino;
1028 #endif
1029             dir_for_V[vFileNum] = dirNum;       /* remember this directory */
1030
1031             if (!maxDir) {
1032                 /* If we're in a real subdir, mark this file to be moved
1033                  * if we've already got too many files in this directory
1034                  */
1035                 assert(dirNum >= 0);
1036                 cache_dir_list[dirNum]++;       /* keep directory's file count */
1037                 if (cache_dir_list[dirNum] > nFilesPerDir) {
1038                     /* Too many files -- add to filelist */
1039                     struct afsd_file_list *tmp = (struct afsd_file_list *)
1040                         malloc(sizeof(*tmp));
1041                     if (!tmp)
1042                         printf
1043                             ("%s: MALLOC FAILED allocating file_list entry\n",
1044                              rn);
1045                     else {
1046                         tmp->fileNum = vFileNum;
1047                         tmp->next = cache_dir_filelist[dirNum];
1048                         cache_dir_filelist[dirNum] = tmp;
1049                     }
1050                 }
1051             }
1052             (*vFilesFound)++;
1053         } else if (dirNum < 0 && (*(currp->d_name) == 'D')
1054                    && GetDDirNumber(currp->d_name, 1 << 30) >= 0) {
1055             int retval = 0;
1056             if ((vFileNum = GetDDirNumber(currp->d_name, maxDir)) >= 0) {
1057                 /* Found a valid cachefile sub-Directory.  Remember this number
1058                  * and recurse into it.  Note that subdirs cannot have subdirs.
1059                  */
1060                 retval = 1;
1061             } else if ((vFileNum = GetDDirNumber(currp->d_name, 1 << 30)) >=
1062                        0) {
1063                 /* This directory is going away, but figure out if there
1064                  * are any cachefiles in here that should be saved by
1065                  * moving them to other cache directories.  This directory
1066                  * will be removed later.
1067                  */
1068                 retval = 2;
1069             }
1070
1071             /* Save the highest directory number we've seen */
1072             if (vFileNum > highDir)
1073                 highDir = vFileNum;
1074
1075             /* If this directory is staying, be sure to mark it as 'found' */
1076             if (retval == 1)
1077                 cache_dir_list[vFileNum] = 0;
1078
1079             /* Print the dirname for recursion */
1080             sprintf(fileToDelete, "%s", currp->d_name);
1081
1082             /* Note: vFileNum is the directory number */
1083             retval =
1084                 doSweepAFSCache(vFilesFound, fullpn_FileToDelete, vFileNum,
1085                                 (retval == 1 ? 0 : -1));
1086             if (retval) {
1087                 printf("%s: Recursive sweep failed on directory %s\n", rn,
1088                        currp->d_name);
1089                 return retval;
1090             }
1091         } else if (dirNum < 0 && strcmp(currp->d_name, DCACHEFILE) == 0) {
1092             /*
1093              * Found the file holding the dcache entries.
1094              */
1095             missing_DCacheFile = 0;
1096             SetNoBackupAttr(fullpn_DCacheFile);
1097         } else if (dirNum < 0 && strcmp(currp->d_name, VOLINFOFILE) == 0) {
1098             /*
1099              * Found the file holding the volume info.
1100              */
1101             missing_VolInfoFile = 0;
1102             SetNoBackupAttr(fullpn_VolInfoFile);
1103         } else if (dirNum < 0 && strcmp(currp->d_name, CELLINFOFILE) == 0) {
1104             /*
1105              * Found the file holding the cell info.
1106              */
1107             missing_CellInfoFile = 0;
1108             SetNoBackupAttr(fullpn_CellInfoFile);
1109         } else if ((strcmp(currp->d_name, ".") == 0)
1110                    || (strcmp(currp->d_name, "..") == 0) ||
1111 #ifdef AFS_DECOSF_ENV
1112                    /* these are magic AdvFS files */
1113                    (strcmp(currp->d_name, ".tags") == 0)
1114                    || (strcmp(currp->d_name, "quota.user") == 0)
1115                    || (strcmp(currp->d_name, "quota.group") == 0) ||
1116 #endif
1117 #ifdef AFS_LINUX22_ENV
1118                    /* this is the ext3 journal file */
1119                    (strcmp(currp->d_name, ".journal") == 0) ||
1120 #endif
1121                    (strcmp(currp->d_name, "lost+found") == 0)) {
1122             /*
1123              * Don't do anything - this file is legit, and is to be left alone.
1124              */
1125         } else {
1126             /*
1127              * This file/directory doesn't belong in the cache.  Nuke it.
1128              */
1129             sprintf(fileToDelete, "%s", currp->d_name);
1130             if (afsd_verbose)
1131                 printf("%s: Deleting '%s'\n", rn, fullpn_FileToDelete);
1132             UnlinkUnwantedFile(rn, fullpn_FileToDelete, fileToDelete);
1133         }
1134     }
1135
1136     if (dirNum < 0) {
1137
1138         /*
1139          * Create all the cache files that are missing.
1140          */
1141         CreateFileIfMissing(fullpn_DCacheFile, missing_DCacheFile);
1142         CreateFileIfMissing(fullpn_VolInfoFile, missing_VolInfoFile);
1143         CreateFileIfMissing(fullpn_CellInfoFile, missing_CellInfoFile);
1144
1145         /* ADJUST CACHE FILES */
1146
1147         /* First, let's walk through the list of files and figure out
1148          * if there are any leftover files in extra directories or
1149          * missing files.  Move the former and create the latter in
1150          * subdirs with extra space.
1151          */
1152
1153         thisDir = 0;            /* Keep track of which subdir has space */
1154
1155         for (vFileNum = 0; vFileNum < cacheFiles; vFileNum++) {
1156             if (dir_for_V[vFileNum] == -1) {
1157                 /* This file does not exist.  Create it in the first
1158                  * subdir that still has extra space.
1159                  */
1160                 while (thisDir < maxDir
1161                        && cache_dir_list[thisDir] >= nFilesPerDir)
1162                     thisDir++;
1163                 if (thisDir >= maxDir)
1164                     printf("%s: can't find directory to create V%d\n", rn,
1165                            vFileNum);
1166                 else {
1167                     struct stat statb;
1168 #if !defined(AFS_CACHE_VNODE_PATH) && !defined(AFS_LINUX26_ENV)
1169                     assert(inode_for_V[vFileNum] == (AFSD_INO_T) 0);
1170 #endif
1171                     sprintf(vFilePtr, "D%d/V%d", thisDir, vFileNum);
1172                     if (afsd_verbose)
1173                         printf("%s: Creating '%s'\n", rn, fullpn_VFile);
1174                     if (cache_dir_list[thisDir] < 0
1175                         && CreateCacheSubDir(directory, thisDir))
1176                         printf("%s: Can't create directory for '%s'\n", rn,
1177                                fullpn_VFile);
1178                     if (CreateCacheFile(fullpn_VFile, &statb))
1179                         printf("%s: Can't create '%s'\n", rn, fullpn_VFile);
1180                     else {
1181 #if !defined(AFS_CACHE_VNODE_PATH) && !defined(AFS_LINUX26_ENV)
1182                         inode_for_V[vFileNum] = statb.st_ino;
1183 #endif
1184                         dir_for_V[vFileNum] = thisDir;
1185                         cache_dir_list[thisDir]++;
1186                         (*vFilesFound)++;
1187                     }
1188                     SetNoBackupAttr(fullpn_VFile);
1189                 }
1190
1191             } else if (dir_for_V[vFileNum] >= maxDir
1192                        || dir_for_V[vFileNum] == -2) {
1193                 /* This file needs to move; move it to the first subdir
1194                  * that has extra space.  (-2 means it's in the toplevel)
1195                  */
1196                 while (thisDir < maxDir
1197                        && cache_dir_list[thisDir] >= nFilesPerDir)
1198                     thisDir++;
1199                 if (thisDir >= maxDir)
1200                     printf("%s: can't find directory to move V%d\n", rn,
1201                            vFileNum);
1202                 else {
1203                     if (MoveCacheFile
1204                         (directory, dir_for_V[vFileNum], thisDir, vFileNum,
1205                          maxDir)) {
1206                         /* Cannot move.  Ignore this file??? */
1207                         /* XXX */
1208                     }
1209                 }
1210             }
1211         }                       /* for */
1212
1213         /* At this point, we've moved all of the valid cache files
1214          * into the valid subdirs, and created all the extra
1215          * cachefiles we need to create.  Next, rebalance any subdirs
1216          * with too many cache files into the directories with not
1217          * enough cache files.  Note that thisDir currently sits at
1218          * the lowest subdir that _may_ have room.
1219          */
1220
1221         for (dirNum = 0; dirNum < maxDir; dirNum++) {
1222             struct afsd_file_list *thisFile;
1223
1224             for (thisFile = cache_dir_filelist[dirNum];
1225                  thisFile && cache_dir_list[dirNum] >= nFilesPerDir;
1226                  thisFile = thisFile->next) {
1227                 while (thisDir < maxDir
1228                        && cache_dir_list[thisDir] >= nFilesPerDir)
1229                     thisDir++;
1230                 if (thisDir >= maxDir)
1231                     printf("%s: can't find directory to move V%d\n", rn,
1232                            vFileNum);
1233                 else {
1234                     if (MoveCacheFile
1235                         (directory, dirNum, thisDir, thisFile->fileNum,
1236                          maxDir)) {
1237                         /* Cannot move.  Ignore this file??? */
1238                         /* XXX */
1239                     }
1240                 }
1241             }                   /* for each file to move */
1242         }                       /* for each directory */
1243
1244         /* Remove any directories >= maxDir -- they should be empty */
1245         for (; highDir >= maxDir; highDir--) {
1246             sprintf(fileToDelete, "D%d", highDir);
1247             UnlinkUnwantedFile(rn, fullpn_FileToDelete, fileToDelete);
1248         }
1249     }
1250
1251     /* dirNum < 0 */
1252     /*
1253      * Close the directory, return success.
1254      */
1255     if (afsd_debug)
1256         printf("%s: Closing cache directory.\n", rn);
1257     closedir(cdirp);
1258     return (0);
1259 }
1260
1261 char *
1262 CheckCacheBaseDir(char *dir)
1263 {
1264     struct stat statbuf;
1265
1266     if (!dir) {
1267         return "cache base dir not specified";
1268     }
1269     if (stat(dir, &statbuf) != 0) {
1270         return "unable to stat cache base directory";
1271     }
1272
1273     /* might want to check here for anything else goofy, like cache pointed at a non-dedicated directory, etc */
1274
1275 #ifdef AFS_LINUX24_ENV
1276     {
1277         int res;
1278         struct statfs statfsbuf;
1279
1280         res = statfs(dir, &statfsbuf);
1281         if (res != 0) {
1282             return "unable to statfs cache base directory";
1283         }
1284 #if !defined(AFS_LINUX26_ENV)
1285         if (statfsbuf.f_type == 0x52654973) {   /* REISERFS_SUPER_MAGIC */
1286             return "cannot use reiserfs as cache partition";
1287         } else if (statfsbuf.f_type == 0x58465342) {    /* XFS_SUPER_MAGIC */
1288             return "cannot use xfs as cache partition";
1289         } else if (statfsbuf.f_type == 0x01021994) {    /* TMPFS_SUPER_MAGIC */
1290             return "cannot use tmpfs as cache partition";
1291         } else if (statfsbuf.f_type != 0xEF53) {
1292             return "must use ext2 or ext3 for cache partition";
1293         }
1294 #endif
1295     }
1296 #endif
1297
1298 #ifdef AFS_HPUX_ENV
1299     {
1300         int res;
1301         struct statfs statfsbuf;
1302         char name[FSTYPSZ];
1303
1304         res = statfs(dir, &statfsbuf);
1305         if (res != 0) {
1306             return "unable to statfs cache base directory";
1307         }
1308
1309         if (sysfs(GETFSTYP, statfsbuf.f_fsid[1], name) != 0) {
1310             return "unable to determine filesystem type for cache base dir";
1311         }
1312
1313         if (strcmp(name, "hfs")) {
1314             return "can only use hfs filesystem for cache partition on hpux";
1315         }
1316     }
1317 #endif
1318
1319 #ifdef AFS_SUN5_ENV
1320     {
1321         FILE *vfstab;
1322         struct mnttab mnt;
1323         struct stat statmnt, statci;
1324
1325         if ((stat(dir, &statci) == 0)
1326             && ((vfstab = fopen(MNTTAB, "r")) != NULL)) {
1327             while (getmntent(vfstab, &mnt) == 0) {
1328                 if (strcmp(dir, mnt.mnt_mountp) != 0) {
1329                     char *cp;
1330                     int rdev = 0;
1331
1332                     if (cp = hasmntopt(&mnt, "dev="))
1333                         rdev =
1334                             (int)strtol(cp + strlen("dev="), (char **)NULL,
1335                                         16);
1336
1337                     if ((rdev == 0) && (stat(mnt.mnt_mountp, &statmnt) == 0))
1338                         rdev = statmnt.st_dev;
1339
1340                     if ((rdev == statci.st_dev)
1341                         && (hasmntopt(&mnt, "logging") != NULL)) {
1342
1343                         fclose(vfstab);
1344                         return
1345                             "mounting a multi-use partition which contains the AFS cache with the\n\"logging\" option may deadlock your system.\n\n";
1346                     }
1347                 }
1348             }
1349
1350             fclose(vfstab);
1351         }
1352     }
1353 #endif
1354
1355     return NULL;
1356 }
1357
1358 int
1359 SweepAFSCache(int *vFilesFound)
1360 {
1361     static char rn[] = "SweepAFSCache"; /*Routine name */
1362     int maxDir = (cacheFiles + nFilesPerDir - 1) / nFilesPerDir;
1363     int i;
1364
1365     *vFilesFound = 0;
1366
1367     if (cacheFlags & AFSCALL_INIT_MEMCACHE) {
1368         if (afsd_debug)
1369             printf("%s: Memory Cache, no cache sweep done\n", rn);
1370         return 0;
1371     }
1372
1373     if (cache_dir_list == NULL) {
1374         cache_dir_list = (int *)malloc(maxDir * sizeof(*cache_dir_list));
1375         if (cache_dir_list == NULL) {
1376             printf("%s: Malloc Failed!\n", rn);
1377             return (-1);
1378         }
1379         for (i = 0; i < maxDir; i++)
1380             cache_dir_list[i] = -1;     /* Does not exist */
1381     }
1382
1383     if (cache_dir_filelist == NULL) {
1384         cache_dir_filelist = (struct afsd_file_list **)
1385             malloc(maxDir * sizeof(*cache_dir_filelist));
1386         if (cache_dir_filelist == NULL) {
1387             printf("%s: Malloc Failed!\n", rn);
1388             return (-1);
1389         }
1390         memset(cache_dir_filelist, 0, maxDir * sizeof(*cache_dir_filelist));
1391     }
1392
1393     if (dir_for_V == NULL) {
1394         dir_for_V = (int *)malloc(cacheFiles * sizeof(*dir_for_V));
1395         if (dir_for_V == NULL) {
1396             printf("%s: Malloc Failed!\n", rn);
1397             return (-1);
1398         }
1399         for (i = 0; i < cacheFiles; i++)
1400             dir_for_V[i] = -1;  /* Does not exist */
1401     }
1402
1403     /* Note, setting dirNum to -2 here will cause cachefiles found in
1404      * the toplevel directory to be marked in directory "-2".  This
1405      * allows us to differentiate between 'file not seen' (-1) and
1406      * 'file seen in top-level' (-2).  Then when we try to move the
1407      * file into a subdirectory, we know it's in the top-level instead
1408      * of some other cache subdir.
1409      */
1410     return doSweepAFSCache(vFilesFound, cacheBaseDir, -2, maxDir);
1411 }
1412
1413 static int
1414 ConfigCell(struct afsconf_cell *aci, void *arock, struct afsconf_dir *adir)
1415 {
1416     int isHomeCell;
1417     int i, code;
1418     afs_int32 cellFlags = 0;
1419     afs_int32 hosts[MAXHOSTSPERCELL];
1420
1421     /* figure out if this is the home cell */
1422     isHomeCell = (strcmp(aci->name, LclCellName) == 0);
1423     if (!isHomeCell) {
1424         cellFlags = 2;          /* not home, suid is forbidden */
1425         if (enable_dynroot == 2)
1426             cellFlags |= 8; /* don't display foreign cells until looked up */
1427     }
1428     /* build address list */
1429     for (i = 0; i < MAXHOSTSPERCELL; i++)
1430         memcpy(&hosts[i], &aci->hostAddr[i].sin_addr, sizeof(afs_int32));
1431
1432     if (aci->linkedCell)
1433         cellFlags |= 4;         /* Flag that linkedCell arg exists,
1434                                  * for upwards compatibility */
1435
1436     /* configure one cell */
1437     code = afsd_call_syscall(AFSOP_ADDCELL2, hosts,     /* server addresses */
1438                         aci->name,      /* cell name */
1439                         cellFlags,      /* is this the home cell? */
1440                         aci->linkedCell);       /* Linked cell, if any */
1441     if (code)
1442         printf("Adding cell '%s': error %d\n", aci->name, code);
1443     return 0;
1444 }
1445
1446 static int
1447 ConfigCellAlias(struct afsconf_cellalias *aca,
1448                 void *arock, struct afsconf_dir *adir)
1449 {
1450     /* push the alias into the kernel */
1451     afsd_call_syscall(AFSOP_ADDCELLALIAS, aca->aliasName, aca->realName);
1452     return 0;
1453 }
1454
1455 static void
1456 AfsdbLookupHandler(void)
1457 {
1458     afs_int32 kernelMsg[64];
1459     char acellName[128];
1460     afs_int32 code;
1461     struct afsconf_cell acellInfo;
1462     int i;
1463
1464     kernelMsg[0] = 0;
1465     kernelMsg[1] = 0;
1466     acellName[0] = '\0';
1467
1468 #if defined(AFS_DARWIN_ENV) && !defined(AFS_ARM_DARWIN_ENV)
1469     /* Fork the event handler also. */
1470     code = fork();
1471     if (code == 0) {
1472         afsd_install_events();
1473         return;
1474     } else if (code != -1) {
1475         event_pid = code;
1476     }
1477 #endif
1478     while (1) {
1479         /* On some platforms you only get 4 args to an AFS call */
1480         int sizeArg = ((sizeof acellName) << 16) | (sizeof kernelMsg);
1481         code =
1482             afsd_call_syscall(AFSOP_AFSDB_HANDLER, acellName, kernelMsg, sizeArg);
1483         if (code) {             /* Something is wrong? */
1484             sleep(1);
1485             continue;
1486         }
1487
1488         if (*acellName == 1)    /* Shutting down */
1489             break;
1490
1491         code = afsconf_GetAfsdbInfo(acellName, 0, &acellInfo);
1492         if (code) {
1493             kernelMsg[0] = 0;
1494             kernelMsg[1] = 0;
1495         } else {
1496             kernelMsg[0] = acellInfo.numServers;
1497             if (acellInfo.timeout)
1498                 kernelMsg[1] = acellInfo.timeout - time(0);
1499             else
1500                 kernelMsg[1] = 0;
1501             for (i = 0; i < acellInfo.numServers; i++)
1502                 kernelMsg[i + 2] = acellInfo.hostAddr[i].sin_addr.s_addr;
1503             strncpy(acellName, acellInfo.name, sizeof(acellName));
1504             acellName[sizeof(acellName) - 1] = '\0';
1505         }
1506     }
1507 #ifdef AFS_DARWIN_ENV
1508     kill(event_pid, SIGTERM);
1509 #endif
1510 }
1511
1512 #ifdef AFS_NEW_BKG
1513 static void
1514 BkgHandler(void)
1515 {
1516     afs_int32 code;
1517     struct afs_uspc_param *uspc;
1518     char srcName[256];
1519     char dstName[256];
1520
1521     uspc = (struct afs_uspc_param *)malloc(sizeof(struct afs_uspc_param));
1522     memset(uspc, 0, sizeof(struct afs_uspc_param));
1523     memset(srcName, 0, sizeof(srcName));
1524     memset(dstName, 0, sizeof(dstName));
1525
1526     /* brscount starts at 0 */
1527     uspc->ts = -1;
1528
1529     while (1) {
1530         pid_t child = 0;
1531         int status;
1532         char srcpath[BUFSIZ];
1533         char dstpath[BUFSIZ];
1534
1535         /* pushing in a buffer this large */
1536         uspc->bufSz = 256;
1537
1538         code = afsd_call_syscall(AFSOP_BKG_HANDLER, uspc, srcName, dstName);
1539         if (code) {             /* Something is wrong? */
1540             if (code == -2) /* shutting down */
1541                 break;
1542
1543             sleep(1);
1544             uspc->retval = -1;
1545             continue;
1546         }
1547
1548         switch (uspc->reqtype) {
1549         case AFS_USPC_UMV:
1550             snprintf(srcpath, BUFSIZ, "/afs/.:mount/%d:%d:%d:%d/%s",
1551                      uspc->req.umv.sCell, uspc->req.umv.sVolume,
1552                      uspc->req.umv.sVnode, uspc->req.umv.sUnique, srcName);
1553             snprintf(dstpath, BUFSIZ, "/afs/.:mount/%d:%d:%d:%d/%s",
1554                      uspc->req.umv.dCell, uspc->req.umv.dVolume,
1555                      uspc->req.umv.dVnode, uspc->req.umv.dUnique, dstName);
1556             if ((child = fork()) == 0) {
1557                 /* first child does cp; second, rm. mv would re-enter. */
1558
1559                 switch (uspc->req.umv.idtype) {
1560                 case IDTYPE_UID:
1561                     if (setuid(uspc->req.umv.id) != 0) {
1562                         exit(-1);
1563                     }
1564                     break;
1565                 default:
1566                     exit(-1);
1567                     break; /* notreached */
1568                 }
1569                 execl("/bin/cp", "(afsd EXDEV helper)", "-PRp", "--", srcpath,
1570                       dstpath, (char *) NULL);
1571             }
1572             if (child == (pid_t) -1) {
1573                 uspc->retval = -1;
1574                 continue;
1575             }
1576
1577             if (waitpid(child, &status, 0) == -1)
1578                 uspc->retval = EIO;
1579             else if (WIFEXITED(status) != 0 && WEXITSTATUS(status) == 0) {
1580                 if ((child = fork()) == 0) {
1581                     switch (uspc->req.umv.idtype) {
1582                     case IDTYPE_UID:
1583                         if (setuid(uspc->req.umv.id) != 0) {
1584                             exit(-1);
1585                         }
1586                         break;
1587                     default:
1588                         exit(-1);
1589                         break; /* notreached */
1590                     }
1591                     execl("/bin/rm", "(afsd EXDEV helper)", "-rf", "--",
1592                           srcpath, (char *) NULL);
1593                 }
1594                 if (child == (pid_t) -1) {
1595                     uspc->retval = -1;
1596                     continue;
1597                 }
1598                 if (waitpid(child, &status, 0) == -1)
1599                     uspc->retval = EIO;
1600                 else if (WIFEXITED(status) != 0) {
1601                     /* rm exit status */
1602                     uspc->retval = WEXITSTATUS(status);
1603                 } else {
1604                     /* rm signal status */
1605                     uspc->retval = -(WTERMSIG(status));
1606                 }
1607             } else {
1608                 /* error from cp: exit or signal status */
1609                 uspc->retval = (WIFEXITED(status) != 0) ?
1610                     WEXITSTATUS(status) : -(WTERMSIG(status));
1611             }
1612             memset(srcName, 0, sizeof(srcName));
1613             memset(dstName, 0, sizeof(dstName));
1614             break;
1615
1616         default:
1617             /* unknown req type */
1618             uspc->retval = -1;
1619             break;
1620         }
1621     }
1622 }
1623 #endif
1624
1625 static void *
1626 afsdb_thread(void *rock)
1627 {
1628     /* Since the AFSDB lookup handler runs as a user process,
1629      * need to drop the controlling TTY, etc.
1630      */
1631     if (afsd_daemon(0, 0) == -1) {
1632         printf("Error starting AFSDB lookup handler: %s\n",
1633                strerror(errno));
1634         exit(1);
1635     }
1636     AfsdbLookupHandler();
1637     return NULL;
1638 }
1639
1640 static void *
1641 daemon_thread(void *rock)
1642 {
1643 #ifdef AFS_NEW_BKG
1644     /* Since the background daemon runs as a user process,
1645      * need to drop the controlling TTY, etc.
1646      */
1647     if (afsd_daemon(0, 0) == -1) {
1648         printf("Error starting background daemon: %s\n",
1649                strerror(errno));
1650         exit(1);
1651     }
1652     BkgHandler();
1653 #elif defined(AFS_AIX32_ENV)
1654     afsd_call_syscall(AFSOP_START_BKG, 0);
1655 #else
1656     afsd_call_syscall(AFSOP_START_BKG);
1657 #endif
1658     return NULL;
1659 }
1660
1661 #ifndef UKERNEL
1662 static void *
1663 rmtsysd_thread(void *rock)
1664 {
1665     rmtsysd();
1666     return NULL;
1667 }
1668 #endif /* !UKERNEL */
1669
1670 int
1671 mainproc(struct cmd_syndesc *as, void *arock)
1672 {
1673     afs_int32 code;             /*Result of fork() */
1674 #ifdef  AFS_SUN5_ENV
1675     struct stat st;
1676 #endif
1677 #ifdef AFS_SGI65_ENV
1678     struct sched_param sp;
1679 #endif
1680
1681 #ifdef AFS_SGI_VNODE_GLUE
1682     if (afs_init_kernel_config(-1) < 0) {
1683         printf("Can't determine NUMA configuration, not starting AFS.\n");
1684         exit(1);
1685     }
1686 #endif
1687
1688     /* call atoi on the appropriate parsed results */
1689     if (cmd_OptionAsInt(as, OPT_blocks, &cacheBlocks) == 0)
1690         sawCacheBlocks = 1;
1691
1692     if (cmd_OptionAsInt(as, OPT_files, &cacheFiles) == 0)
1693         filesSet = 1;
1694
1695     if (cmd_OptionAsString(as, OPT_rootvol, &rootVolume) == 0)
1696         rootVolSet = 1;
1697
1698     if (cmd_OptionAsInt(as, OPT_stat, &cacheStatEntries) == 0)
1699         sawCacheStatEntries = 1;
1700
1701     if (cmd_OptionPresent(as, OPT_memcache)) {
1702         cacheBaseDir = NULL;
1703         sawCacheBaseDir = 1;
1704         cacheFlags |= AFSCALL_INIT_MEMCACHE;
1705     }
1706
1707     if (cmd_OptionAsString(as, OPT_cachedir, &cacheBaseDir) == 0)
1708         sawCacheBaseDir = 1;
1709
1710     if (cmd_OptionAsString(as, OPT_mountdir, &afsd_cacheMountDir) == 0)
1711         sawCacheMountDir = 1;
1712
1713     cmd_OptionAsInt(as, OPT_daemons, &nDaemons);
1714
1715     afsd_verbose = cmd_OptionPresent(as, OPT_verbose);
1716
1717     if (cmd_OptionPresent(as, OPT_rmtsys)) {
1718         afsd_rmtsys = 1;
1719 #ifdef UKERNEL
1720         printf("-rmtsys not supported for UKERNEL\n");
1721         return -1;
1722 #endif
1723     }
1724
1725     if (cmd_OptionPresent(as, OPT_debug)) {
1726         afsd_debug = 1;
1727         afsd_verbose = 1;
1728     }
1729
1730     if (cmd_OptionAsInt(as, OPT_chunksize, &chunkSize) == 0) {
1731         if (chunkSize < 0 || chunkSize > 30) {
1732             printf
1733                 ("afsd:invalid chunk size (not in range 0-30), using default\n");
1734             chunkSize = 0;
1735         }
1736     }
1737
1738     if (cmd_OptionAsInt(as, OPT_dcache, &dCacheSize) == 0)
1739         sawDCacheSize = 1;
1740
1741     cmd_OptionAsInt(as, OPT_volumes, &vCacheSize);
1742
1743     if (cmd_OptionPresent(as, OPT_biods)) {
1744         /* -biods */
1745 #ifndef AFS_AIX32_ENV
1746         printf
1747             ("afsd: [-biods] currently only enabled for aix3.x VM supported systems\n");
1748 #else
1749         cmd_OptionAsInt(as, OPT_biods, &nBiods);
1750 #endif
1751     }
1752     cmd_OptionAsInt(as, OPT_prealloc, &preallocs);
1753
1754     if (cmd_OptionAsString(as, OPT_confdir, &confDir) == CMD_MISSING) {
1755         confDir = strdup(AFSDIR_CLIENT_ETC_DIRPATH);
1756     }
1757     sprintf(fullpn_CacheInfo, "%s/%s", confDir, CACHEINFOFILE);
1758
1759     if (cmd_OptionPresent(as, OPT_logfile)) {
1760         printf("afsd: Ignoring obsolete -logfile flag\n");
1761     }
1762
1763     afsd_CloseSynch = cmd_OptionPresent(as, OPT_waitclose);
1764
1765     if (cmd_OptionPresent(as, OPT_shutdown)) {
1766         /* -shutdown */
1767         afs_shutdown = 1;
1768         /*
1769          * Cold shutdown is the default
1770          */
1771         printf("afsd: Shutting down all afs processes and afs state\n");
1772         code = afsd_call_syscall(AFSOP_SHUTDOWN, 1);
1773         if (code) {
1774             printf("afsd: AFS still mounted; Not shutting down\n");
1775             exit(1);
1776         }
1777         exit(0);
1778     }
1779
1780     enable_peer_stats = cmd_OptionPresent(as, OPT_peerstats);
1781     enable_process_stats = cmd_OptionPresent(as, OPT_processstats);
1782
1783     if (cmd_OptionPresent(as, OPT_memallocsleep)) {
1784         printf("afsd: -mem_alloc_sleep is deprecated -- ignored\n");
1785     }
1786
1787     enable_afsdb = cmd_OptionPresent(as, OPT_afsdb);
1788     if (cmd_OptionPresent(as, OPT_filesdir)) {
1789         /* -files_per_subdir */
1790         int res;
1791         cmd_OptionAsInt(as, OPT_filesdir, &res);
1792         if (res < 10 || res > (1 << 30)) {
1793             printf
1794                 ("afsd:invalid number of files per subdir, \"%s\". Ignored\n",
1795                  as->parms[25].items->data);
1796         } else {
1797             nFilesPerDir = res;
1798         }
1799     }
1800     enable_dynroot = cmd_OptionPresent(as, OPT_dynroot);
1801
1802     if (cmd_OptionPresent(as, OPT_fakestat)) {
1803         enable_fakestat = 2;
1804     }
1805     if (cmd_OptionPresent(as, OPT_fakestatall)) {
1806         enable_fakestat = 1;
1807     }
1808     if (cmd_OptionPresent(as, OPT_settime)) {
1809         /* -settime */
1810         printf("afsd: -settime ignored\n");
1811         printf("afsd: the OpenAFS client no longer sets the system time; "
1812                "please use NTP or\n");
1813         printf("afsd: another such system to synchronize client time\n");
1814     }
1815
1816     enable_nomount = cmd_OptionPresent(as, OPT_nomount);
1817     enable_backuptree = cmd_OptionPresent(as, OPT_backuptree);
1818     enable_rxbind = cmd_OptionPresent(as, OPT_rxbind);
1819
1820     /* set rx_extraPackets */
1821     if (cmd_OptionPresent(as, OPT_rxpck)) {
1822         /* -rxpck */
1823         int rxpck;
1824         cmd_OptionAsInt(as, OPT_rxpck, &rxpck);
1825         printf("afsd: set rxpck = %d\n", rxpck);
1826         code = afsd_call_syscall(AFSOP_SET_RXPCK, rxpck);
1827         if (code) {
1828             printf("afsd: failed to set rxpck\n");
1829             exit(1);
1830         }
1831     }
1832     if (cmd_OptionPresent(as, OPT_splitcache)) {
1833         char *c;
1834         char *var = NULL;
1835
1836         cmd_OptionAsString(as, OPT_splitcache, &var);
1837
1838         if (var == NULL || ((c = strchr(var, '/')) == NULL))
1839             printf
1840                 ("ignoring splitcache (specify as RW/RO percentages: 60/40)\n");
1841         else {
1842             ropct = atoi(c + 1);
1843             *c = '\0';
1844             rwpct = atoi(var);
1845             if ((rwpct != 0) && (ropct != 0) && (ropct + rwpct == 100)) {
1846                 /* -splitcache */
1847                 enable_splitcache = 1;
1848             }
1849         }
1850         free(var);
1851     }
1852     if (cmd_OptionPresent(as, OPT_nodynvcache)) {
1853 #ifdef AFS_MAXVCOUNT_ENV
1854        afsd_dynamic_vcaches = 0;
1855 #else
1856        printf("afsd: Error toggling flag, dynamically allocated vcaches not supported on your platform\n");
1857        exit(1);
1858 #endif
1859     }
1860 #ifdef AFS_MAXVCOUNT_ENV
1861     else {
1862        /* -dynamic-vcaches */
1863        afsd_dynamic_vcaches = 1;
1864     }
1865
1866     if (afsd_verbose)
1867     printf("afsd: %s dynamically allocated vcaches\n", ( afsd_dynamic_vcaches ? "enabling" : "disabling" ));
1868 #endif
1869
1870     cmd_OptionAsInt(as, OPT_rxmaxmtu, &rxmaxmtu);
1871
1872     if (cmd_OptionPresent(as, OPT_dynrootsparse)) {
1873         enable_dynroot = 2;
1874     }
1875
1876     cmd_OptionAsInt(as, OPT_rxmaxfrags, &rxmaxfrags);
1877
1878     /* parse cacheinfo file if this is a diskcache */
1879     if (ParseCacheInfoFile()) {
1880         exit(1);
1881     }
1882
1883     return 0;
1884 }
1885
1886 int
1887 afsd_run(void)
1888 {
1889     static char rn[] = "afsd";  /*Name of this routine */
1890     struct afsconf_dir *cdir;   /* config dir */
1891     int lookupResult;           /*Result of GetLocalCellName() */
1892     int i;
1893     afs_int32 code;             /*Result of fork() */
1894     char *fsTypeMsg = NULL;
1895     int cacheIteration;         /*How many times through cache verification */
1896     int vFilesFound;            /*How many data cache files were found in sweep */
1897     int currVFile;              /*Current AFS cache file number passed in */
1898
1899         /*
1900      * Pull out all the configuration info for the workstation's AFS cache and
1901      * the cellular community we're willing to let our users see.
1902      */
1903     cdir = afsconf_Open(confDir);
1904     if (!cdir) {
1905         printf("afsd: some file missing or bad in %s\n", confDir);
1906         exit(1);
1907     }
1908
1909     lookupResult =
1910         afsconf_GetLocalCell(cdir, LclCellName, sizeof(LclCellName));
1911     if (lookupResult) {
1912         printf("%s: Can't get my home cell name!  [Error is %d]\n", rn,
1913                lookupResult);
1914     } else {
1915         if (afsd_verbose)
1916             printf("%s: My home cell is '%s'\n", rn, LclCellName);
1917     }
1918
1919     if (!enable_nomount) {
1920         if (afsd_check_mount(rn, afsd_cacheMountDir)) {
1921             return -1;
1922         }
1923     }
1924
1925     /* do some random computations in memcache case to get things to work
1926      * reasonably no matter which parameters you set.
1927      */
1928     if (cacheFlags & AFSCALL_INIT_MEMCACHE) {
1929         /* memory cache: size described either as blocks or dcache entries, but
1930          * not both.
1931          */
1932         if (filesSet) {
1933             fprintf(stderr, "%s: -files ignored with -memcache\n", rn);
1934         }
1935         if (sawDCacheSize) {
1936             if (chunkSize == 0) {
1937                 chunkSize = 13; /* 8k default chunksize for memcache */
1938             }
1939             if (sawCacheBlocks) {
1940                 printf
1941                     ("%s: can't set cache blocks and dcache size simultaneously when diskless.\n",
1942                      rn);
1943                 exit(1);
1944             }
1945             /* compute the cache size based on # of chunks times the chunk size */
1946             i = (1 << chunkSize);       /* bytes per chunk */
1947             cacheBlocks = i * dCacheSize;
1948             sawCacheBlocks = 1; /* so that ParseCacheInfoFile doesn't overwrite */
1949         } else {
1950             if (chunkSize == 0) {
1951                 /* Try to autotune the memcache chunksize based on size
1952                  * of memcache. This is done on the assumption that approx
1953                  * 1024 chunks is suitable, it's a balance between enough
1954                  * chunks to be useful and ramping up nicely when using larger
1955                  * memcache to improve bulk read/write performance
1956                  */
1957                 for (i = 14;
1958                      i <= 21 && (1 << i) / 1024 < (cacheBlocks / 1024); i++);
1959                 chunkSize = i - 1;
1960             }
1961             /* compute the dcache size from overall cache size and chunk size */
1962             if (chunkSize > 10) {
1963                 dCacheSize = (cacheBlocks >> (chunkSize - 10));
1964             } else if (chunkSize < 10) {
1965                 dCacheSize = (cacheBlocks << (10 - chunkSize));
1966             } else {
1967                 dCacheSize = cacheBlocks;
1968             }
1969             /* don't have to set sawDCacheSize here since it isn't overwritten
1970              * by ParseCacheInfoFile.
1971              */
1972         }
1973         if (afsd_verbose)
1974             printf("%s: chunkSize autotuned to %d\n", rn, chunkSize);
1975
1976         /* kernel computes # of dcache entries as min of cacheFiles and
1977          * dCacheSize, so we now make them equal.
1978          */
1979         cacheFiles = dCacheSize;
1980     } else {
1981         /* Disk cache:
1982          * Compute the number of cache files based on cache size,
1983          * but only if -files isn't given on the command line.
1984          * Don't let # files be so small as to prevent full utilization
1985          * of the cache unless user has explicitly asked for it.
1986          */
1987         if (chunkSize == 0) {
1988             /* Set chunksize to 256kB - 1MB depending on cache size */
1989             if (cacheBlocks < 500000) {
1990                 chunkSize = 18;
1991             } else if (cacheBlocks < 1000000) {
1992                 chunkSize = 19;
1993             } else {
1994                 chunkSize = 20;
1995             }
1996         }
1997
1998         if (!filesSet) {
1999             cacheFiles = cacheBlocks / 32;      /* Assume 32k avg filesize */
2000
2001             cacheFiles = max(cacheFiles, 1000);
2002
2003             /* Always allow more files than chunks.  Presume average V-file
2004              * is ~67% of a chunk...  (another guess, perhaps Honeyman will
2005              * have a grad student write a paper).  i is KILOBYTES.
2006              */
2007             i = 1 << (chunkSize < 10 ? 0 : chunkSize - 10);
2008             cacheFiles = max(cacheFiles, 1.5 * (cacheBlocks / i));
2009
2010             /* never permit more files than blocks, while leaving space for
2011              * VolumeInfo and CacheItems files.  VolumeInfo is usually 20K,
2012              * CacheItems is 50 Bytes / file (== 1K/20)
2013              */
2014 #define CACHEITMSZ (cacheFiles / 20)
2015 #define VOLINFOSZ 50            /* 40kB has been seen, be conservative */
2016 #define CELLINFOSZ 4            /* Assuming disk block size is 4k ... */
2017 #define INFOSZ (VOLINFOSZ+CELLINFOSZ+CACHEITMSZ)
2018
2019             /* Sanity check: If the obtained number of disk cache files
2020              * is larger than the number of available (4k) disk blocks, we're
2021              * doing something wrong. Fail hard so we can fix the bug instead
2022              * of silently hiding it like before */
2023
2024             if (cacheFiles > (cacheBlocks - INFOSZ) / 4) {
2025                 fprintf(stderr,
2026                         "%s: ASSERT: cacheFiles %d  diskblocks %d\n",
2027                         rn, cacheFiles, (cacheBlocks - INFOSZ) / 4);
2028                 exit(1);
2029             }
2030             if (cacheFiles < 100)
2031                 fprintf(stderr, "%s: WARNING: cache probably too small!\n",
2032                         rn);
2033
2034             if (afsd_verbose)
2035                 printf("%s: cacheFiles autotuned to %d\n", rn, cacheFiles);
2036         }
2037 #if 0
2038        /* This actually needs to
2039           1) use powers of 2
2040           2) not second-guess when a chunksize comes from the command line
2041           3) be less, um, small. 2^2??
2042        */
2043         /* Sanity check chunkSize */
2044         i = max(cacheBlocks / 1000, cacheBlocks / cacheFiles);
2045         chunkSize = min(chunkSize, i);
2046         chunkSize = max(chunkSize, 2);
2047         if (afsd_verbose)
2048             printf("%s: chunkSize autotuned to %d\n", rn, chunkSize);
2049 #endif
2050
2051         if (!sawDCacheSize) {
2052             dCacheSize = cacheFiles / 2;
2053             if (dCacheSize > 10000) {
2054                 dCacheSize = 10000;
2055             }
2056             if (dCacheSize < 2000) {
2057                 dCacheSize = 2000;
2058             }
2059             if (afsd_verbose)
2060                 printf("%s: dCacheSize autotuned to %d\n", rn, dCacheSize);
2061         }
2062     }
2063     if (!sawCacheStatEntries) {
2064         if (chunkSize <= 13) {
2065             cacheStatEntries = dCacheSize / 4;
2066         } else if (chunkSize >= 16) {
2067             cacheStatEntries = dCacheSize * 1.5;
2068         } else {
2069             cacheStatEntries = dCacheSize;
2070         }
2071         if (afsd_verbose)
2072             printf("%s: cacheStatEntries autotuned to %d\n", rn,
2073                    cacheStatEntries);
2074     }
2075
2076 #if !defined(AFS_CACHE_VNODE_PATH) && !defined(AFS_LINUX26_ENV)
2077     /*
2078      * Create and zero the inode table for the desired cache files.
2079      */
2080     inode_for_V = (AFSD_INO_T *) malloc(cacheFiles * sizeof(AFSD_INO_T));
2081     if (inode_for_V == (AFSD_INO_T *) 0) {
2082         printf
2083             ("%s: malloc() failed for cache file inode table with %d entries.\n",
2084              rn, cacheFiles);
2085         exit(1);
2086     }
2087     memset(inode_for_V, '\0', (cacheFiles * sizeof(AFSD_INO_T)));
2088     if (afsd_debug)
2089         printf("%s: %d inode_for_V entries at 0x%x, %lu bytes\n", rn,
2090                cacheFiles, inode_for_V, (cacheFiles * sizeof(AFSD_INO_T)));
2091 #endif
2092
2093     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE)) {
2094         /*
2095          * Set up all the pathnames we'll need for later.
2096          */
2097         sprintf(fullpn_DCacheFile, "%s/%s", cacheBaseDir, DCACHEFILE);
2098         sprintf(fullpn_VolInfoFile, "%s/%s", cacheBaseDir, VOLINFOFILE);
2099         sprintf(fullpn_CellInfoFile, "%s/%s", cacheBaseDir, CELLINFOFILE);
2100         sprintf(fullpn_VFile, "%s/", cacheBaseDir);
2101         vFilePtr = fullpn_VFile + strlen(fullpn_VFile);
2102
2103         fsTypeMsg = CheckCacheBaseDir(cacheBaseDir);
2104         if (fsTypeMsg) {
2105 #ifdef AFS_SUN5_ENV
2106             printf("%s: WARNING: Cache dir check failed (%s)\n", rn, fsTypeMsg);
2107 #else
2108             printf("%s: ERROR: Cache dir check failed (%s)\n", rn, fsTypeMsg);
2109             exit(1);
2110 #endif
2111         }
2112     }
2113
2114     /*
2115      * Set up all the kernel processes needed for AFS.
2116      */
2117 #ifdef mac2
2118     setpgrp(getpid(), 0);
2119 #endif /* mac2 */
2120
2121     /*
2122      * Set the primary cell name.
2123      */
2124     afsd_call_syscall(AFSOP_SET_THISCELL, LclCellName);
2125
2126     /* Initialize RX daemons and services */
2127
2128     /* initialize the rx random number generator from user space */
2129     {
2130         /* parse multihomed address files */
2131         afs_uint32 addrbuf[MAXIPADDRS], maskbuf[MAXIPADDRS],
2132             mtubuf[MAXIPADDRS];
2133         char reason[1024];
2134         code =
2135             parseNetFiles(addrbuf, maskbuf, mtubuf, MAXIPADDRS, reason,
2136                           AFSDIR_CLIENT_NETINFO_FILEPATH,
2137                           AFSDIR_CLIENT_NETRESTRICT_FILEPATH);
2138         if (code > 0) {
2139             if (enable_rxbind)
2140                 code = code | 0x80000000;
2141                 afsd_call_syscall(AFSOP_ADVISEADDR, code, addrbuf, maskbuf, mtubuf);
2142         } else
2143             printf("ADVISEADDR: Error in specifying interface addresses:%s\n",
2144                    reason);
2145     }
2146
2147     /* Set realtime priority for most threads to same as for biod's. */
2148     afsd_set_afsd_rtpri();
2149
2150     /* Start listener, then callback listener. Lastly, start rx event daemon.
2151      * Change in ordering is so that Linux port has socket fd in listener
2152      * process.
2153      * preallocs are passed for both listener and callback server. Only
2154      * the one which actually does the initialization uses them though.
2155      */
2156     if (preallocs < cacheStatEntries + 50)
2157         preallocs = cacheStatEntries + 50;
2158 #ifdef RXK_LISTENER_ENV
2159     if (afsd_verbose)
2160         printf("%s: Forking rx listener daemon.\n", rn);
2161 # ifdef AFS_SUN510_ENV
2162     fork_rx_syscall_wait(rn, AFSOP_RXLISTENER_DAEMON, preallocs,
2163                          enable_peer_stats, enable_process_stats);
2164 # else /* !AFS_SUN510_ENV */
2165     fork_rx_syscall(rn, AFSOP_RXLISTENER_DAEMON, preallocs, enable_peer_stats,
2166                     enable_process_stats);
2167 # endif /* !AFS_SUN510_ENV */
2168 #endif
2169     if (afsd_verbose)
2170         printf("%s: Forking rx callback listener.\n", rn);
2171 #ifndef RXK_LISTENER_ENV
2172     fork_rx_syscall(rn, AFSOP_START_RXCALLBACK, preallocs, enable_peer_stats,
2173                     enable_process_stats);
2174 #else
2175     fork_syscall(rn, AFSOP_START_RXCALLBACK, preallocs);
2176 #endif
2177 #if defined(AFS_SUN5_ENV) || defined(RXK_LISTENER_ENV) || defined(RXK_UPCALL_ENV)
2178     if (afsd_verbose)
2179         printf("%s: Forking rxevent daemon.\n", rn);
2180     fork_rx_syscall(rn, AFSOP_RXEVENT_DAEMON);
2181 #endif
2182
2183     if (enable_afsdb) {
2184         if (afsd_verbose)
2185             printf("%s: Forking AFSDB lookup handler.\n", rn);
2186         afsd_fork(0, afsdb_thread, NULL);
2187     }
2188     code = afsd_call_syscall(AFSOP_BASIC_INIT, 1);
2189     if (code) {
2190         printf("%s: Error %d in basic initialization.\n", rn, code);
2191         exit(1);
2192     }
2193
2194     /*
2195      * Tell the kernel some basic information about the workstation's cache.
2196      */
2197     if (afsd_verbose)
2198         printf
2199             ("%s: Calling AFSOP_CACHEINIT: %d stat cache entries, %d optimum cache files, %d blocks in the cache, flags = 0x%x, dcache entries %d\n",
2200              rn, cacheStatEntries, cacheFiles, cacheBlocks, cacheFlags,
2201              dCacheSize);
2202     memset(&cparams, '\0', sizeof(cparams));
2203     cparams.cacheScaches = cacheStatEntries;
2204     cparams.cacheFiles = cacheFiles;
2205     cparams.cacheBlocks = cacheBlocks;
2206     cparams.cacheDcaches = dCacheSize;
2207     cparams.cacheVolumes = vCacheSize;
2208     cparams.chunkSize = chunkSize;
2209     cparams.setTimeFlag = 0;
2210     cparams.memCacheFlag = cacheFlags;
2211     cparams.dynamic_vcaches = afsd_dynamic_vcaches;
2212         afsd_call_syscall(AFSOP_CACHEINIT, &cparams);
2213
2214     /* do it before we init the cache inodes */
2215     if (enable_splitcache) {
2216         afsd_call_syscall(AFSOP_BUCKETPCT, 1, rwpct);
2217         afsd_call_syscall(AFSOP_BUCKETPCT, 2, ropct);
2218     }
2219
2220     if (afsd_CloseSynch)
2221         afsd_call_syscall(AFSOP_CLOSEWAIT);
2222
2223     /*
2224      * Sweep the workstation AFS cache directory, remembering the inodes of
2225      * valid files and deleting extraneous files.  Keep sweeping until we
2226      * have the right number of data cache files or we've swept too many
2227      * times.
2228      *
2229      * This also creates files in the cache directory like VolumeItems and
2230      * CellItems, and thus must be ran before those are sent to the kernel.
2231      */
2232     if (afsd_verbose)
2233         printf("%s: Sweeping workstation's AFS cache directory.\n", rn);
2234     cacheIteration = 0;
2235     /* Memory-cache based system doesn't need any of this */
2236     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE)) {
2237         do {
2238             cacheIteration++;
2239             if (SweepAFSCache(&vFilesFound)) {
2240                 printf("%s: Error on sweep %d of workstation AFS cache \
2241                        directory.\n", rn, cacheIteration);
2242                 exit(1);
2243             }
2244             if (afsd_verbose)
2245                 printf
2246                     ("%s: %d out of %d data cache files found in sweep %d.\n",
2247                      rn, vFilesFound, cacheFiles, cacheIteration);
2248         } while ((vFilesFound < cacheFiles)
2249                  && (cacheIteration < MAX_CACHE_LOOPS));
2250     } else if (afsd_verbose)
2251         printf("%s: Using memory cache, not swept\n", rn);
2252
2253     /*
2254      * Pass the kernel the name of the workstation cache file holding the
2255      * dcache entries.
2256      */
2257     if (afsd_debug)
2258         printf("%s: Calling AFSOP_CACHEINFO: dcache file is '%s'\n", rn,
2259                fullpn_DCacheFile);
2260     /* once again, meaningless for a memory-based cache. */
2261     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE))
2262         afsd_call_syscall(AFSOP_CACHEINFO, fullpn_DCacheFile);
2263
2264     /*
2265      * Pass the kernel the name of the workstation cache file holding the
2266      * cell information.
2267      */
2268     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE)) {
2269         if (afsd_debug)
2270             printf("%s: Calling AFSOP_CELLINFO: cell info file is '%s'\n", rn,
2271                    fullpn_CellInfoFile);
2272         afsd_call_syscall(AFSOP_CELLINFO, fullpn_CellInfoFile);
2273     }
2274
2275     if (rxmaxfrags) {
2276         if (afsd_verbose)
2277             printf("%s: Setting rxmaxfrags in kernel = %d\n", rn, rxmaxfrags);
2278         code = afsd_call_syscall(AFSOP_SET_RXMAXFRAGS, rxmaxfrags);
2279         if (code)
2280             printf("%s: Error seting rxmaxfrags\n", rn);
2281     }
2282
2283     if (rxmaxmtu) {
2284         if (afsd_verbose)
2285             printf("%s: Setting rxmaxmtu in kernel = %d\n", rn, rxmaxmtu);
2286         code = afsd_call_syscall(AFSOP_SET_RXMAXMTU, rxmaxmtu);
2287         if (code)
2288             printf("%s: Error seting rxmaxmtu\n", rn);
2289     }
2290
2291     if (enable_dynroot) {
2292         if (afsd_verbose)
2293             printf("%s: Enabling dynroot support in kernel%s.\n", rn,
2294                    (enable_dynroot==2)?", not showing cells.":"");
2295         code = afsd_call_syscall(AFSOP_SET_DYNROOT, 1);
2296         if (code)
2297             printf("%s: Error enabling dynroot support.\n", rn);
2298     }
2299
2300     if (enable_fakestat) {
2301         if (afsd_verbose)
2302             printf("%s: Enabling fakestat support in kernel%s.\n", rn,
2303                    (enable_fakestat==2)?" for all mountpoints."
2304                    :" for crosscell mountpoints");
2305         code = afsd_call_syscall(AFSOP_SET_FAKESTAT, enable_fakestat);
2306         if (code)
2307             printf("%s: Error enabling fakestat support.\n", rn);
2308     }
2309
2310     if (enable_backuptree) {
2311         if (afsd_verbose)
2312             printf("%s: Enabling backup tree support in kernel.\n", rn);
2313         code = afsd_call_syscall(AFSOP_SET_BACKUPTREE, enable_backuptree);
2314         if (code)
2315             printf("%s: Error enabling backup tree support.\n", rn);
2316     }
2317
2318     /*
2319      * Tell the kernel about each cell in the configuration.
2320      */
2321     afsconf_CellApply(cdir, ConfigCell, NULL);
2322     afsconf_CellAliasApply(cdir, ConfigCellAlias, NULL);
2323
2324     /* Initialize AFS daemon threads. */
2325     if (afsd_verbose)
2326         printf("%s: Forking AFS daemon.\n", rn);
2327     fork_syscall(rn, AFSOP_START_AFS);
2328
2329     if (afsd_verbose)
2330         printf("%s: Forking Check Server Daemon.\n", rn);
2331     fork_syscall(rn, AFSOP_START_CS);
2332
2333     if (afsd_verbose)
2334         printf("%s: Forking %d background daemons.\n", rn, nDaemons);
2335 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
2336     /* Add one because for sgi we always "steal" the first daemon for a
2337      * different task if we only have a 4K stack.
2338      */
2339     nDaemons++;
2340 #endif
2341     for (i = 0; i < nDaemons; i++) {
2342         afsd_fork(0, daemon_thread, NULL);
2343     }
2344 #ifdef  AFS_AIX32_ENV
2345     if (!sawBiod)
2346         nBiods = nDaemons * 2;
2347     if (nBiods < 5)
2348         nBiods = 5;
2349     for (i = 0; i < nBiods; i++) {
2350         fork_syscall(rn, AFSOP_START_BKG, nBiods);
2351     }
2352 #endif
2353
2354     /*
2355      * If the root volume has been explicitly set, tell the kernel.
2356      */
2357     if (rootVolSet) {
2358         if (afsd_verbose)
2359             printf("%s: Calling AFSOP_ROOTVOLUME with '%s'\n", rn,
2360                    rootVolume);
2361         afsd_call_syscall(AFSOP_ROOTVOLUME, rootVolume);
2362     }
2363
2364     /*
2365      * Pass the kernel the name of the workstation cache file holding the
2366      * volume information.
2367      */
2368     if (afsd_debug)
2369         printf("%s: Calling AFSOP_VOLUMEINFO: volume info file is '%s'\n", rn,
2370                fullpn_VolInfoFile);
2371     /* once again, meaningless for a memory-based cache. */
2372     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE))
2373         afsd_call_syscall(AFSOP_VOLUMEINFO, fullpn_VolInfoFile);
2374
2375     /*
2376      * Give the kernel the names of the AFS files cached on the workstation's
2377      * disk.
2378      */
2379     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE)) {
2380         int nocachefile = 0;
2381         if (afsd_debug)
2382             printf
2383                 ("%s: Calling AFSOP_CACHEFILE for each of the %d files in '%s'\n",
2384                  rn, cacheFiles, cacheBaseDir);
2385         /* ... and again ... */
2386         for (currVFile = 0; currVFile < cacheFiles; currVFile++) {
2387             if (!nocachefile) {
2388                 sprintf(fullpn_VFile, "%s/D%d/V%d", cacheBaseDir, dir_for_V[currVFile], currVFile);
2389                 code = afsd_call_syscall(AFSOP_CACHEFILE, fullpn_VFile);
2390                 if (code) {
2391                     if (currVFile == 0) {
2392                         if (afsd_debug)
2393                             printf
2394                                 ("%s: Calling AFSOP_CACHEINODE for each of the %d files in '%s'\n",
2395                                  rn, cacheFiles, cacheBaseDir);
2396                         nocachefile = 1;
2397                     } else {
2398                         printf
2399                             ("%s: Error calling AFSOP_CACHEFILE for '%s'\n",
2400                              rn, fullpn_VFile);
2401                         exit(1);
2402                     }
2403                 } else {
2404                     continue;
2405                 }
2406                 /* fall through to setup-by-inode */
2407             }
2408 #ifdef AFS_SGI62_ENV
2409             afsd_call_syscall(AFSOP_CACHEINODE,
2410                          (afs_uint32) (inode_for_V[currVFile] >> 32),
2411                          (afs_uint32) (inode_for_V[currVFile] & 0xffffffff));
2412 #elif !(defined(AFS_LINUX26_ENV) || defined(AFS_CACHE_VNODE_PATH))
2413             afsd_call_syscall(AFSOP_CACHEINODE, inode_for_V[currVFile]);
2414 #else
2415             printf
2416                 ("%s: Error calling AFSOP_CACHEINODE: not configured\n",
2417                  rn);
2418             exit(1);
2419 #endif
2420         }
2421     }
2422     /*end for */
2423     /*
2424      * All the necessary info has been passed into the kernel to run an AFS
2425      * system.  Give the kernel our go-ahead.
2426      */
2427     if (afsd_debug)
2428         printf("%s: Calling AFSOP_GO with cacheSetTime = %d\n", rn,
2429                0);
2430         afsd_call_syscall(AFSOP_GO, 0);
2431
2432     /*
2433      * At this point, we have finished passing the kernel all the info
2434      * it needs to set up the AFS.  Mount the AFS root.
2435      */
2436     printf("%s: All AFS daemons started.\n", rn);
2437
2438     if (afsd_verbose)
2439         printf("%s: Forking trunc-cache daemon.\n", rn);
2440     fork_syscall(rn, AFSOP_START_TRUNCDAEMON);
2441
2442     if (!enable_nomount) {
2443         afsd_mount_afs(rn, afsd_cacheMountDir);
2444     }
2445
2446 #ifndef UKERNEL
2447     if (afsd_rmtsys) {
2448         if (afsd_verbose)
2449             printf("%s: Forking 'rmtsys' daemon.\n", rn);
2450         afsd_fork(0, rmtsysd_thread, NULL);
2451     }
2452 #endif /* !UKERNEL */
2453     /*
2454      * Exit successfully.
2455      */
2456     return 0;
2457 }
2458
2459 #include "AFS_component_version_number.c"
2460
2461 void
2462 afsd_init(void)
2463 {
2464     struct cmd_syndesc *ts;
2465
2466     ts = cmd_CreateSyntax(NULL, mainproc, NULL, "start AFS");
2467
2468     /* 0 - 10 */
2469     cmd_AddParmAtOffset(ts, OPT_blocks, "-blocks", CMD_SINGLE,
2470                         CMD_OPTIONAL, "1024 byte blocks in cache");
2471     cmd_AddParmAtOffset(ts, OPT_files, "-files", CMD_SINGLE,
2472                         CMD_OPTIONAL, "files in cache");
2473     cmd_AddParmAtOffset(ts, OPT_rootvol, "-rootvol", CMD_SINGLE,
2474                         CMD_OPTIONAL, "name of AFS root volume");
2475     cmd_AddParmAtOffset(ts, OPT_stat, "-stat", CMD_SINGLE,
2476                         CMD_OPTIONAL, "number of stat entries");
2477     cmd_AddParmAtOffset(ts, OPT_memcache, "-memcache", CMD_FLAG,
2478                         CMD_OPTIONAL, "run diskless");
2479     cmd_AddParmAtOffset(ts, OPT_cachedir, "-cachedir", CMD_SINGLE,
2480                         CMD_OPTIONAL, "cache directory");
2481     cmd_AddParmAtOffset(ts, OPT_mountdir, "-mountdir", CMD_SINGLE,
2482                         CMD_OPTIONAL, "mount location");
2483     cmd_AddParmAtOffset(ts, OPT_daemons, "-daemons", CMD_SINGLE,
2484                         CMD_OPTIONAL, "number of daemons to use");
2485     cmd_AddParmAtOffset(ts, OPT_nosettime, "-nosettime", CMD_FLAG,
2486                         CMD_OPTIONAL, "don't set the time");
2487     cmd_AddParmAtOffset(ts, OPT_verbose, "-verbose", CMD_FLAG,
2488                         CMD_OPTIONAL, "display lots of information");
2489     cmd_AddParmAtOffset(ts, OPT_rmtsys, "-rmtsys", CMD_FLAG,
2490                         CMD_OPTIONAL, "start NFS rmtsysd program");
2491     cmd_AddParmAtOffset(ts, OPT_debug, "-debug", CMD_FLAG,
2492                         CMD_OPTIONAL, "display debug info");
2493     cmd_AddParmAtOffset(ts, OPT_chunksize, "-chunksize", CMD_SINGLE,
2494                         CMD_OPTIONAL, "log(2) of chunk size");
2495     cmd_AddParmAtOffset(ts, OPT_dcache, "-dcache", CMD_SINGLE,
2496                         CMD_OPTIONAL, "number of dcache entries");
2497     cmd_AddParmAtOffset(ts, OPT_volumes, "-volumes", CMD_SINGLE,
2498                         CMD_OPTIONAL, "number of volume entries");
2499     cmd_AddParmAtOffset(ts, OPT_biods, "-biods", CMD_SINGLE,
2500                         CMD_OPTIONAL, "number of bkg I/O daemons (aix vm)");
2501     cmd_AddParmAtOffset(ts, OPT_prealloc, "-prealloc", CMD_SINGLE,
2502                         CMD_OPTIONAL, "number of 'small' preallocated blocks");
2503     cmd_AddParmAtOffset(ts, OPT_confdir, "-confdir", CMD_SINGLE,
2504                         CMD_OPTIONAL, "configuration directory");
2505     cmd_AddParmAtOffset(ts, OPT_logfile, "-logfile", CMD_SINGLE,
2506                         CMD_OPTIONAL, "Place to keep the CM log");
2507     cmd_AddParmAtOffset(ts, OPT_waitclose, "-waitclose", CMD_FLAG,
2508                         CMD_OPTIONAL, "make close calls synchronous");
2509     cmd_AddParmAtOffset(ts, OPT_shutdown, "-shutdown", CMD_FLAG,
2510                         CMD_OPTIONAL, "Shutdown all afs state");
2511     cmd_AddParmAtOffset(ts, OPT_peerstats, "-enable_peer_stats", CMD_FLAG,
2512                         CMD_OPTIONAL | CMD_HIDE,
2513                         "Collect rpc statistics by peer");
2514     cmd_AddParmAtOffset(ts, OPT_processstats, "-enable_process_stats",
2515                         CMD_FLAG, CMD_OPTIONAL | CMD_HIDE,
2516                         "Collect rpc statistics for this process");
2517     cmd_AddParmAtOffset(ts, OPT_memallocsleep, "-mem_alloc_sleep",
2518                         CMD_FLAG, CMD_OPTIONAL | CMD_HIDE,
2519                         "Allow sleeps when allocating memory cache");
2520     cmd_AddParmAtOffset(ts, OPT_afsdb, "-afsdb", CMD_FLAG,
2521                         CMD_OPTIONAL, "Enable AFSDB support");
2522     cmd_AddParmAtOffset(ts, OPT_filesdir, "-files_per_subdir", CMD_SINGLE,
2523                         CMD_OPTIONAL,
2524                         "log(2) of the number of cache files per "
2525                         "cache subdirectory");
2526     cmd_AddParmAtOffset(ts, OPT_dynroot, "-dynroot", CMD_FLAG,
2527                         CMD_OPTIONAL, "Enable dynroot support");
2528     cmd_AddParmAtOffset(ts, OPT_fakestat, "-fakestat", CMD_FLAG,
2529                         CMD_OPTIONAL,
2530                         "Enable fakestat support for cross-cell mounts");
2531     cmd_AddParmAtOffset(ts, OPT_fakestatall, "-fakestat-all", CMD_FLAG,
2532                         CMD_OPTIONAL,
2533                         "Enable fakestat support for all mounts");
2534     cmd_AddParmAtOffset(ts, OPT_nomount, "-nomount", CMD_FLAG,
2535                         CMD_OPTIONAL, "Do not mount AFS");
2536     cmd_AddParmAtOffset(ts, OPT_backuptree, "-backuptree", CMD_FLAG,
2537                         CMD_OPTIONAL,
2538                         "Prefer backup volumes for mointpoints in backup "
2539                         "volumes");
2540     cmd_AddParmAtOffset(ts, OPT_rxbind, "-rxbind", CMD_FLAG,
2541                         CMD_OPTIONAL,
2542                         "Bind the Rx socket (one interface only)");
2543     cmd_AddParmAtOffset(ts, OPT_settime, "-settime", CMD_FLAG,
2544                         CMD_OPTIONAL, "set the time");
2545     cmd_AddParmAtOffset(ts, OPT_rxpck, "-rxpck", CMD_SINGLE, CMD_OPTIONAL,
2546                         "set rx_extraPackets to this value");
2547     cmd_AddParmAtOffset(ts, OPT_splitcache, "-splitcache", CMD_SINGLE,
2548                         CMD_OPTIONAL,
2549                         "Percentage RW versus RO in cache (specify as 60/40)");
2550     cmd_AddParmAtOffset(ts, OPT_nodynvcache, "-disable-dynamic-vcaches",
2551                         CMD_FLAG, CMD_OPTIONAL,
2552                         "disable stat/vcache cache growing as needed");
2553     cmd_AddParmAtOffset(ts, OPT_rxmaxmtu, "-rxmaxmtu", CMD_SINGLE,
2554                         CMD_OPTIONAL, "set rx max MTU to use");
2555     cmd_AddParmAtOffset(ts, OPT_dynrootsparse, "-dynroot-sparse", CMD_FLAG,
2556                         CMD_OPTIONAL,
2557                         "Enable dynroot support with minimal cell list");
2558     cmd_AddParmAtOffset(ts, OPT_rxmaxfrags, "-rxmaxfrags", CMD_SINGLE,
2559                         CMD_OPTIONAL,
2560                         "Set the maximum number of UDP fragments Rx should "
2561                         "send/receive per Rx packet");
2562 }
2563
2564 int
2565 afsd_parse(int argc, char **argv)
2566 {
2567     return cmd_Dispatch(argc, argv);
2568 }
2569
2570 struct afsd_syscall_args {
2571     long syscall;
2572     long param1;
2573     long param2;
2574     long param3;
2575     long param4;
2576     long param5;
2577     const char *rn;
2578     int rxpri;
2579 };
2580
2581 /**
2582  * entry point for calling a syscall from another proc/thread.
2583  *
2584  * @param[in] rock  a struct afsd_syscall_args* specifying what syscall to call
2585  *
2586  * @return unused
2587  *   @retval NULL always
2588  */
2589 static void *
2590 call_syscall_thread(void *rock)
2591 {
2592     struct afsd_syscall_args *args = rock;
2593     int code;
2594
2595     if (args->rxpri) {
2596         afsd_set_rx_rtpri();
2597     }
2598
2599     code = afsd_call_syscall(args->syscall, args->param1, args->param2,
2600                                  args->param3, args->param4, args->param5);
2601     if (code && args->syscall == AFSOP_START_CS) {
2602         printf("%s: No check server daemon in client.\n", args->rn);
2603     }
2604
2605     free(args);
2606
2607     return NULL;
2608 }
2609
2610 /**
2611  * common code for calling a syscall in another proc/thread.
2612  *
2613  * @param[in] rx   1 if this is a thread for RX stuff, 0 otherwise
2614  * @param[in] wait 1 if we should wait for the new proc/thread to finish, 0 to
2615  *                 let it run in the background
2616  * @param[in] rn   the name of the running program
2617  * @param[in] syscall syscall to run
2618  */
2619 static void
2620 fork_syscall_impl(int rx, int wait, const char *rn, long syscall, long param1,
2621                   long param2, long param3, long param4, long param5)
2622 {
2623     struct afsd_syscall_args *args;
2624
2625     args = malloc(sizeof(*args));
2626
2627     args->syscall = syscall;
2628     args->param1 = param1;
2629     args->param2 = param2;
2630     args->param3 = param3;
2631     args->param4 = param4;
2632     args->param5 = param5;
2633     args->rxpri = rx;
2634     args->rn = rn;
2635
2636     afsd_fork(wait, call_syscall_thread, args);
2637 }
2638
2639 /**
2640  * call a syscall in another process or thread.
2641  */
2642 static void
2643 fork_syscall(const char *rn, long syscall, long param1, long param2,
2644              long param3, long param4, long param5)
2645 {
2646     fork_syscall_impl(0, 0, rn, syscall, param1, param2, param3, param4, param5);
2647 }
2648
2649 /**
2650  * call a syscall in another process or thread, and give it RX priority.
2651  */
2652 static void
2653 fork_rx_syscall(const char *rn, long syscall, long param1, long param2,
2654                 long param3, long param4, long param5)
2655 {
2656     fork_syscall_impl(1, 0, rn, syscall, param1, param2, param3, param4, param5);
2657 }
2658
2659 #if defined(AFS_SUN510_ENV) && defined(RXK_LISTENER_ENV)
2660 /**
2661  * call a syscall in another process or thread, give it RX priority, and wait
2662  * for it to finish before returning.
2663  */
2664 static void
2665 fork_rx_syscall_wait(const char *rn, long syscall, long param1, long param2,
2666                      long param3, long param4, long param5)
2667 {
2668     fork_syscall_impl(1, 1, rn, syscall, param1, param2, param3, param4, param5);
2669 }
2670 #endif /* AFS_SUN510_ENV && RXK_LISTENER_ENV */