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