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