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