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