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