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