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