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