DEVEL15-windows-64bit-printf-sanity-20090218
[openafs.git] / src / afsd / afsd.c
index a258aa1..17b3e32 100644 (file)
@@ -133,7 +133,6 @@ RCSID
 #include <netinet/in.h>
 #include <afs/afs_args.h>
 #include <afs/cellconfig.h>
-#include <afs/auth.h>
 #include <ctype.h>
 #include <afs/afssyscalls.h>
 #include <afs/afsutil.h>
@@ -165,6 +164,36 @@ kern_return_t DiskArbStart(mach_port_t *);
 kern_return_t DiskArbDiskAppearedWithMountpointPing_auto(char *, unsigned int,
                                                         char *);
 #define DISK_ARB_NETWORK_DISK_FLAG 8
+
+#include <mach/mach_port.h>
+#include <mach/mach_interface.h>
+#include <mach/mach_init.h>
+
+#include <CoreFoundation/CoreFoundation.h>
+
+#include <SystemConfiguration/SystemConfiguration.h>
+#include <SystemConfiguration/SCDynamicStore.h>
+
+#include <IOKit/pwr_mgt/IOPMLib.h>
+#include <IOKit/IOMessage.h>
+
+#include <dns_sd.h>
+
+typedef struct DNSSDState
+{
+    DNSServiceRef       service;
+    CFRunLoopSourceRef  source;
+    CFSocketRef         socket;
+} DNSSDState;
+
+static io_connect_t root_port;
+static IONotificationPortRef notify;
+static io_object_t iterator;
+static CFRunLoopSourceRef source;
+static DNSSDState dnsstate;
+
+static int event_pid;
+
 #endif /* AFS_DARWIN_ENV */
 
 #ifndef MOUNT_AFS
@@ -263,7 +292,12 @@ int createAndTrunc = O_CREAT | O_TRUNC;    /*Create & truncate on open */
 int ownerRWmode = 0600;                /*Read/write OK by owner */
 static int filesSet = 0;       /*True if number of files explicitly set */
 static int nFilesPerDir = 2048;        /* # files per cache dir */
-static int nDaemons = 2;       /* Number of background daemons */
+#if defined(AFS_CACHE_BYPASS)
+#define AFSD_NDAEMONS 4
+#else
+#define AFSD_NDAEMONS 2
+#endif
+static int nDaemons = AFSD_NDAEMONS;   /* Number of background daemons */
 static int chunkSize = 0;      /* 2^chunkSize bytes per chunk */
 static int dCacheSize;         /* # of dcache entries */
 static int vCacheSize = 200;   /* # of volume cache entries */
@@ -305,8 +339,10 @@ int *dir_for_V = NULL;             /* Array: dir of each cache file.
                                 * -2: file exists in top-level
                                 * >=0: file exists in Dxxx
                                 */
+#if !defined(AFS_CACHE_VNODE_PATH) && !defined(LINUX_USE_FH)
 AFSD_INO_T *inode_for_V;       /* Array of inodes for desired
                                 * cache files */
+#endif
 int missing_DCacheFile = 1;    /*Is the DCACHEFILE missing? */
 int missing_VolInfoFile = 1;   /*Is the VOLINFOFILE missing? */
 int missing_CellInfoFile = 1;  /*Is the CELLINFOFILE missing? */
@@ -315,6 +351,162 @@ struct afs_cacheParams cparams;   /* params passed to cache manager */
 
 static int HandleMTab();
 
+#ifdef AFS_DARWIN_ENV
+static void
+afsd_sleep_callback(void * refCon, io_service_t service, 
+                   natural_t messageType, void * messageArgument )
+{
+    afs_int32 code;
+    
+    switch (messageType) {
+    case kIOMessageCanSystemSleep:
+       /* Idle sleep is about to kick in; can 
+          prevent sleep by calling IOCancelPowerChange, otherwise 
+          if we don't ack in 30s the system sleeps anyway */
+       
+       /* allow it */
+       IOAllowPowerChange(root_port, (long)messageArgument);
+       break;
+       
+    case kIOMessageSystemWillSleep:
+       /* The system WILL go to sleep. Ack or suffer delay */
+       
+       IOAllowPowerChange(root_port, (long)messageArgument);
+       break;
+       
+    case kIOMessageSystemWillRestart:
+       /* The system WILL restart. Ack or suffer delay */
+       
+       IOAllowPowerChange(root_port, (long)messageArgument);
+       break;
+       
+    case kIOMessageSystemWillPowerOn:
+    case kIOMessageSystemHasPoweredOn:
+       /* coming back from sleep */
+       
+       IOAllowPowerChange(root_port, (long)messageArgument);
+       break;
+       
+    default:
+       IOAllowPowerChange(root_port, (long)messageArgument);
+       break;
+    }
+}
+
+static void
+afsd_update_addresses(CFRunLoopTimerRef timer, void *info)
+{
+    /* parse multihomed address files */
+    afs_int32 addrbuf[MAXIPADDRS], maskbuf[MAXIPADDRS],
+       mtubuf[MAXIPADDRS];
+    char reason[1024];
+    afs_int32 code;
+
+    code =
+       parseNetFiles(addrbuf, maskbuf, mtubuf, MAXIPADDRS, reason,
+                     AFSDIR_CLIENT_NETINFO_FILEPATH,
+                     AFSDIR_CLIENT_NETRESTRICT_FILEPATH);
+
+    if (code > 0) {
+       /* Note we're refreshing */
+       code = code | 0x40000000;
+       call_syscall(AFSOP_ADVISEADDR, code, addrbuf, maskbuf, mtubuf);
+    } else
+       printf("ADVISEADDR: Error in specifying interface addresses:%s\n",
+              reason);
+}
+
+/* This function is called when the system's ip addresses may have changed. */
+static void
+afsd_ipaddr_callback (SCDynamicStoreRef store, CFArrayRef changed_keys, void *info)
+{
+      CFRunLoopTimerRef timer;
+
+      timer = CFRunLoopTimerCreate (NULL, CFAbsoluteTimeGetCurrent () + 1.0,
+                                   0.0, 0, 0, afsd_update_addresses, NULL);
+      CFRunLoopAddTimer (CFRunLoopGetCurrent (), timer,
+                        kCFRunLoopDefaultMode);
+      CFRelease (timer);
+}
+
+static void 
+afsd_event_cleanup(int signo) {
+    DNSSDState *query = &dnsstate;
+
+    CFRunLoopRemoveSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
+    CFRelease (source);
+    IODeregisterForSystemPower(&iterator);
+    IOServiceClose(root_port);
+    IONotificationPortDestroy(notify);
+
+    exit(0);
+}
+
+/* Adapted from "Living in a Dynamic TCP/IP Environment" technote. */
+static Boolean
+afsd_install_events(void)
+{
+    SCDynamicStoreContext ctx = {0};
+    SCDynamicStoreRef store;
+
+    root_port = IORegisterForSystemPower(0,&notify,afsd_sleep_callback,&iterator);
+    
+    if (root_port) {
+       CFRunLoopAddSource(CFRunLoopGetCurrent(),
+                          IONotificationPortGetRunLoopSource(notify),
+                          kCFRunLoopDefaultMode);
+    }
+    
+    
+    store = SCDynamicStoreCreate (NULL,
+                                 CFSTR ("AddIPAddressListChangeCallbackSCF"),
+                                 afsd_ipaddr_callback, &ctx);
+    
+    if (store) {
+       const void *keys[1];
+       
+       /* Request IPV4 address change notification */
+       keys[0] = (SCDynamicStoreKeyCreateNetworkServiceEntity
+                  (NULL, kSCDynamicStoreDomainState,
+                   kSCCompAnyRegex, kSCEntNetIPv4));
+       
+#if 0
+       /* This should tell us when the hostname(s) change. do we care? */
+       keys[N] = SCDynamicStoreKeyCreateHostNames (NULL);
+#endif
+       
+       if (keys[0] != NULL) {
+           CFArrayRef pattern_array;
+           
+           pattern_array = CFArrayCreate (NULL, keys, 1,
+                                          &kCFTypeArrayCallBacks);
+           
+           if (pattern_array != NULL)
+           {
+               SCDynamicStoreSetNotificationKeys (store, NULL, pattern_array);
+               source = SCDynamicStoreCreateRunLoopSource (NULL, store, 0);
+               
+               CFRelease (pattern_array);
+           }
+           
+           if (keys[0] != NULL)
+               CFRelease (keys[0]);
+       }
+       
+       CFRelease (store); 
+    }
+    
+    if (source != NULL) {
+       CFRunLoopAddSource (CFRunLoopGetCurrent(),
+                           source, kCFRunLoopDefaultMode);
+    }
+    
+    signal(SIGTERM, afsd_event_cleanup);
+
+    CFRunLoopRun();
+}
+#endif
+
 /* ParseArgs is now obsolete, being handled by cmd */
 
 /*------------------------------------------------------------------------------
@@ -799,7 +991,7 @@ doSweepAFSCache(vFilesFound, directory, dirNum, maxDir)
        if (afsd_debug) {
            printf("%s: Current directory entry:\n", rn);
 #ifdef AFS_SGI62_ENV
-           printf("\tinode=%lld, reclen=%d, name='%s'\n", currp->d_ino,
+           printf("\tinode=%" AFS_INT64_FMT ", reclen=%d, name='%s'\n", currp->d_ino,
                   currp->d_reclen, currp->d_name);
 #else
            printf("\tinode=%d, reclen=%d, name='%s'\n", currp->d_ino,
@@ -822,7 +1014,9 @@ doSweepAFSCache(vFilesFound, directory, dirNum, maxDir)
             * file's inode, directory, and bump the number of files found
             * total and in this directory.
             */
+#if !defined(AFS_CACHE_VNODE_PATH) && !defined(LINUX_USE_FH)
            inode_for_V[vFileNum] = currp->d_ino;
+#endif
            dir_for_V[vFileNum] = dirNum;       /* remember this directory */
 
            if (!maxDir) {
@@ -959,7 +1153,9 @@ doSweepAFSCache(vFilesFound, directory, dirNum, maxDir)
                           vFileNum);
                else {
                    struct stat statb;
+#if !defined(AFS_CACHE_VNODE_PATH) && !defined(LINUX_USE_FH)
                    assert(inode_for_V[vFileNum] == (AFSD_INO_T) 0);
+#endif
                    sprintf(vFilePtr, "D%d/V%d", thisDir, vFileNum);
                    if (afsd_verbose)
                        printf("%s: Creating '%s'\n", rn, fullpn_VFile);
@@ -970,7 +1166,9 @@ doSweepAFSCache(vFilesFound, directory, dirNum, maxDir)
                    if (CreateCacheFile(fullpn_VFile, &statb))
                        printf("%s: Can't create '%s'\n", rn, fullpn_VFile);
                    else {
+#if !defined(AFS_CACHE_VNODE_PATH) && !defined(LINUX_USE_FH)
                        inode_for_V[vFileNum] = statb.st_ino;
+#endif
                        dir_for_V[vFileNum] = thisDir;
                        cache_dir_list[thisDir]++;
                        (*vFilesFound)++;
@@ -1070,11 +1268,17 @@ CheckCacheBaseDir(char *dir)
        if (res != 0) {
            return "unable to statfs cache base directory";
        }
+#if !defined(LINUX_USE_FH)
        if (statfsbuf.f_type == 0x52654973) {   /* REISERFS_SUPER_MAGIC */
            return "cannot use reiserfs as cache partition";
        } else if (statfsbuf.f_type == 0x58465342) {    /* XFS_SUPER_MAGIC */
            return "cannot use xfs as cache partition";
+       } else if (statfsbuf.f_type == 0x01021994) {    /* TMPFS_SUPER_MAGIC */
+            return "cannot use tmpfs as cache partition";
+        } else if (statfsbuf.f_type != 0xEF53) {
+            return "must use ext2 or ext3 for cache partition";
        }
+#endif
     }
 #endif
 
@@ -1194,8 +1398,8 @@ SweepAFSCache(vFilesFound)
     return doSweepAFSCache(vFilesFound, cacheBaseDir, -2, maxDir);
 }
 
-static
-ConfigCell(struct afsconf_cell *aci, char *arock, struct afsconf_dir *adir)
+static int
+ConfigCell(struct afsconf_cell *aci, void *arock, struct afsconf_dir *adir)
 {
     int isHomeCell;
     int i, code;
@@ -1227,7 +1431,7 @@ ConfigCell(struct afsconf_cell *aci, char *arock, struct afsconf_dir *adir)
 
 static
 ConfigCellAlias(struct afsconf_cellalias *aca,
-               char *arock, struct afsconf_dir *adir)
+               void *arock, struct afsconf_dir *adir)
 {
     /* push the alias into the kernel */
     call_syscall(AFSOP_ADDCELLALIAS, aca->aliasName, aca->realName);
@@ -1248,6 +1452,16 @@ AfsdbLookupHandler()
     kernelMsg[1] = 0;
     acellName[0] = '\0';
 
+#ifdef AFS_DARWIN_ENV
+    /* Fork the event handler also. */
+    code = fork();
+    if (code == 0) {
+       afsd_install_events();
+       exit(1);
+    } else if (code != -1) {
+       event_pid = code;
+    }
+#endif
     while (1) {
        /* On some platforms you only get 4 args to an AFS call */
        int sizeArg = ((sizeof acellName) << 16) | (sizeof kernelMsg);
@@ -1277,7 +1491,9 @@ AfsdbLookupHandler()
            acellName[sizeof(acellName) - 1] = '\0';
        }
     }
-
+#ifdef AFS_DARWIN_ENV
+    kill(event_pid, SIGTERM);
+#endif
     exit(1);
 }
 #endif
@@ -1308,7 +1524,7 @@ AfsdbLookupHandler()
 #endif
 #endif
 
-mainproc(struct cmd_syndesc *as, char *arock)
+mainproc(struct cmd_syndesc *as, void *arock)
 {
     static char rn[] = "afsd"; /*Name of this routine */
     afs_int32 code;            /*Result of fork() */
@@ -1483,7 +1699,7 @@ mainproc(struct cmd_syndesc *as, char *arock)
     if (as->parms[25].items) {
        /* -files_per_subdir */
        int res = atoi(as->parms[25].items->data);
-       if (res < 10 || res > 2 ^ 30) {
+       if (res < 10 || res > (1 << 30)) {
            printf
                ("afsd:invalid number of files per subdir, \"%s\". Ignored\n",
                 as->parms[25].items->data);
@@ -1683,12 +1899,19 @@ mainproc(struct cmd_syndesc *as, char *arock)
            if (afsd_verbose)
                printf("%s: cacheFiles autotuned to %d\n", rn, cacheFiles);
        }
+#if 0
+       /* This actually needs to
+          1) use powers of 2
+          2) not second-guess when a chunksize comes from the command line
+          3) be less, um, small. 2^2?? 
+       */
        /* Sanity check chunkSize */
        i = max(cacheBlocks / 1000, cacheBlocks / cacheFiles);
        chunkSize = min(chunkSize, i);
        chunkSize = max(chunkSize, 2);
        if (afsd_verbose)
            printf("%s: chunkSize autotuned to %d\n", rn, chunkSize);
+#endif
 
        if (!sawDCacheSize) {
            dCacheSize = cacheFiles / 2;
@@ -1715,6 +1938,7 @@ mainproc(struct cmd_syndesc *as, char *arock)
                   cacheStatEntries);
     }
 
+#if !defined(AFS_CACHE_VNODE_PATH) && !defined(LINUX_USE_FH)
     /*
      * Create and zero the inode table for the desired cache files.
      */
@@ -1729,6 +1953,7 @@ mainproc(struct cmd_syndesc *as, char *arock)
     if (afsd_debug)
        printf("%s: %d inode_for_V entries at 0x%x, %d bytes\n", rn,
               cacheFiles, inode_for_V, (cacheFiles * sizeof(AFSD_INO_T)));
+#endif
 
     /*
      * Set up all the pathnames we'll need for later.
@@ -1741,12 +1966,13 @@ mainproc(struct cmd_syndesc *as, char *arock)
 
     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE)
        && (fsTypeMsg = CheckCacheBaseDir(cacheBaseDir))) {
+#ifdef AFS_SUN5_ENV
        printf("%s: WARNING: Cache dir check failed (%s)\n", rn, fsTypeMsg);
-    }
-#if 0
-    fputs(AFS_GOVERNMENT_MESSAGE, stdout);
-    fflush(stdout);
+#else
+       printf("%s: ERROR: Cache dir check failed (%s)\n", rn, fsTypeMsg);
+       exit(1);
 #endif
+    }
 
     /*
      * Set up all the kernel processes needed for AFS.
@@ -1916,6 +2142,23 @@ mainproc(struct cmd_syndesc *as, char *arock)
                     rn, vFilesFound, cacheFiles, cacheIteration);
        } while ((vFilesFound < cacheFiles)
                 && (cacheIteration < MAX_CACHE_LOOPS));
+#ifdef AFS_CACHE_VNODE_PATH
+       if (afsd_debug)
+           printf
+               ("%s: Calling AFSOP_CACHEBASEDIR with '%s'\n",
+                rn, cacheBaseDir);
+       call_syscall(AFSOP_CACHEBASEDIR, cacheBaseDir);
+       if (afsd_debug)
+           printf
+               ("%s: Calling AFSOP_CACHEDIRS with %d dirs\n",
+                rn, nFilesPerDir);
+       call_syscall(AFSOP_CACHEDIRS, nFilesPerDir);
+       if (afsd_debug)
+           printf
+               ("%s: Calling AFSOP_CACHEFILES with %d files\n",
+                rn, cacheFiles);
+       call_syscall(AFSOP_CACHEFILES, cacheFiles);
+#endif
     } else if (afsd_verbose)
        printf("%s: Using memory cache, not swept\n", rn);
 
@@ -2050,6 +2293,7 @@ mainproc(struct cmd_syndesc *as, char *arock)
     if (!(cacheFlags & AFSCALL_INIT_MEMCACHE))
        call_syscall(AFSOP_VOLUMEINFO, fullpn_VolInfoFile);
 
+#ifndef AFS_CACHE_VNODE_PATH
     /*
      * Give the kernel the names of the AFS files cached on the workstation's
      * disk.
@@ -2065,10 +2309,15 @@ mainproc(struct cmd_syndesc *as, char *arock)
                         (afs_uint32) (inode_for_V[currVFile] >> 32),
                         (afs_uint32) (inode_for_V[currVFile] & 0xffffffff));
 #else
+#if defined(LINUX_USE_FH)
+           sprintf(fullpn_VFile, "%s/D%d/V%d", cacheBaseDir, dir_for_V[currVFile], currVFile);
+           call_syscall(AFSOP_CACHEFILE, fullpn_VFile);
+#else
            call_syscall(AFSOP_CACHEINODE, inode_for_V[currVFile]);
 #endif
+#endif
        }
-
+#endif
 
     /*end for */
     /*
@@ -2387,7 +2636,7 @@ call_syscall(param1, param2, param3, param4, param5, param6, param7)
                param5, param6, param7);
 #endif
 
-    if (afsd_verbose)
+    if (afsd_debug)
        printf("SScall(%d, %d, %d)=%d ", AFS_SYSCALL, AFSCALL_CALL, param1,
               error);
     return (error);