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