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