Don't cast returns from malloc()
[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 = malloc(sizeof(*tmp));
1040                     if (!tmp)
1041                         printf
1042                             ("%s: MALLOC FAILED allocating file_list entry\n",
1043                              rn);
1044                     else {
1045                         tmp->fileNum = vFileNum;
1046                         tmp->next = cache_dir_filelist[dirNum];
1047                         cache_dir_filelist[dirNum] = tmp;
1048                     }
1049                 }
1050             }
1051             (*vFilesFound)++;
1052         } else if (dirNum < 0 && (*(currp->d_name) == 'D')
1053                    && GetDDirNumber(currp->d_name, 1 << 30) >= 0) {
1054             int retval = 0;
1055             if ((vFileNum = GetDDirNumber(currp->d_name, maxDir)) >= 0) {
1056                 /* Found a valid cachefile sub-Directory.  Remember this number
1057                  * and recurse into it.  Note that subdirs cannot have subdirs.
1058                  */
1059                 retval = 1;
1060             } else if ((vFileNum = GetDDirNumber(currp->d_name, 1 << 30)) >=
1061                        0) {
1062                 /* This directory is going away, but figure out if there
1063                  * are any cachefiles in here that should be saved by
1064                  * moving them to other cache directories.  This directory
1065                  * will be removed later.
1066                  */
1067                 retval = 2;
1068             }
1069
1070             /* Save the highest directory number we've seen */
1071             if (vFileNum > highDir)
1072                 highDir = vFileNum;
1073
1074             /* If this directory is staying, be sure to mark it as 'found' */
1075             if (retval == 1)
1076                 cache_dir_list[vFileNum] = 0;
1077
1078             /* Print the dirname for recursion */
1079             sprintf(fileToDelete, "%s", currp->d_name);
1080
1081             /* Note: vFileNum is the directory number */
1082             retval =
1083                 doSweepAFSCache(vFilesFound, fullpn_FileToDelete, vFileNum,
1084                                 (retval == 1 ? 0 : -1));
1085             if (retval) {
1086                 printf("%s: Recursive sweep failed on directory %s\n", rn,
1087                        currp->d_name);
1088                 return retval;
1089             }
1090         } else if (dirNum < 0 && strcmp(currp->d_name, DCACHEFILE) == 0) {
1091             /*
1092              * Found the file holding the dcache entries.
1093              */
1094             missing_DCacheFile = 0;
1095             SetNoBackupAttr(fullpn_DCacheFile);
1096         } else if (dirNum < 0 && strcmp(currp->d_name, VOLINFOFILE) == 0) {
1097             /*
1098              * Found the file holding the volume info.
1099              */
1100             missing_VolInfoFile = 0;
1101             SetNoBackupAttr(fullpn_VolInfoFile);
1102         } else if (dirNum < 0 && strcmp(currp->d_name, CELLINFOFILE) == 0) {
1103             /*
1104              * Found the file holding the cell info.
1105              */
1106             missing_CellInfoFile = 0;
1107             SetNoBackupAttr(fullpn_CellInfoFile);
1108         } else if ((strcmp(currp->d_name, ".") == 0)
1109                    || (strcmp(currp->d_name, "..") == 0) ||
1110 #ifdef AFS_DECOSF_ENV
1111                    /* these are magic AdvFS files */
1112                    (strcmp(currp->d_name, ".tags") == 0)
1113                    || (strcmp(currp->d_name, "quota.user") == 0)
1114                    || (strcmp(currp->d_name, "quota.group") == 0) ||
1115 #endif
1116 #ifdef AFS_LINUX22_ENV
1117                    /* this is the ext3 journal file */
1118                    (strcmp(currp->d_name, ".journal") == 0) ||
1119 #endif
1120                    (strcmp(currp->d_name, "lost+found") == 0)) {
1121             /*
1122              * Don't do anything - this file is legit, and is to be left alone.
1123              */
1124         } else {
1125             /*
1126              * This file/directory doesn't belong in the cache.  Nuke it.
1127              */
1128             sprintf(fileToDelete, "%s", currp->d_name);
1129             if (afsd_verbose)
1130                 printf("%s: Deleting '%s'\n", rn, fullpn_FileToDelete);
1131             UnlinkUnwantedFile(rn, fullpn_FileToDelete, fileToDelete);
1132         }
1133     }
1134
1135     if (dirNum < 0) {
1136
1137         /*
1138          * Create all the cache files that are missing.
1139          */
1140         CreateFileIfMissing(fullpn_DCacheFile, missing_DCacheFile);
1141         CreateFileIfMissing(fullpn_VolInfoFile, missing_VolInfoFile);
1142         CreateFileIfMissing(fullpn_CellInfoFile, missing_CellInfoFile);
1143
1144         /* ADJUST CACHE FILES */
1145
1146         /* First, let's walk through the list of files and figure out
1147          * if there are any leftover files in extra directories or
1148          * missing files.  Move the former and create the latter in
1149          * subdirs with extra space.
1150          */
1151
1152         thisDir = 0;            /* Keep track of which subdir has space */
1153
1154         for (vFileNum = 0; vFileNum < cacheFiles; vFileNum++) {
1155             if (dir_for_V[vFileNum] == -1) {
1156                 /* This file does not exist.  Create it in the first
1157                  * subdir that still has extra space.
1158                  */
1159                 while (thisDir < maxDir
1160                        && cache_dir_list[thisDir] >= nFilesPerDir)
1161                     thisDir++;
1162                 if (thisDir >= maxDir)
1163                     printf("%s: can't find directory to create V%d\n", rn,
1164                            vFileNum);
1165                 else {
1166                     struct stat statb;
1167 #if !defined(AFS_CACHE_VNODE_PATH) && !defined(AFS_LINUX26_ENV)
1168                     assert(inode_for_V[vFileNum] == (AFSD_INO_T) 0);
1169 #endif
1170                     sprintf(vFilePtr, "D%d/V%d", thisDir, vFileNum);
1171                     if (afsd_verbose)
1172                         printf("%s: Creating '%s'\n", rn, fullpn_VFile);
1173                     if (cache_dir_list[thisDir] < 0
1174                         && CreateCacheSubDir(directory, thisDir))
1175                         printf("%s: Can't create directory for '%s'\n", rn,
1176                                fullpn_VFile);
1177                     if (CreateCacheFile(fullpn_VFile, &statb))
1178                         printf("%s: Can't create '%s'\n", rn, fullpn_VFile);
1179                     else {
1180 #if !defined(AFS_CACHE_VNODE_PATH) && !defined(AFS_LINUX26_ENV)
1181                         inode_for_V[vFileNum] = statb.st_ino;
1182 #endif
1183                         dir_for_V[vFileNum] = thisDir;
1184                         cache_dir_list[thisDir]++;
1185                         (*vFilesFound)++;
1186                     }
1187                     SetNoBackupAttr(fullpn_VFile);
1188                 }
1189
1190             } else if (dir_for_V[vFileNum] >= maxDir
1191                        || dir_for_V[vFileNum] == -2) {
1192                 /* This file needs to move; move it to the first subdir
1193                  * that has extra space.  (-2 means it's in the toplevel)
1194                  */
1195                 while (thisDir < maxDir
1196                        && cache_dir_list[thisDir] >= nFilesPerDir)
1197                     thisDir++;
1198                 if (thisDir >= maxDir)
1199                     printf("%s: can't find directory to move V%d\n", rn,
1200                            vFileNum);
1201                 else {
1202                     if (MoveCacheFile
1203                         (directory, dir_for_V[vFileNum], thisDir, vFileNum,
1204                          maxDir)) {
1205                         /* Cannot move.  Ignore this file??? */
1206                         /* XXX */
1207                     }
1208                 }
1209             }
1210         }                       /* for */
1211
1212         /* At this point, we've moved all of the valid cache files
1213          * into the valid subdirs, and created all the extra
1214          * cachefiles we need to create.  Next, rebalance any subdirs
1215          * with too many cache files into the directories with not
1216          * enough cache files.  Note that thisDir currently sits at
1217          * the lowest subdir that _may_ have room.
1218          */
1219
1220         for (dirNum = 0; dirNum < maxDir; dirNum++) {
1221             struct afsd_file_list *thisFile;
1222
1223             for (thisFile = cache_dir_filelist[dirNum];
1224                  thisFile && cache_dir_list[dirNum] >= nFilesPerDir;
1225                  thisFile = thisFile->next) {
1226                 while (thisDir < maxDir
1227                        && cache_dir_list[thisDir] >= nFilesPerDir)
1228                     thisDir++;
1229                 if (thisDir >= maxDir)
1230                     printf("%s: can't find directory to move V%d\n", rn,
1231                            vFileNum);
1232                 else {
1233                     if (MoveCacheFile
1234                         (directory, dirNum, thisDir, thisFile->fileNum,
1235                          maxDir)) {
1236                         /* Cannot move.  Ignore this file??? */
1237                         /* XXX */
1238                     }
1239                 }
1240             }                   /* for each file to move */
1241         }                       /* for each directory */
1242
1243         /* Remove any directories >= maxDir -- they should be empty */
1244         for (; highDir >= maxDir; highDir--) {
1245             sprintf(fileToDelete, "D%d", highDir);
1246             UnlinkUnwantedFile(rn, fullpn_FileToDelete, fileToDelete);
1247         }
1248     }
1249
1250     /* dirNum < 0 */
1251     /*
1252      * Close the directory, return success.
1253      */
1254     if (afsd_debug)
1255         printf("%s: Closing cache directory.\n", rn);
1256     closedir(cdirp);
1257     return (0);
1258 }
1259
1260 char *
1261 CheckCacheBaseDir(char *dir)
1262 {
1263     struct stat statbuf;
1264
1265     if (!dir) {
1266         return "cache base dir not specified";
1267     }
1268     if (stat(dir, &statbuf) != 0) {
1269         return "unable to stat cache base directory";
1270     }
1271
1272     /* might want to check here for anything else goofy, like cache pointed at a non-dedicated directory, etc */
1273
1274 #ifdef AFS_LINUX24_ENV
1275     {
1276         int res;
1277         struct statfs statfsbuf;
1278
1279         res = statfs(dir, &statfsbuf);
1280         if (res != 0) {
1281             return "unable to statfs cache base directory";
1282         }
1283 #if !defined(AFS_LINUX26_ENV)
1284         if (statfsbuf.f_type == 0x52654973) {   /* REISERFS_SUPER_MAGIC */
1285             return "cannot use reiserfs as cache partition";
1286         } else if (statfsbuf.f_type == 0x58465342) {    /* XFS_SUPER_MAGIC */
1287             return "cannot use xfs as cache partition";
1288         } else if (statfsbuf.f_type == 0x01021994) {    /* TMPFS_SUPER_MAGIC */
1289             return "cannot use tmpfs as cache partition";
1290         } else if (statfsbuf.f_type != 0xEF53) {
1291             return "must use ext2 or ext3 for cache partition";
1292         }
1293 #endif
1294     }
1295 #endif
1296
1297 #ifdef AFS_HPUX_ENV
1298     {
1299         int res;
1300         struct statfs statfsbuf;
1301         char name[FSTYPSZ];
1302
1303         res = statfs(dir, &statfsbuf);
1304         if (res != 0) {
1305             return "unable to statfs cache base directory";
1306         }
1307
1308         if (sysfs(GETFSTYP, statfsbuf.f_fsid[1], name) != 0) {
1309             return "unable to determine filesystem type for cache base dir";
1310         }
1311
1312         if (strcmp(name, "hfs")) {
1313             return "can only use hfs filesystem for cache partition on hpux";
1314         }
1315     }
1316 #endif
1317
1318 #ifdef AFS_SUN5_ENV
1319     {
1320         FILE *vfstab;
1321         struct mnttab mnt;
1322         struct stat statmnt, statci;
1323
1324         if ((stat(dir, &statci) == 0)
1325             && ((vfstab = fopen(MNTTAB, "r")) != NULL)) {
1326             while (getmntent(vfstab, &mnt) == 0) {
1327                 if (strcmp(dir, mnt.mnt_mountp) != 0) {
1328                     char *cp;
1329                     int rdev = 0;
1330
1331                     if (cp = hasmntopt(&mnt, "dev="))
1332                         rdev =
1333                             (int)strtol(cp + strlen("dev="), (char **)NULL,
1334                                         16);
1335
1336                     if ((rdev == 0) && (stat(mnt.mnt_mountp, &statmnt) == 0))
1337                         rdev = statmnt.st_dev;
1338
1339                     if ((rdev == statci.st_dev)
1340                         && (hasmntopt(&mnt, "logging") != NULL)) {
1341
1342                         fclose(vfstab);
1343                         return
1344                             "mounting a multi-use partition which contains the AFS cache with the\n\"logging\" option may deadlock your system.\n\n";
1345                     }
1346                 }
1347             }
1348
1349             fclose(vfstab);
1350         }
1351     }
1352 #endif
1353
1354     return NULL;
1355 }
1356
1357 int
1358 SweepAFSCache(int *vFilesFound)
1359 {
1360     static char rn[] = "SweepAFSCache"; /*Routine name */
1361     int maxDir = (cacheFiles + nFilesPerDir - 1) / nFilesPerDir;
1362     int i;
1363
1364     *vFilesFound = 0;
1365
1366     if (cacheFlags & AFSCALL_INIT_MEMCACHE) {
1367         if (afsd_debug)
1368             printf("%s: Memory Cache, no cache sweep done\n", rn);
1369         return 0;
1370     }
1371
1372     if (cache_dir_list == NULL) {
1373         cache_dir_list = malloc(maxDir * sizeof(*cache_dir_list));
1374         if (cache_dir_list == NULL) {
1375             printf("%s: Malloc Failed!\n", rn);
1376             return (-1);
1377         }
1378         for (i = 0; i < maxDir; i++)
1379             cache_dir_list[i] = -1;     /* Does not exist */
1380     }
1381
1382     if (cache_dir_filelist == NULL) {
1383         cache_dir_filelist = calloc(maxDir, sizeof(*cache_dir_filelist));
1384         if (cache_dir_filelist == NULL) {
1385             printf("%s: Malloc Failed!\n", rn);
1386             return (-1);
1387         }
1388     }
1389
1390     if (dir_for_V == NULL) {
1391         dir_for_V = malloc(cacheFiles * sizeof(*dir_for_V));
1392         if (dir_for_V == NULL) {
1393             printf("%s: Malloc Failed!\n", rn);
1394             return (-1);
1395         }
1396         for (i = 0; i < cacheFiles; i++)
1397             dir_for_V[i] = -1;  /* Does not exist */
1398     }
1399
1400     /* Note, setting dirNum to -2 here will cause cachefiles found in
1401      * the toplevel directory to be marked in directory "-2".  This
1402      * allows us to differentiate between 'file not seen' (-1) and
1403      * 'file seen in top-level' (-2).  Then when we try to move the
1404      * file into a subdirectory, we know it's in the top-level instead
1405      * of some other cache subdir.
1406      */
1407     return doSweepAFSCache(vFilesFound, cacheBaseDir, -2, maxDir);
1408 }
1409
1410 static int
1411 ConfigCell(struct afsconf_cell *aci, void *arock, struct afsconf_dir *adir)
1412 {
1413     int isHomeCell;
1414     int i, code;
1415     afs_int32 cellFlags = 0;
1416     afs_int32 hosts[MAXHOSTSPERCELL];
1417
1418     /* figure out if this is the home cell */
1419     isHomeCell = (strcmp(aci->name, LclCellName) == 0);
1420     if (!isHomeCell) {
1421         cellFlags = 2;          /* not home, suid is forbidden */
1422         if (enable_dynroot == 2)
1423             cellFlags |= 8; /* don't display foreign cells until looked up */
1424     }
1425     /* build address list */
1426     for (i = 0; i < MAXHOSTSPERCELL; i++)
1427         memcpy(&hosts[i], &aci->hostAddr[i].sin_addr, sizeof(afs_int32));
1428
1429     if (aci->linkedCell)
1430         cellFlags |= 4;         /* Flag that linkedCell arg exists,
1431                                  * for upwards compatibility */
1432
1433     /* configure one cell */
1434     code = afsd_call_syscall(AFSOP_ADDCELL2, hosts,     /* server addresses */
1435                         aci->name,      /* cell name */
1436                         cellFlags,      /* is this the home cell? */
1437                         aci->linkedCell);       /* Linked cell, if any */
1438     if (code)
1439         printf("Adding cell '%s': error %d\n", aci->name, code);
1440     return 0;
1441 }
1442
1443 static int
1444 ConfigCellAlias(struct afsconf_cellalias *aca,
1445                 void *arock, struct afsconf_dir *adir)
1446 {
1447     /* push the alias into the kernel */
1448     afsd_call_syscall(AFSOP_ADDCELLALIAS, aca->aliasName, aca->realName);
1449     return 0;
1450 }
1451
1452 static void
1453 AfsdbLookupHandler(void)
1454 {
1455     afs_int32 kernelMsg[64];
1456     char acellName[128];
1457     afs_int32 code;
1458     struct afsconf_cell acellInfo;
1459     int i;
1460
1461     kernelMsg[0] = 0;
1462     kernelMsg[1] = 0;
1463     acellName[0] = '\0';
1464
1465 #if defined(AFS_DARWIN_ENV) && !defined(AFS_ARM_DARWIN_ENV)
1466     /* Fork the event handler also. */
1467     code = fork();
1468     if (code == 0) {
1469         afsd_install_events();
1470         return;
1471     } else if (code != -1) {
1472         event_pid = code;
1473     }
1474 #endif
1475     while (1) {
1476         /* On some platforms you only get 4 args to an AFS call */
1477         int sizeArg = ((sizeof acellName) << 16) | (sizeof kernelMsg);
1478         code =
1479             afsd_call_syscall(AFSOP_AFSDB_HANDLER, acellName, kernelMsg, sizeArg);
1480         if (code) {             /* Something is wrong? */
1481             sleep(1);
1482             continue;
1483         }
1484
1485         if (*acellName == 1)    /* Shutting down */
1486             break;
1487
1488         code = afsconf_GetAfsdbInfo(acellName, 0, &acellInfo);
1489         if (code) {
1490             kernelMsg[0] = 0;
1491             kernelMsg[1] = 0;
1492         } else {
1493             kernelMsg[0] = acellInfo.numServers;
1494             if (acellInfo.timeout)
1495                 kernelMsg[1] = acellInfo.timeout - time(0);
1496             else
1497                 kernelMsg[1] = 0;
1498             for (i = 0; i < acellInfo.numServers; i++)
1499                 kernelMsg[i + 2] = acellInfo.hostAddr[i].sin_addr.s_addr;
1500             strncpy(acellName, acellInfo.name, sizeof(acellName));
1501             acellName[sizeof(acellName) - 1] = '\0';
1502         }
1503     }
1504 #ifdef AFS_DARWIN_ENV
1505     kill(event_pid, SIGTERM);
1506 #endif
1507 }
1508
1509 #ifdef AFS_NEW_BKG
1510 static void
1511 BkgHandler(void)
1512 {
1513     afs_int32 code;
1514     struct afs_uspc_param *uspc;
1515     char srcName[256];
1516     char dstName[256];
1517
1518     uspc = calloc(1, sizeof(struct afs_uspc_param));
1519     memset(srcName, 0, sizeof(srcName));
1520     memset(dstName, 0, sizeof(dstName));
1521
1522     /* brscount starts at 0 */
1523     uspc->ts = -1;
1524
1525     while (1) {
1526         pid_t child = 0;
1527         int status;
1528         char srcpath[BUFSIZ];
1529         char dstpath[BUFSIZ];
1530
1531         /* pushing in a buffer this large */
1532         uspc->bufSz = 256;
1533
1534         code = afsd_call_syscall(AFSOP_BKG_HANDLER, uspc, srcName, dstName);
1535         if (code) {             /* Something is wrong? */
1536             if (code == -2) /* shutting down */
1537                 break;
1538
1539             sleep(1);
1540             uspc->retval = -1;
1541             continue;
1542         }
1543
1544         switch (uspc->reqtype) {
1545         case AFS_USPC_UMV:
1546             snprintf(srcpath, BUFSIZ, "/afs/.:mount/%d:%d:%d:%d/%s",
1547                      uspc->req.umv.sCell, uspc->req.umv.sVolume,
1548                      uspc->req.umv.sVnode, uspc->req.umv.sUnique, srcName);
1549             snprintf(dstpath, BUFSIZ, "/afs/.:mount/%d:%d:%d:%d/%s",
1550                      uspc->req.umv.dCell, uspc->req.umv.dVolume,
1551                      uspc->req.umv.dVnode, uspc->req.umv.dUnique, dstName);
1552             if ((child = fork()) == 0) {
1553                 /* first child does cp; second, rm. mv would re-enter. */
1554
1555                 switch (uspc->req.umv.idtype) {
1556                 case IDTYPE_UID:
1557                     if (setuid(uspc->req.umv.id) != 0) {
1558                         exit(-1);
1559                     }
1560                     break;
1561                 default:
1562                     exit(-1);
1563                     break; /* notreached */
1564                 }
1565                 execl("/bin/cp", "(afsd EXDEV helper)", "-PRp", "--", srcpath,
1566                       dstpath, (char *) NULL);
1567             }
1568             if (child == (pid_t) -1) {
1569                 uspc->retval = -1;
1570                 continue;
1571             }
1572
1573             if (waitpid(child, &status, 0) == -1)
1574                 uspc->retval = EIO;
1575             else if (WIFEXITED(status) != 0 && WEXITSTATUS(status) == 0) {
1576                 if ((child = fork()) == 0) {
1577                     switch (uspc->req.umv.idtype) {
1578                     case IDTYPE_UID:
1579                         if (setuid(uspc->req.umv.id) != 0) {
1580                             exit(-1);
1581                         }
1582                         break;
1583                     default:
1584                         exit(-1);
1585                         break; /* notreached */
1586                     }
1587                     execl("/bin/rm", "(afsd EXDEV helper)", "-rf", "--",
1588                           srcpath, (char *) NULL);
1589                 }
1590                 if (child == (pid_t) -1) {
1591                     uspc->retval = -1;
1592                     continue;
1593                 }
1594                 if (waitpid(child, &status, 0) == -1)
1595                     uspc->retval = EIO;
1596                 else if (WIFEXITED(status) != 0) {
1597                     /* rm exit status */
1598                     uspc->retval = WEXITSTATUS(status);
1599                 } else {
1600                     /* rm signal status */
1601                     uspc->retval = -(WTERMSIG(status));
1602                 }
1603             } else {
1604                 /* error from cp: exit or signal status */
1605                 uspc->retval = (WIFEXITED(status) != 0) ?
1606                     WEXITSTATUS(status) : -(WTERMSIG(status));
1607             }
1608             memset(srcName, 0, sizeof(srcName));
1609             memset(dstName, 0, sizeof(dstName));
1610             break;
1611
1612         default:
1613             /* unknown req type */
1614             uspc->retval = -1;
1615             break;
1616         }
1617     }
1618 }
1619 #endif
1620
1621 static void *
1622 afsdb_thread(void *rock)
1623 {
1624     /* Since the AFSDB lookup handler runs as a user process,
1625      * need to drop the controlling TTY, etc.
1626      */
1627     if (afsd_daemon(0, 0) == -1) {
1628         printf("Error starting AFSDB lookup handler: %s\n",
1629                strerror(errno));
1630         exit(1);
1631     }
1632     AfsdbLookupHandler();
1633     return NULL;
1634 }
1635
1636 static void *
1637 daemon_thread(void *rock)
1638 {
1639 #ifdef AFS_NEW_BKG
1640     /* Since the background daemon runs as a user process,
1641      * need to drop the controlling TTY, etc.
1642      */
1643     if (afsd_daemon(0, 0) == -1) {
1644         printf("Error starting background daemon: %s\n",
1645                strerror(errno));
1646         exit(1);
1647     }
1648     BkgHandler();
1649 #elif defined(AFS_AIX32_ENV)
1650     afsd_call_syscall(AFSOP_START_BKG, 0);
1651 #else
1652     afsd_call_syscall(AFSOP_START_BKG);
1653 #endif
1654     return NULL;
1655 }
1656
1657 #ifndef UKERNEL
1658 static void *
1659 rmtsysd_thread(void *rock)
1660 {
1661     rmtsysd();
1662     return NULL;
1663 }
1664 #endif /* !UKERNEL */
1665
1666 int
1667 mainproc(struct cmd_syndesc *as, void *arock)
1668 {
1669     afs_int32 code;             /*Result of fork() */
1670 #ifdef  AFS_SUN5_ENV
1671     struct stat st;
1672 #endif
1673 #ifdef AFS_SGI65_ENV
1674     struct sched_param sp;
1675 #endif
1676
1677 #ifdef AFS_SGI_VNODE_GLUE
1678     if (afs_init_kernel_config(-1) < 0) {
1679         printf("Can't determine NUMA configuration, not starting AFS.\n");
1680         exit(1);
1681     }
1682 #endif
1683
1684     /* call atoi on the appropriate parsed results */
1685     if (cmd_OptionAsInt(as, OPT_blocks, &cacheBlocks) == 0)
1686         sawCacheBlocks = 1;
1687
1688     if (cmd_OptionAsInt(as, OPT_files, &cacheFiles) == 0)
1689         filesSet = 1;
1690
1691     if (cmd_OptionAsString(as, OPT_rootvol, &rootVolume) == 0)
1692         rootVolSet = 1;
1693
1694     if (cmd_OptionAsInt(as, OPT_stat, &cacheStatEntries) == 0)
1695         sawCacheStatEntries = 1;
1696
1697     if (cmd_OptionPresent(as, OPT_memcache)) {
1698         cacheBaseDir = NULL;
1699         sawCacheBaseDir = 1;
1700         cacheFlags |= AFSCALL_INIT_MEMCACHE;
1701     }
1702
1703     if (cmd_OptionAsString(as, OPT_cachedir, &cacheBaseDir) == 0)
1704         sawCacheBaseDir = 1;
1705
1706     if (cmd_OptionAsString(as, OPT_mountdir, &afsd_cacheMountDir) == 0)
1707         sawCacheMountDir = 1;
1708
1709     cmd_OptionAsInt(as, OPT_daemons, &nDaemons);
1710
1711     afsd_verbose = cmd_OptionPresent(as, OPT_verbose);
1712
1713     if (cmd_OptionPresent(as, OPT_rmtsys)) {
1714         afsd_rmtsys = 1;
1715 #ifdef UKERNEL
1716         printf("-rmtsys not supported for UKERNEL\n");
1717         return -1;
1718 #endif
1719     }
1720
1721     if (cmd_OptionPresent(as, OPT_debug)) {
1722         afsd_debug = 1;
1723         afsd_verbose = 1;
1724     }
1725
1726     if (cmd_OptionAsInt(as, OPT_chunksize, &chunkSize) == 0) {
1727         if (chunkSize < 0 || chunkSize > 30) {
1728             printf
1729                 ("afsd:invalid chunk size (not in range 0-30), using default\n");
1730             chunkSize = 0;
1731         }
1732     }
1733
1734     if (cmd_OptionAsInt(as, OPT_dcache, &dCacheSize) == 0)
1735         sawDCacheSize = 1;
1736
1737     cmd_OptionAsInt(as, OPT_volumes, &vCacheSize);
1738
1739     if (cmd_OptionPresent(as, OPT_biods)) {
1740         /* -biods */
1741 #ifndef AFS_AIX32_ENV
1742         printf
1743             ("afsd: [-biods] currently only enabled for aix3.x VM supported systems\n");
1744 #else
1745         cmd_OptionAsInt(as, OPT_biods, &nBiods);
1746 #endif
1747     }
1748     cmd_OptionAsInt(as, OPT_prealloc, &preallocs);
1749
1750     if (cmd_OptionAsString(as, OPT_confdir, &confDir) == CMD_MISSING) {
1751         confDir = strdup(AFSDIR_CLIENT_ETC_DIRPATH);
1752     }
1753     sprintf(fullpn_CacheInfo, "%s/%s", confDir, CACHEINFOFILE);
1754
1755     if (cmd_OptionPresent(as, OPT_logfile)) {
1756         printf("afsd: Ignoring obsolete -logfile flag\n");
1757     }
1758
1759     afsd_CloseSynch = cmd_OptionPresent(as, OPT_waitclose);
1760
1761     if (cmd_OptionPresent(as, OPT_shutdown)) {
1762         /* -shutdown */
1763         afs_shutdown = 1;
1764         /*
1765          * Cold shutdown is the default
1766          */
1767         printf("afsd: Shutting down all afs processes and afs state\n");
1768         code = afsd_call_syscall(AFSOP_SHUTDOWN, 1);
1769         if (code) {
1770             printf("afsd: AFS still mounted; Not shutting down\n");
1771             exit(1);
1772         }
1773         exit(0);
1774     }
1775
1776     enable_peer_stats = cmd_OptionPresent(as, OPT_peerstats);
1777     enable_process_stats = cmd_OptionPresent(as, OPT_processstats);
1778
1779     if (cmd_OptionPresent(as, OPT_memallocsleep)) {
1780         printf("afsd: -mem_alloc_sleep is deprecated -- ignored\n");
1781     }
1782
1783     enable_afsdb = cmd_OptionPresent(as, OPT_afsdb);
1784     if (cmd_OptionPresent(as, OPT_filesdir)) {
1785         /* -files_per_subdir */
1786         int res;
1787         cmd_OptionAsInt(as, OPT_filesdir, &res);
1788         if (res < 10 || res > (1 << 30)) {
1789             printf
1790                 ("afsd:invalid number of files per subdir, \"%s\". Ignored\n",
1791                  as->parms[25].items->data);
1792         } else {
1793             nFilesPerDir = res;
1794         }
1795     }
1796     enable_dynroot = cmd_OptionPresent(as, OPT_dynroot);
1797
1798     if (cmd_OptionPresent(as, OPT_fakestat)) {
1799         enable_fakestat = 2;
1800     }
1801     if (cmd_OptionPresent(as, OPT_fakestatall)) {
1802         enable_fakestat = 1;
1803     }
1804     if (cmd_OptionPresent(as, OPT_settime)) {
1805         /* -settime */
1806         printf("afsd: -settime ignored\n");
1807         printf("afsd: the OpenAFS client no longer sets the system time; "
1808                "please use NTP or\n");
1809         printf("afsd: another such system to synchronize client time\n");
1810     }
1811
1812     enable_nomount = cmd_OptionPresent(as, OPT_nomount);
1813     enable_backuptree = cmd_OptionPresent(as, OPT_backuptree);
1814     enable_rxbind = cmd_OptionPresent(as, OPT_rxbind);
1815
1816     /* set rx_extraPackets */
1817     if (cmd_OptionPresent(as, OPT_rxpck)) {
1818         /* -rxpck */
1819         int rxpck;
1820         cmd_OptionAsInt(as, OPT_rxpck, &rxpck);
1821         printf("afsd: set rxpck = %d\n", rxpck);
1822         code = afsd_call_syscall(AFSOP_SET_RXPCK, rxpck);
1823         if (code) {
1824             printf("afsd: failed to set rxpck\n");
1825             exit(1);
1826         }
1827     }
1828     if (cmd_OptionPresent(as, OPT_splitcache)) {
1829         char *c;
1830         char *var = NULL;
1831
1832         cmd_OptionAsString(as, OPT_splitcache, &var);
1833
1834         if (var == NULL || ((c = strchr(var, '/')) == NULL))
1835             printf
1836                 ("ignoring splitcache (specify as RW/RO percentages: 60/40)\n");
1837         else {
1838             ropct = atoi(c + 1);
1839             *c = '\0';
1840             rwpct = atoi(var);
1841             if ((rwpct != 0) && (ropct != 0) && (ropct + rwpct == 100)) {
1842                 /* -splitcache */
1843                 enable_splitcache = 1;
1844             }
1845         }
1846         free(var);
1847     }
1848     if (cmd_OptionPresent(as, OPT_nodynvcache)) {
1849 #ifdef AFS_MAXVCOUNT_ENV
1850        afsd_dynamic_vcaches = 0;
1851 #else
1852        printf("afsd: Error toggling flag, dynamically allocated vcaches not supported on your platform\n");
1853        exit(1);
1854 #endif
1855     }
1856 #ifdef AFS_MAXVCOUNT_ENV
1857     else {
1858        /* -dynamic-vcaches */
1859        afsd_dynamic_vcaches = 1;
1860     }
1861
1862     if (afsd_verbose)
1863     printf("afsd: %s dynamically allocated vcaches\n", ( afsd_dynamic_vcaches ? "enabling" : "disabling" ));
1864 #endif
1865
1866     cmd_OptionAsInt(as, OPT_rxmaxmtu, &rxmaxmtu);
1867
1868     if (cmd_OptionPresent(as, OPT_dynrootsparse)) {
1869         enable_dynroot = 2;
1870     }
1871
1872     cmd_OptionAsInt(as, OPT_rxmaxfrags, &rxmaxfrags);
1873
1874     /* parse cacheinfo file if this is a diskcache */
1875     if (ParseCacheInfoFile()) {
1876         exit(1);
1877     }
1878
1879     return 0;
1880 }
1881
1882 int
1883 afsd_run(void)
1884 {
1885     static char rn[] = "afsd";  /*Name of this routine */
1886     struct afsconf_dir *cdir;   /* config dir */
1887     int lookupResult;           /*Result of GetLocalCellName() */
1888     int i;
1889     afs_int32 code;             /*Result of fork() */
1890     char *fsTypeMsg = NULL;
1891     int cacheIteration;         /*How many times through cache verification */
1892     int vFilesFound;            /*How many data cache files were found in sweep */
1893     int currVFile;              /*Current AFS cache file number passed in */
1894
1895         /*
1896      * Pull out all the configuration info for the workstation's AFS cache and
1897      * the cellular community we're willing to let our users see.
1898      */
1899     cdir = afsconf_Open(confDir);
1900     if (!cdir) {
1901         printf("afsd: some file missing or bad in %s\n", confDir);
1902         exit(1);
1903     }
1904
1905     lookupResult =
1906         afsconf_GetLocalCell(cdir, LclCellName, sizeof(LclCellName));
1907     if (lookupResult) {
1908         printf("%s: Can't get my home cell name!  [Error is %d]\n", rn,
1909                lookupResult);
1910     } else {
1911         if (afsd_verbose)
1912             printf("%s: My home cell is '%s'\n", rn, LclCellName);
1913     }
1914
1915     if (!enable_nomount) {
1916         if (afsd_check_mount(rn, afsd_cacheMountDir)) {
1917             return -1;
1918         }
1919     }
1920
1921     /* do some random computations in memcache case to get things to work
1922      * reasonably no matter which parameters you set.
1923      */
1924     if (cacheFlags & AFSCALL_INIT_MEMCACHE) {
1925         /* memory cache: size described either as blocks or dcache entries, but
1926          * not both.
1927          */
1928         if (filesSet) {
1929             fprintf(stderr, "%s: -files ignored with -memcache\n", rn);
1930         }
1931         if (sawDCacheSize) {
1932             if (chunkSize == 0) {
1933                 chunkSize = 13; /* 8k default chunksize for memcache */
1934             }
1935             if (sawCacheBlocks) {
1936                 printf
1937                     ("%s: can't set cache blocks and dcache size simultaneously when diskless.\n",
1938                      rn);
1939                 exit(1);
1940             }
1941             /* compute the cache size based on # of chunks times the chunk size */
1942             i = (1 << chunkSize);       /* bytes per chunk */
1943             cacheBlocks = i * dCacheSize;
1944             sawCacheBlocks = 1; /* so that ParseCacheInfoFile doesn't overwrite */
1945         } else {
1946             if (chunkSize == 0) {
1947                 /* Try to autotune the memcache chunksize based on size
1948                  * of memcache. This is done on the assumption that approx
1949                  * 1024 chunks is suitable, it's a balance between enough
1950                  * chunks to be useful and ramping up nicely when using larger
1951                  * memcache to improve bulk read/write performance
1952                  */
1953                 for (i = 14;
1954                      i <= 21 && (1 << i) / 1024 < (cacheBlocks / 1024); i++);
1955                 chunkSize = i - 1;
1956             }
1957             /* compute the dcache size from overall cache size and chunk size */
1958             if (chunkSize > 10) {
1959                 dCacheSize = (cacheBlocks >> (chunkSize - 10));
1960             } else if (chunkSize < 10) {
1961                 dCacheSize = (cacheBlocks << (10 - chunkSize));
1962             } else {
1963                 dCacheSize = cacheBlocks;
1964             }
1965             /* don't have to set sawDCacheSize here since it isn't overwritten
1966              * by ParseCacheInfoFile.
1967              */
1968         }
1969         if (afsd_verbose)
1970             printf("%s: chunkSize autotuned to %d\n", rn, chunkSize);
1971
1972         /* kernel computes # of dcache entries as min of cacheFiles and
1973          * dCacheSize, so we now make them equal.
1974          */
1975         cacheFiles = dCacheSize;
1976     } else {
1977         /* Disk cache:
1978          * Compute the number of cache files based on cache size,
1979          * but only if -files isn't given on the command line.
1980          * Don't let # files be so small as to prevent full utilization
1981          * of the cache unless user has explicitly asked for it.
1982          */
1983         if (chunkSize == 0) {
1984             /* Set chunksize to 256kB - 1MB depending on cache size */
1985             if (cacheBlocks < 500000) {
1986                 chunkSize = 18;
1987             } else if (cacheBlocks < 1000000) {
1988                 chunkSize = 19;
1989             } else {
1990                 chunkSize = 20;
1991             }
1992         }
1993
1994         if (!filesSet) {
1995             cacheFiles = cacheBlocks / 32;      /* Assume 32k avg filesize */
1996
1997             cacheFiles = max(cacheFiles, 1000);
1998
1999             /* Always allow more files than chunks.  Presume average V-file
2000              * is ~67% of a chunk...  (another guess, perhaps Honeyman will
2001              * have a grad student write a paper).  i is KILOBYTES.
2002              */
2003             i = 1 << (chunkSize < 10 ? 0 : chunkSize - 10);
2004             cacheFiles = max(cacheFiles, 1.5 * (cacheBlocks / i));
2005
2006             /* never permit more files than blocks, while leaving space for
2007              * VolumeInfo and CacheItems files.  VolumeInfo is usually 20K,
2008              * CacheItems is 50 Bytes / file (== 1K/20)
2009              */
2010 #define CACHEITMSZ (cacheFiles / 20)
2011 #define VOLINFOSZ 50            /* 40kB has been seen, be conservative */
2012 #define CELLINFOSZ 4            /* Assuming disk block size is 4k ... */
2013 #define INFOSZ (VOLINFOSZ+CELLINFOSZ+CACHEITMSZ)
2014
2015             /* Sanity check: If the obtained number of disk cache files
2016              * is larger than the number of available (4k) disk blocks, we're
2017              * doing something wrong. Fail hard so we can fix the bug instead
2018              * of silently hiding it like before */
2019
2020             if (cacheFiles > (cacheBlocks - INFOSZ) / 4) {
2021                 fprintf(stderr,
2022                         "%s: ASSERT: cacheFiles %d  diskblocks %d\n",
2023                         rn, cacheFiles, (cacheBlocks - INFOSZ) / 4);
2024                 exit(1);
2025             }
2026             if (cacheFiles < 100)
2027                 fprintf(stderr, "%s: WARNING: cache probably too small!\n",
2028                         rn);
2029
2030             if (afsd_verbose)
2031                 printf("%s: cacheFiles autotuned to %d\n", rn, cacheFiles);
2032         }
2033 #if 0
2034        /* This actually needs to
2035           1) use powers of 2
2036           2) not second-guess when a chunksize comes from the command line
2037           3) be less, um, small. 2^2??
2038        */
2039         /* Sanity check chunkSize */
2040         i = max(cacheBlocks / 1000, cacheBlocks / cacheFiles);
2041         chunkSize = min(chunkSize, i);
2042         chunkSize = max(chunkSize, 2);
2043         if (afsd_verbose)
2044             printf("%s: chunkSize autotuned to %d\n", rn, chunkSize);
2045 #endif
2046
2047         if (!sawDCacheSize) {
2048             dCacheSize = cacheFiles / 2;
2049             if (dCacheSize > 10000) {
2050                 dCacheSize = 10000;
2051             }
2052             if (dCacheSize < 2000) {
2053                 dCacheSize = 2000;
2054             }
2055             if (afsd_verbose)
2056                 printf("%s: dCacheSize autotuned to %d\n", rn, dCacheSize);
2057         }
2058     }
2059     if (!sawCacheStatEntries) {
2060         if (chunkSize <= 13) {
2061             cacheStatEntries = dCacheSize / 4;
2062         } else if (chunkSize >= 16) {
2063             cacheStatEntries = dCacheSize * 1.5;
2064         } else {
2065             cacheStatEntries = dCacheSize;
2066         }
2067         if (afsd_verbose)
2068             printf("%s: cacheStatEntries autotuned to %d\n", rn,
2069                    cacheStatEntries);
2070     }
2071
2072 #if !defined(AFS_CACHE_VNODE_PATH) && !defined(AFS_LINUX26_ENV)
2073     /*
2074      * Create and zero the inode table for the desired cache files.
2075      */
2076     inode_for_V = calloc(cacheFiles, sizeof(AFSD_INO_T));
2077     if (inode_for_V == (AFSD_INO_T *) 0) {
2078         printf
2079             ("%s: malloc() failed for cache file inode table with %d entries.\n",
2080              rn, cacheFiles);
2081         exit(1);
2082     }
2083     if (afsd_debug)
2084         printf("%s: %d inode_for_V entries at 0x%x, %lu bytes\n", rn,
2085                cacheFiles, inode_for_V, (cacheFiles * sizeof(AFSD_INO_T)));
2086 #endif
2087
2088     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE)) {
2089         /*
2090          * Set up all the pathnames we'll need for later.
2091          */
2092         sprintf(fullpn_DCacheFile, "%s/%s", cacheBaseDir, DCACHEFILE);
2093         sprintf(fullpn_VolInfoFile, "%s/%s", cacheBaseDir, VOLINFOFILE);
2094         sprintf(fullpn_CellInfoFile, "%s/%s", cacheBaseDir, CELLINFOFILE);
2095         sprintf(fullpn_VFile, "%s/", cacheBaseDir);
2096         vFilePtr = fullpn_VFile + strlen(fullpn_VFile);
2097
2098         fsTypeMsg = CheckCacheBaseDir(cacheBaseDir);
2099         if (fsTypeMsg) {
2100 #ifdef AFS_SUN5_ENV
2101             printf("%s: WARNING: Cache dir check failed (%s)\n", rn, fsTypeMsg);
2102 #else
2103             printf("%s: ERROR: Cache dir check failed (%s)\n", rn, fsTypeMsg);
2104             exit(1);
2105 #endif
2106         }
2107     }
2108
2109     /*
2110      * Set up all the kernel processes needed for AFS.
2111      */
2112 #ifdef mac2
2113     setpgrp(getpid(), 0);
2114 #endif /* mac2 */
2115
2116     /*
2117      * Set the primary cell name.
2118      */
2119     afsd_call_syscall(AFSOP_SET_THISCELL, LclCellName);
2120
2121     /* Initialize RX daemons and services */
2122
2123     /* initialize the rx random number generator from user space */
2124     {
2125         /* parse multihomed address files */
2126         afs_uint32 addrbuf[MAXIPADDRS], maskbuf[MAXIPADDRS],
2127             mtubuf[MAXIPADDRS];
2128         char reason[1024];
2129         code =
2130             parseNetFiles(addrbuf, maskbuf, mtubuf, MAXIPADDRS, reason,
2131                           AFSDIR_CLIENT_NETINFO_FILEPATH,
2132                           AFSDIR_CLIENT_NETRESTRICT_FILEPATH);
2133         if (code > 0) {
2134             if (enable_rxbind)
2135                 code = code | 0x80000000;
2136                 afsd_call_syscall(AFSOP_ADVISEADDR, code, addrbuf, maskbuf, mtubuf);
2137         } else
2138             printf("ADVISEADDR: Error in specifying interface addresses:%s\n",
2139                    reason);
2140     }
2141
2142     /* Set realtime priority for most threads to same as for biod's. */
2143     afsd_set_afsd_rtpri();
2144
2145     /* Start listener, then callback listener. Lastly, start rx event daemon.
2146      * Change in ordering is so that Linux port has socket fd in listener
2147      * process.
2148      * preallocs are passed for both listener and callback server. Only
2149      * the one which actually does the initialization uses them though.
2150      */
2151     if (preallocs < cacheStatEntries + 50)
2152         preallocs = cacheStatEntries + 50;
2153 #ifdef RXK_LISTENER_ENV
2154     if (afsd_verbose)
2155         printf("%s: Forking rx listener daemon.\n", rn);
2156 # ifdef AFS_SUN510_ENV
2157     fork_rx_syscall_wait(rn, AFSOP_RXLISTENER_DAEMON, preallocs,
2158                          enable_peer_stats, enable_process_stats);
2159 # else /* !AFS_SUN510_ENV */
2160     fork_rx_syscall(rn, AFSOP_RXLISTENER_DAEMON, preallocs, enable_peer_stats,
2161                     enable_process_stats);
2162 # endif /* !AFS_SUN510_ENV */
2163 #endif
2164     if (afsd_verbose)
2165         printf("%s: Forking rx callback listener.\n", rn);
2166 #ifndef RXK_LISTENER_ENV
2167     fork_rx_syscall(rn, AFSOP_START_RXCALLBACK, preallocs, enable_peer_stats,
2168                     enable_process_stats);
2169 #else
2170     fork_syscall(rn, AFSOP_START_RXCALLBACK, preallocs);
2171 #endif
2172 #if defined(AFS_SUN5_ENV) || defined(RXK_LISTENER_ENV) || defined(RXK_UPCALL_ENV)
2173     if (afsd_verbose)
2174         printf("%s: Forking rxevent daemon.\n", rn);
2175     fork_rx_syscall(rn, AFSOP_RXEVENT_DAEMON);
2176 #endif
2177
2178     if (enable_afsdb) {
2179         if (afsd_verbose)
2180             printf("%s: Forking AFSDB lookup handler.\n", rn);
2181         afsd_fork(0, afsdb_thread, NULL);
2182     }
2183     code = afsd_call_syscall(AFSOP_BASIC_INIT, 1);
2184     if (code) {
2185         printf("%s: Error %d in basic initialization.\n", rn, code);
2186         exit(1);
2187     }
2188
2189     /*
2190      * Tell the kernel some basic information about the workstation's cache.
2191      */
2192     if (afsd_verbose)
2193         printf
2194             ("%s: Calling AFSOP_CACHEINIT: %d stat cache entries, %d optimum cache files, %d blocks in the cache, flags = 0x%x, dcache entries %d\n",
2195              rn, cacheStatEntries, cacheFiles, cacheBlocks, cacheFlags,
2196              dCacheSize);
2197     memset(&cparams, '\0', sizeof(cparams));
2198     cparams.cacheScaches = cacheStatEntries;
2199     cparams.cacheFiles = cacheFiles;
2200     cparams.cacheBlocks = cacheBlocks;
2201     cparams.cacheDcaches = dCacheSize;
2202     cparams.cacheVolumes = vCacheSize;
2203     cparams.chunkSize = chunkSize;
2204     cparams.setTimeFlag = 0;
2205     cparams.memCacheFlag = cacheFlags;
2206     cparams.dynamic_vcaches = afsd_dynamic_vcaches;
2207         afsd_call_syscall(AFSOP_CACHEINIT, &cparams);
2208
2209     /* do it before we init the cache inodes */
2210     if (enable_splitcache) {
2211         afsd_call_syscall(AFSOP_BUCKETPCT, 1, rwpct);
2212         afsd_call_syscall(AFSOP_BUCKETPCT, 2, ropct);
2213     }
2214
2215     if (afsd_CloseSynch)
2216         afsd_call_syscall(AFSOP_CLOSEWAIT);
2217
2218     /*
2219      * Sweep the workstation AFS cache directory, remembering the inodes of
2220      * valid files and deleting extraneous files.  Keep sweeping until we
2221      * have the right number of data cache files or we've swept too many
2222      * times.
2223      *
2224      * This also creates files in the cache directory like VolumeItems and
2225      * CellItems, and thus must be ran before those are sent to the kernel.
2226      */
2227     if (afsd_verbose)
2228         printf("%s: Sweeping workstation's AFS cache directory.\n", rn);
2229     cacheIteration = 0;
2230     /* Memory-cache based system doesn't need any of this */
2231     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE)) {
2232         do {
2233             cacheIteration++;
2234             if (SweepAFSCache(&vFilesFound)) {
2235                 printf("%s: Error on sweep %d of workstation AFS cache \
2236                        directory.\n", rn, cacheIteration);
2237                 exit(1);
2238             }
2239             if (afsd_verbose)
2240                 printf
2241                     ("%s: %d out of %d data cache files found in sweep %d.\n",
2242                      rn, vFilesFound, cacheFiles, cacheIteration);
2243         } while ((vFilesFound < cacheFiles)
2244                  && (cacheIteration < MAX_CACHE_LOOPS));
2245     } else if (afsd_verbose)
2246         printf("%s: Using memory cache, not swept\n", rn);
2247
2248     /*
2249      * Pass the kernel the name of the workstation cache file holding the
2250      * dcache entries.
2251      */
2252     if (afsd_debug)
2253         printf("%s: Calling AFSOP_CACHEINFO: dcache file is '%s'\n", rn,
2254                fullpn_DCacheFile);
2255     /* once again, meaningless for a memory-based cache. */
2256     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE))
2257         afsd_call_syscall(AFSOP_CACHEINFO, fullpn_DCacheFile);
2258
2259     /*
2260      * Pass the kernel the name of the workstation cache file holding the
2261      * cell information.
2262      */
2263     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE)) {
2264         if (afsd_debug)
2265             printf("%s: Calling AFSOP_CELLINFO: cell info file is '%s'\n", rn,
2266                    fullpn_CellInfoFile);
2267         afsd_call_syscall(AFSOP_CELLINFO, fullpn_CellInfoFile);
2268     }
2269
2270     if (rxmaxfrags) {
2271         if (afsd_verbose)
2272             printf("%s: Setting rxmaxfrags in kernel = %d\n", rn, rxmaxfrags);
2273         code = afsd_call_syscall(AFSOP_SET_RXMAXFRAGS, rxmaxfrags);
2274         if (code)
2275             printf("%s: Error seting rxmaxfrags\n", rn);
2276     }
2277
2278     if (rxmaxmtu) {
2279         if (afsd_verbose)
2280             printf("%s: Setting rxmaxmtu in kernel = %d\n", rn, rxmaxmtu);
2281         code = afsd_call_syscall(AFSOP_SET_RXMAXMTU, rxmaxmtu);
2282         if (code)
2283             printf("%s: Error seting rxmaxmtu\n", rn);
2284     }
2285
2286     if (enable_dynroot) {
2287         if (afsd_verbose)
2288             printf("%s: Enabling dynroot support in kernel%s.\n", rn,
2289                    (enable_dynroot==2)?", not showing cells.":"");
2290         code = afsd_call_syscall(AFSOP_SET_DYNROOT, 1);
2291         if (code)
2292             printf("%s: Error enabling dynroot support.\n", rn);
2293     }
2294
2295     if (enable_fakestat) {
2296         if (afsd_verbose)
2297             printf("%s: Enabling fakestat support in kernel%s.\n", rn,
2298                    (enable_fakestat==1)?" for all mountpoints."
2299                    :" for crosscell mountpoints");
2300         code = afsd_call_syscall(AFSOP_SET_FAKESTAT, enable_fakestat);
2301         if (code)
2302             printf("%s: Error enabling fakestat support.\n", rn);
2303     }
2304
2305     if (enable_backuptree) {
2306         if (afsd_verbose)
2307             printf("%s: Enabling backup tree support in kernel.\n", rn);
2308         code = afsd_call_syscall(AFSOP_SET_BACKUPTREE, enable_backuptree);
2309         if (code)
2310             printf("%s: Error enabling backup tree support.\n", rn);
2311     }
2312
2313     /*
2314      * Tell the kernel about each cell in the configuration.
2315      */
2316     afsconf_CellApply(cdir, ConfigCell, NULL);
2317     afsconf_CellAliasApply(cdir, ConfigCellAlias, NULL);
2318
2319     /* Initialize AFS daemon threads. */
2320     if (afsd_verbose)
2321         printf("%s: Forking AFS daemon.\n", rn);
2322     fork_syscall(rn, AFSOP_START_AFS);
2323
2324     if (afsd_verbose)
2325         printf("%s: Forking Check Server Daemon.\n", rn);
2326     fork_syscall(rn, AFSOP_START_CS);
2327
2328     if (afsd_verbose)
2329         printf("%s: Forking %d background daemons.\n", rn, nDaemons);
2330 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
2331     /* Add one because for sgi we always "steal" the first daemon for a
2332      * different task if we only have a 4K stack.
2333      */
2334     nDaemons++;
2335 #endif
2336     for (i = 0; i < nDaemons; i++) {
2337         afsd_fork(0, daemon_thread, NULL);
2338     }
2339 #ifdef  AFS_AIX32_ENV
2340     if (!sawBiod)
2341         nBiods = nDaemons * 2;
2342     if (nBiods < 5)
2343         nBiods = 5;
2344     for (i = 0; i < nBiods; i++) {
2345         fork_syscall(rn, AFSOP_START_BKG, nBiods);
2346     }
2347 #endif
2348
2349     /*
2350      * If the root volume has been explicitly set, tell the kernel.
2351      */
2352     if (rootVolSet) {
2353         if (afsd_verbose)
2354             printf("%s: Calling AFSOP_ROOTVOLUME with '%s'\n", rn,
2355                    rootVolume);
2356         afsd_call_syscall(AFSOP_ROOTVOLUME, rootVolume);
2357     }
2358
2359     /*
2360      * Pass the kernel the name of the workstation cache file holding the
2361      * volume information.
2362      */
2363     if (afsd_debug)
2364         printf("%s: Calling AFSOP_VOLUMEINFO: volume info file is '%s'\n", rn,
2365                fullpn_VolInfoFile);
2366     /* once again, meaningless for a memory-based cache. */
2367     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE))
2368         afsd_call_syscall(AFSOP_VOLUMEINFO, fullpn_VolInfoFile);
2369
2370     /*
2371      * Give the kernel the names of the AFS files cached on the workstation's
2372      * disk.
2373      */
2374     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE)) {
2375         int nocachefile = 0;
2376         if (afsd_debug)
2377             printf
2378                 ("%s: Calling AFSOP_CACHEFILE for each of the %d files in '%s'\n",
2379                  rn, cacheFiles, cacheBaseDir);
2380         /* ... and again ... */
2381         for (currVFile = 0; currVFile < cacheFiles; currVFile++) {
2382             if (!nocachefile) {
2383                 sprintf(fullpn_VFile, "%s/D%d/V%d", cacheBaseDir, dir_for_V[currVFile], currVFile);
2384                 code = afsd_call_syscall(AFSOP_CACHEFILE, fullpn_VFile);
2385                 if (code) {
2386                     if (currVFile == 0) {
2387                         if (afsd_debug)
2388                             printf
2389                                 ("%s: Calling AFSOP_CACHEINODE for each of the %d files in '%s'\n",
2390                                  rn, cacheFiles, cacheBaseDir);
2391                         nocachefile = 1;
2392                     } else {
2393                         printf
2394                             ("%s: Error calling AFSOP_CACHEFILE for '%s'\n",
2395                              rn, fullpn_VFile);
2396                         exit(1);
2397                     }
2398                 } else {
2399                     continue;
2400                 }
2401                 /* fall through to setup-by-inode */
2402             }
2403 #ifdef AFS_SGI62_ENV
2404             afsd_call_syscall(AFSOP_CACHEINODE,
2405                          (afs_uint32) (inode_for_V[currVFile] >> 32),
2406                          (afs_uint32) (inode_for_V[currVFile] & 0xffffffff));
2407 #elif !(defined(AFS_LINUX26_ENV) || defined(AFS_CACHE_VNODE_PATH))
2408             afsd_call_syscall(AFSOP_CACHEINODE, inode_for_V[currVFile]);
2409 #else
2410             printf
2411                 ("%s: Error calling AFSOP_CACHEINODE: not configured\n",
2412                  rn);
2413             exit(1);
2414 #endif
2415         }
2416     }
2417     /*end for */
2418     /*
2419      * All the necessary info has been passed into the kernel to run an AFS
2420      * system.  Give the kernel our go-ahead.
2421      */
2422     if (afsd_debug)
2423         printf("%s: Calling AFSOP_GO with cacheSetTime = %d\n", rn,
2424                0);
2425         afsd_call_syscall(AFSOP_GO, 0);
2426
2427     /*
2428      * At this point, we have finished passing the kernel all the info
2429      * it needs to set up the AFS.  Mount the AFS root.
2430      */
2431     printf("%s: All AFS daemons started.\n", rn);
2432
2433     if (afsd_verbose)
2434         printf("%s: Forking trunc-cache daemon.\n", rn);
2435     fork_syscall(rn, AFSOP_START_TRUNCDAEMON);
2436
2437     if (!enable_nomount) {
2438         afsd_mount_afs(rn, afsd_cacheMountDir);
2439     }
2440
2441 #ifndef UKERNEL
2442     if (afsd_rmtsys) {
2443         if (afsd_verbose)
2444             printf("%s: Forking 'rmtsys' daemon.\n", rn);
2445         afsd_fork(0, rmtsysd_thread, NULL);
2446     }
2447 #endif /* !UKERNEL */
2448     /*
2449      * Exit successfully.
2450      */
2451     return 0;
2452 }
2453
2454 #include "AFS_component_version_number.c"
2455
2456 void
2457 afsd_init(void)
2458 {
2459     struct cmd_syndesc *ts;
2460
2461     ts = cmd_CreateSyntax(NULL, mainproc, NULL, "start AFS");
2462
2463     /* 0 - 10 */
2464     cmd_AddParmAtOffset(ts, OPT_blocks, "-blocks", CMD_SINGLE,
2465                         CMD_OPTIONAL, "1024 byte blocks in cache");
2466     cmd_AddParmAtOffset(ts, OPT_files, "-files", CMD_SINGLE,
2467                         CMD_OPTIONAL, "files in cache");
2468     cmd_AddParmAtOffset(ts, OPT_rootvol, "-rootvol", CMD_SINGLE,
2469                         CMD_OPTIONAL, "name of AFS root volume");
2470     cmd_AddParmAtOffset(ts, OPT_stat, "-stat", CMD_SINGLE,
2471                         CMD_OPTIONAL, "number of stat entries");
2472     cmd_AddParmAtOffset(ts, OPT_memcache, "-memcache", CMD_FLAG,
2473                         CMD_OPTIONAL, "run diskless");
2474     cmd_AddParmAtOffset(ts, OPT_cachedir, "-cachedir", CMD_SINGLE,
2475                         CMD_OPTIONAL, "cache directory");
2476     cmd_AddParmAtOffset(ts, OPT_mountdir, "-mountdir", CMD_SINGLE,
2477                         CMD_OPTIONAL, "mount location");
2478     cmd_AddParmAtOffset(ts, OPT_daemons, "-daemons", CMD_SINGLE,
2479                         CMD_OPTIONAL, "number of daemons to use");
2480     cmd_AddParmAtOffset(ts, OPT_nosettime, "-nosettime", CMD_FLAG,
2481                         CMD_OPTIONAL, "don't set the time");
2482     cmd_AddParmAtOffset(ts, OPT_verbose, "-verbose", CMD_FLAG,
2483                         CMD_OPTIONAL, "display lots of information");
2484     cmd_AddParmAtOffset(ts, OPT_rmtsys, "-rmtsys", CMD_FLAG,
2485                         CMD_OPTIONAL, "start NFS rmtsysd program");
2486     cmd_AddParmAtOffset(ts, OPT_debug, "-debug", CMD_FLAG,
2487                         CMD_OPTIONAL, "display debug info");
2488     cmd_AddParmAtOffset(ts, OPT_chunksize, "-chunksize", CMD_SINGLE,
2489                         CMD_OPTIONAL, "log(2) of chunk size");
2490     cmd_AddParmAtOffset(ts, OPT_dcache, "-dcache", CMD_SINGLE,
2491                         CMD_OPTIONAL, "number of dcache entries");
2492     cmd_AddParmAtOffset(ts, OPT_volumes, "-volumes", CMD_SINGLE,
2493                         CMD_OPTIONAL, "number of volume entries");
2494     cmd_AddParmAtOffset(ts, OPT_biods, "-biods", CMD_SINGLE,
2495                         CMD_OPTIONAL, "number of bkg I/O daemons (aix vm)");
2496     cmd_AddParmAtOffset(ts, OPT_prealloc, "-prealloc", CMD_SINGLE,
2497                         CMD_OPTIONAL, "number of 'small' preallocated blocks");
2498     cmd_AddParmAtOffset(ts, OPT_confdir, "-confdir", CMD_SINGLE,
2499                         CMD_OPTIONAL, "configuration directory");
2500     cmd_AddParmAtOffset(ts, OPT_logfile, "-logfile", CMD_SINGLE,
2501                         CMD_OPTIONAL, "Place to keep the CM log");
2502     cmd_AddParmAtOffset(ts, OPT_waitclose, "-waitclose", CMD_FLAG,
2503                         CMD_OPTIONAL, "make close calls synchronous");
2504     cmd_AddParmAtOffset(ts, OPT_shutdown, "-shutdown", CMD_FLAG,
2505                         CMD_OPTIONAL, "Shutdown all afs state");
2506     cmd_AddParmAtOffset(ts, OPT_peerstats, "-enable_peer_stats", CMD_FLAG,
2507                         CMD_OPTIONAL | CMD_HIDE,
2508                         "Collect rpc statistics by peer");
2509     cmd_AddParmAtOffset(ts, OPT_processstats, "-enable_process_stats",
2510                         CMD_FLAG, CMD_OPTIONAL | CMD_HIDE,
2511                         "Collect rpc statistics for this process");
2512     cmd_AddParmAtOffset(ts, OPT_memallocsleep, "-mem_alloc_sleep",
2513                         CMD_FLAG, CMD_OPTIONAL | CMD_HIDE,
2514                         "Allow sleeps when allocating memory cache");
2515     cmd_AddParmAtOffset(ts, OPT_afsdb, "-afsdb", CMD_FLAG,
2516                         CMD_OPTIONAL, "Enable AFSDB support");
2517     cmd_AddParmAtOffset(ts, OPT_filesdir, "-files_per_subdir", CMD_SINGLE,
2518                         CMD_OPTIONAL,
2519                         "log(2) of the number of cache files per "
2520                         "cache subdirectory");
2521     cmd_AddParmAtOffset(ts, OPT_dynroot, "-dynroot", CMD_FLAG,
2522                         CMD_OPTIONAL, "Enable dynroot support");
2523     cmd_AddParmAtOffset(ts, OPT_fakestat, "-fakestat", CMD_FLAG,
2524                         CMD_OPTIONAL,
2525                         "Enable fakestat support for cross-cell mounts");
2526     cmd_AddParmAtOffset(ts, OPT_fakestatall, "-fakestat-all", CMD_FLAG,
2527                         CMD_OPTIONAL,
2528                         "Enable fakestat support for all mounts");
2529     cmd_AddParmAtOffset(ts, OPT_nomount, "-nomount", CMD_FLAG,
2530                         CMD_OPTIONAL, "Do not mount AFS");
2531     cmd_AddParmAtOffset(ts, OPT_backuptree, "-backuptree", CMD_FLAG,
2532                         CMD_OPTIONAL,
2533                         "Prefer backup volumes for mointpoints in backup "
2534                         "volumes");
2535     cmd_AddParmAtOffset(ts, OPT_rxbind, "-rxbind", CMD_FLAG,
2536                         CMD_OPTIONAL,
2537                         "Bind the Rx socket (one interface only)");
2538     cmd_AddParmAtOffset(ts, OPT_settime, "-settime", CMD_FLAG,
2539                         CMD_OPTIONAL, "set the time");
2540     cmd_AddParmAtOffset(ts, OPT_rxpck, "-rxpck", CMD_SINGLE, CMD_OPTIONAL,
2541                         "set rx_extraPackets to this value");
2542     cmd_AddParmAtOffset(ts, OPT_splitcache, "-splitcache", CMD_SINGLE,
2543                         CMD_OPTIONAL,
2544                         "Percentage RW versus RO in cache (specify as 60/40)");
2545     cmd_AddParmAtOffset(ts, OPT_nodynvcache, "-disable-dynamic-vcaches",
2546                         CMD_FLAG, CMD_OPTIONAL,
2547                         "disable stat/vcache cache growing as needed");
2548     cmd_AddParmAtOffset(ts, OPT_rxmaxmtu, "-rxmaxmtu", CMD_SINGLE,
2549                         CMD_OPTIONAL, "set rx max MTU to use");
2550     cmd_AddParmAtOffset(ts, OPT_dynrootsparse, "-dynroot-sparse", CMD_FLAG,
2551                         CMD_OPTIONAL,
2552                         "Enable dynroot support with minimal cell list");
2553     cmd_AddParmAtOffset(ts, OPT_rxmaxfrags, "-rxmaxfrags", CMD_SINGLE,
2554                         CMD_OPTIONAL,
2555                         "Set the maximum number of UDP fragments Rx should "
2556                         "send/receive per Rx packet");
2557 }
2558
2559 int
2560 afsd_parse(int argc, char **argv)
2561 {
2562     return cmd_Dispatch(argc, argv);
2563 }
2564
2565 struct afsd_syscall_args {
2566     long syscall;
2567     long param1;
2568     long param2;
2569     long param3;
2570     long param4;
2571     long param5;
2572     const char *rn;
2573     int rxpri;
2574 };
2575
2576 /**
2577  * entry point for calling a syscall from another proc/thread.
2578  *
2579  * @param[in] rock  a struct afsd_syscall_args* specifying what syscall to call
2580  *
2581  * @return unused
2582  *   @retval NULL always
2583  */
2584 static void *
2585 call_syscall_thread(void *rock)
2586 {
2587     struct afsd_syscall_args *args = rock;
2588     int code;
2589
2590     if (args->rxpri) {
2591         afsd_set_rx_rtpri();
2592     }
2593
2594     code = afsd_call_syscall(args->syscall, args->param1, args->param2,
2595                                  args->param3, args->param4, args->param5);
2596     if (code && args->syscall == AFSOP_START_CS) {
2597         printf("%s: No check server daemon in client.\n", args->rn);
2598     }
2599
2600     free(args);
2601
2602     return NULL;
2603 }
2604
2605 /**
2606  * common code for calling a syscall in another proc/thread.
2607  *
2608  * @param[in] rx   1 if this is a thread for RX stuff, 0 otherwise
2609  * @param[in] wait 1 if we should wait for the new proc/thread to finish, 0 to
2610  *                 let it run in the background
2611  * @param[in] rn   the name of the running program
2612  * @param[in] syscall syscall to run
2613  */
2614 static void
2615 fork_syscall_impl(int rx, int wait, const char *rn, long syscall, long param1,
2616                   long param2, long param3, long param4, long param5)
2617 {
2618     struct afsd_syscall_args *args;
2619
2620     args = malloc(sizeof(*args));
2621
2622     args->syscall = syscall;
2623     args->param1 = param1;
2624     args->param2 = param2;
2625     args->param3 = param3;
2626     args->param4 = param4;
2627     args->param5 = param5;
2628     args->rxpri = rx;
2629     args->rn = rn;
2630
2631     afsd_fork(wait, call_syscall_thread, args);
2632 }
2633
2634 /**
2635  * call a syscall in another process or thread.
2636  */
2637 static void
2638 fork_syscall(const char *rn, long syscall, long param1, long param2,
2639              long param3, long param4, long param5)
2640 {
2641     fork_syscall_impl(0, 0, rn, syscall, param1, param2, param3, param4, param5);
2642 }
2643
2644 /**
2645  * call a syscall in another process or thread, and give it RX priority.
2646  */
2647 static void
2648 fork_rx_syscall(const char *rn, long syscall, long param1, long param2,
2649                 long param3, long param4, long param5)
2650 {
2651     fork_syscall_impl(1, 0, rn, syscall, param1, param2, param3, param4, param5);
2652 }
2653
2654 #if defined(AFS_SUN510_ENV) && defined(RXK_LISTENER_ENV)
2655 /**
2656  * call a syscall in another process or thread, give it RX priority, and wait
2657  * for it to finish before returning.
2658  */
2659 static void
2660 fork_rx_syscall_wait(const char *rn, long syscall, long param1, long param2,
2661                      long param3, long param4, long param5)
2662 {
2663     fork_syscall_impl(1, 1, rn, syscall, param1, param2, param3, param4, param5);
2664 }
2665 #endif /* AFS_SUN510_ENV && RXK_LISTENER_ENV */