viced: host hash address collisions
[openafs.git] / src / viced / host.c
index 7e72394..819a3e5 100644 (file)
@@ -12,8 +12,6 @@
 #include <afsconfig.h>
 #include <afs/param.h>
 
-RCSID
-    ("$Header$");
 
 #include <stdio.h>
 #include <errno.h>
@@ -33,6 +31,8 @@ RCSID
 #include <lwp.h>
 #include <lock.h>
 #include <afs/afsint.h>
+#define FSINT_COMMON_XG
+#include <afs/afscbint.h>
 #include <afs/rxgen_consts.h>
 #include <afs/nfs.h>
 #include <afs/errors.h>
@@ -87,13 +87,14 @@ int rxcon_client_key;
 static struct rx_securityClass *sc = NULL;
 
 static void h_SetupCallbackConn_r(struct host * host);
+static int h_threadquota(int);
 
 #define CESPERBLOCK 73
 struct CEBlock {               /* block of CESPERBLOCK file entries */
     struct client entry[CESPERBLOCK];
 };
 
-static void h_TossStuff_r(register struct host *host);
+void h_TossStuff_r(register struct host *host);
 
 /*
  * Make sure the subnet macros have been defined.
@@ -156,7 +157,7 @@ GetCE(void)
     entry = CEFree;
     CEFree = entry->next;
     CEs++;
-    memset((char *)entry, 0, CLIENT_TO_ZERO(entry));
+    memset(entry, 0, CLIENT_TO_ZERO(entry));
     return (entry);
 
 }                              /*GetCE */
@@ -244,7 +245,7 @@ GetHT(void)
     entry = HTFree;
     HTFree = entry->next;
     HTs++;
-    memset((char *)entry, 0, HOST_TO_ZERO(entry));
+    memset(entry, 0, HOST_TO_ZERO(entry));
     return (entry);
 
 }                              /*GetHT */
@@ -265,9 +266,8 @@ hpr_Initialize(struct ubik_client **uclient)
 {
     afs_int32 code;
     struct rx_connection *serverconns[MAXSERVERS];
-    struct rx_securityClass *sc[3];
+    struct rx_securityClass *sc;
     struct afsconf_dir *tdir;
-    struct ktc_token ttoken;
     afs_int32 scIndex;
     struct afsconf_cell info;
     afs_int32 i;
@@ -288,7 +288,8 @@ hpr_Initialize(struct ubik_client **uclient)
     
     code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
     if (code) {
-       ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s", cellstr, confDir, AFSDIR_CELLSERVDB_FILE));
+       ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s",
+                   cellstr, confDir->name, AFSDIR_CELLSERVDB_FILE));
        afsconf_Close(tdir);
        return code;
     }
@@ -300,55 +301,29 @@ hpr_Initialize(struct ubik_client **uclient)
         return code;
     }
     
-    scIndex = 2;
-    sc[0] = 0;
-    sc[1] = 0;
-    sc[2] = 0;
     /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
      * to force use of the KeyFile.  secLevel == 0 implies -noauth was
      * specified. */
     if ((afsconf_GetLatestKey(tdir, 0, 0) == 0)) {
-        code = afsconf_ClientAuthSecure(tdir, &sc[2], &scIndex);
+        code = afsconf_ClientAuthSecure(tdir, &sc, &scIndex);
         if (code)
            ViceLog(0, ("hpr_Initialize: clientauthsecure returns %d %s (so trying noauth)", code, afs_error_message(code)));
         if (code)
-            scIndex = 0;        /* use noauth */
-        if (scIndex != 2)
-            /* if there was a problem, an unauthenticated conn is returned */
-            sc[scIndex] = sc[2];
+            scIndex = RX_SECIDX_NULL;
     } else {
-        struct ktc_principal sname;
-        strcpy(sname.cell, info.name);
-        sname.instance[0] = 0;
-        strcpy(sname.name, "afs");
-        code = ktc_GetToken(&sname, &ttoken, sizeof(ttoken), NULL);
-        if (code)
-            scIndex = 0;
-        else {
-            if (ttoken.kvno >= 0 && ttoken.kvno <= 256)
-                /* this is a kerberos ticket, set scIndex accordingly */
-                scIndex = 2;
-            else {
-                ViceLog(0, ("hpr_Initialize: funny kvno (%d) in ticket, proceeding", ttoken.kvno));
-                scIndex = 2;
-            }
-            sc[2] =
-                rxkad_NewClientSecurityObject(rxkad_clear, &ttoken.sessionKey,
-                                              ttoken.kvno, ttoken.ticketLen,
-                                              ttoken.ticket);
-        }
+       afsconf_ClientAuthToken(&info, 0, &sc, &scIndex, NULL);
     }
-    if ((scIndex == 0) && (sc[0] == 0))
-        sc[0] = rxnull_NewClientSecurityObject();
-    if ((scIndex == 0))
+    if ((scIndex == RX_SECIDX_NULL) && (sc == NULL))
+        sc = rxnull_NewClientSecurityObject();
+    if (scIndex == RX_SECIDX_NULL)
        ViceLog(0, ("hpr_Initialize: Could not get afs tokens, running unauthenticated. [%d]", code));
     
     memset(serverconns, 0, sizeof(serverconns));        /* terminate list!!! */
     for (i = 0; i < info.numServers; i++) {
         serverconns[i] =
             rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
-                             info.hostAddr[i].sin_port, PRSRV, sc[scIndex],
-                             scIndex);
+                             info.hostAddr[i].sin_port, PRSRV,
+                            sc, scIndex);
     }
 
     code = ubik_ClientInit(serverconns, uclient);
@@ -356,7 +331,7 @@ hpr_Initialize(struct ubik_client **uclient)
        ViceLog(0, ("hpr_Initialize: ubik client init failed. [%d]", code));
     }
     afsconf_Close(tdir);
-    code = rxs_Release(sc[scIndex]);
+    code = rxs_Release(sc);
     return code;
 }
 
@@ -490,56 +465,6 @@ hpr_GetCPS(afs_int32 id, prlist *CPS)
 static short consolePort = 0;
 
 int
-h_Release(register struct host *host)
-{
-    H_LOCK;
-    h_Release_r(host);
-    H_UNLOCK;
-    return 0;
-}
-
-/**
- * If this thread does not have a hold on this host AND
- * if other threads also dont have any holds on this host AND
- * If either the HOSTDELETED or CLIENTDELETED flags are set
- * then toss the host
- */
-int
-h_Release_r(register struct host *host)
-{
-
-    if (!((host)->holds[h_holdSlot()] & ~h_holdbit())) {
-       if (!h_OtherHolds_r(host)) {
-           /* must avoid masking this until after h_OtherHolds_r runs
-            * but it should be run before h_TossStuff_r */
-           (host)->holds[h_holdSlot()] &= ~h_holdbit();
-           if ((host->hostFlags & HOSTDELETED)
-               || (host->hostFlags & CLIENTDELETED)) {
-               h_TossStuff_r(host);
-           }
-       } else
-           (host)->holds[h_holdSlot()] &= ~h_holdbit();
-    } else
-       (host)->holds[h_holdSlot()] &= ~h_holdbit();
-
-    return 0;
-}
-
-int
-h_OtherHolds_r(register struct host *host)
-{
-    register int i, bit, slot;
-    bit = h_holdbit();
-    slot = h_holdSlot();
-    for (i = 0; i < h_maxSlots; i++) {
-       if (host->holds[i] != ((i == slot) ? bit : 0)) {
-           return 1;
-       }
-    }
-    return 0;
-}
-
-int
 h_Lock_r(register struct host *host)
 {
     H_UNLOCK;
@@ -708,12 +633,12 @@ h_gethostcps_r(register struct host *host, register afs_int32 now)
             */
            host->hcpsfailed = 1;
            ViceLog(0,
-                   ("Warning:  GetHostCPS failed (%d) for %x (%s:%d); will retry\n",
+                   ("Warning:  GetHostCPS failed (%d) for %p (%s:%d); will retry\n",
                     code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
        } else {
            host->hcpsfailed = 0;
            ViceLog(1,
-                   ("gethost:  GetHostCPS failed (%d) for %x (%s:%d); ignored\n",
+                   ("gethost:  GetHostCPS failed (%d) for %p (%s:%d); ignored\n",
                     code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
        }
        if (host->hcps.prlist_val)
@@ -741,14 +666,12 @@ void
 h_flushhostcps(register afs_uint32 hostaddr, register afs_uint16 hport)
 {
     struct host *host;
-    int held = 0;
 
     H_LOCK;
-    h_Lookup_r(hostaddr, hport, &held, &host);
+    h_Lookup_r(hostaddr, hport, &host);
     if (host) {
        host->hcpsfailed = 1;
-       if (!held)
-           h_Release_r(host);
+       h_Release_r(host);
     }
     H_UNLOCK;
     return;
@@ -835,12 +758,14 @@ h_SetupCallbackConn_r(struct host * host)
     rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
 }
 
-/* Lookup a host given an IP address and UDP port number. */
-/* hostaddr and hport are in network order */
-/* Note: host should be released by caller if 0 == *heldp and non-null */
-/* hostaddr and hport are in network order */
+/* h_Lookup_r
+ * Lookup a host given an IP address and UDP port number.
+ * hostaddr and hport are in network order
+ * hostaddr and hport are in network order
+ * On return, refCount is incremented.
+ */
 int
-h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, int *heldp, struct host **hostp)
+h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, struct host **hostp)
 {
     afs_int32 now;
     struct host *host = NULL;
@@ -859,14 +784,12 @@ h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, int *heldp, struct host **hostp)
                *hostp = 0;
                return VBUSY;
            }
-           *heldp = h_Held_r(host);
-           if (!*heldp)
-               h_Hold_r(host);
+           h_Hold_r(host);
            h_Lock_r(host);
            if (host->hostFlags & HOSTDELETED) {
                h_Unlock_r(host);
-               if (!*heldp)
-                   h_Release_r(host);
+               h_Release_r(host);
+               host = NULL;
                goto restart;
            }
            h_Unlock_r(host);
@@ -878,7 +801,7 @@ h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, int *heldp, struct host **hostp)
                 * first time that the host is added to a group.  Also
                 * here we also retry on previous legitimate hcps failures.
                 *
-                * If we get here we still have a host hold.
+                * If we get here refCount is elevated.
                 */
                h_gethostcps_r(host, now);
            }
@@ -910,31 +833,27 @@ h_LookupUuid_r(afsUUID * uuidp)
 }                              /*h_Lookup */
 
 
-/*
- * h_Hold_r: Establish a hold by the current LWP on this host--the host
- * or its clients will not be physically deleted until all holds have
- * been released.
- * NOTE: h_Hold_r is a macro defined in host.h.
- */
-
 /* h_TossStuff_r:  Toss anything in the host structure (the host or
  * clients marked for deletion.  Called from h_Release_r ONLY.
  * To be called, there must be no holds, and either host->deleted
  * or host->clientDeleted must be set.
  */
-static void
+void
 h_TossStuff_r(register struct host *host)
 {
     register struct client **cp, *client;
-    int i;
+    int code;
 
-    /* if somebody still has this host held */
-    for (i = 0; (i < h_maxSlots) && (!(host)->holds[i]); i++);
-    if (i != h_maxSlots)
-       return;
+    /* make sure host doesn't go away over h_NBLock_r */
+    h_Hold_r(host);
+
+    code = h_NBLock_r(host);
+
+    /* don't use h_Release_r, since that may call h_TossStuff_r again */
+    h_Decrement_r(host);
 
     /* if somebody still has this host locked */
-    if (h_NBLock_r(host) != 0) {
+    if (code != 0) {
        char hoststr[16];
        ViceLog(0,
                ("Warning:  h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was locked.\n",
@@ -944,6 +863,17 @@ h_TossStuff_r(register struct host *host)
        h_Unlock_r(host);
     }
 
+    /* if somebody still has this host held */
+    /* we must check this _after_ h_NBLock_r, since h_NBLock_r can drop and
+     * reacquire H_LOCK */
+    if (host->refCount > 0) {
+       char hoststr[16];
+       ViceLog(0,
+               ("Warning:  h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was held.\n",
+                host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
+       return;
+    }
+
     /* ASSUMPTION: rxi_FreeConnection() does not yield */
     for (cp = &host->FirstClient; (client = *cp);) {
        if ((host->hostFlags & HOSTDELETED) || client->deleted) {
@@ -952,7 +882,8 @@ h_TossStuff_r(register struct host *host)
            if (code < 0) {
                char hoststr[16];
                ViceLog(0,
-                       ("Warning: h_TossStuff_r failed: Host %" AFS_PTR_FMT " (%s:%d) client %x was locked.\n",
+                       ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
+                        "client %p was locked.\n",
                         host, afs_inet_ntoa_r(host->host, hoststr),
                         ntohs(host->port), client));
                return;
@@ -961,7 +892,8 @@ h_TossStuff_r(register struct host *host)
            if (client->refCount) {
                char hoststr[16];
                ViceLog(0,
-                       ("Warning: h_TossStuff_r failed: Host %" AFS_PTR_FMT " (%s:%d) client %x refcount %d.\n",
+                       ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
+                        "client %p refcount %d.\n",
                         host, afs_inet_ntoa_r(host->host, hoststr),
                         ntohs(host->port), client, client->refCount));
                /* This is the same thing we do if the host is locked */
@@ -1030,19 +962,26 @@ h_TossStuff_r(register struct host *host)
 }                              /*h_TossStuff_r */
 
 
+
 /* h_Enumerate: Calls (*proc)(host, held, param) for at least each host in the
  * system at the start of the enumeration (perhaps more).  Hosts may be deleted
- * (have delete flag set); ditto for clients.  (*proc) is always called with
- * host h_held().  The hold state of the host with respect to this lwp is passed
- * to (*proc) as the param held.  The proc should return 0 if the host should be
- * released, 1 if it should be held after enumeration.
+ * (have delete flag set); ditto for clients.  refCount is always incremented
+ * before (*proc) is called.  The param flags is passed to (*proc) as the
+ * param flags, permitting (*proc) to stop the enumeration (BAIL).
+ *
+ * Needed?  Why not always h_Hold_r and h_Release_r in (*proc), or even -never-
+ * h_Hold_r or h_Release_r in (*proc)?
+ *
+ * **The proc should return 0 if the host should be released, 1 if it should
+ * be held after enumeration.
  */
 void
 h_Enumerate(int (*proc) (struct host*, int, void *), void *param)
 {
     register struct host *host, **list;
-    register int *held;
+    register int *flags;
     register int i, count;
+    int totalCount;
 
     H_LOCK;
     if (hostCount == 0) {
@@ -1051,44 +990,58 @@ h_Enumerate(int (*proc) (struct host*, int, void *), void *param)
     }
     list = (struct host **)malloc(hostCount * sizeof(struct host *));
     if (!list) {
-       ViceLog(0, ("Failed malloc in h_Enumerate\n"));
+       ViceLog(0, ("Failed malloc in h_Enumerate (list)\n"));
        assert(0);
     }
-    held = (int *)malloc(hostCount * sizeof(int));
-    if (!held) {
-       ViceLog(0, ("Failed malloc in h_Enumerate\n"));
+    flags = (int *)malloc(hostCount * sizeof(int));
+    if (!flags) {
+       ViceLog(0, ("Failed malloc in h_Enumerate (flags)\n"));
        assert(0);
     }
-    for (count = 0, host = hostList; host; host = host->next, count++) {
-       list[count] = host;
-       if (!(held[count] = h_Held_r(host)))
+    for (totalCount = count = 0, host = hostList;
+         host && totalCount < hostCount;
+        host = host->next, totalCount++) {
+
+       if (!(host->hostFlags & HOSTDELETED)) {
+           list[count] = host;
            h_Hold_r(host);
+           count++;
+       }
     }
-    if (count != hostCount) {
-       ViceLog(0, ("h_Enumerate found %d of %d hosts\n", count, hostCount));
+    if (totalCount != hostCount) {
+       ViceLog(0, ("h_Enumerate found %d of %d hosts\n", totalCount, hostCount));
+    } else if (host != NULL) {
+       ViceLog(0, ("h_Enumerate found more than %d hosts\n", hostCount));
+       ShutDownAndCore(PANIC);
     }
-    assert(count <= hostCount);
     H_UNLOCK;
     for (i = 0; i < count; i++) {
-       held[i] = (*proc) (list[i], held[i], param);
-       if (!H_ENUMERATE_ISSET_HELD(held[i]))
-           h_Release(list[i]); /* this might free up the host */
+       flags[i] = (*proc) (list[i], flags[i], param);
+       h_Release_r(list[i]);
        /* bail out of the enumeration early */
-       if (H_ENUMERATE_ISSET_BAIL(held[i]))
+       if (H_ENUMERATE_ISSET_BAIL(flags[i]))
            break;
     }
     free((void *)list);
-    free((void *)held);
-}                              /*h_Enumerate */
+    free((void *)flags);
+}      /* h_Enumerate */
+
 
 /* h_Enumerate_r (revised):
- * Calls (*proc)(host, held, param) for each host in hostList, starting
- * at enumstart
- * Hosts may be deleted (have delete flag set); ditto for clients.
- * (*proc) is always called with
- * host h_held() and the global host lock (H_LOCK) locked.The hold state of the
- * host with respect to this lwp is passed to (*proc) as the param held.
- * The proc should return 0 if the host should be released, 1 if it should
+ * Calls (*proc)(host, flags, param) for each host in hostList, starting
+ * at enumstart. Called only under H_LOCK.  Hosts may be deleted (have
+ * delete flag set); ditto for clients.  refCount is always incremented
+ * before (*proc) is called.  The param flags is passed to (*proc) as the
+ * param flags, permitting (*proc) to stop the enumeration (BAIL).
+ *
+ * Needed?  Why not always h_Hold_r and h_Release_r in (*proc), or even -never-
+ * h_Hold_r or h_Release_r in (*proc)?
+ *
+ * @note Assumes that hostList is only prepended to, that a host is never
+ *       inserted into the middle. Otherwise this would not be guaranteed to
+ *       terminate.
+ *
+ * **The proc should return 0 if the host should be released, 1 if it should
  * be held after enumeration.
  */
 void
@@ -1096,28 +1049,76 @@ h_Enumerate_r(int (*proc) (struct host *, int, void *),
              struct host *enumstart, void *param)
 {
     register struct host *host, *next;
-    int held = 0;
-    int nheld = 0;
+    int flags = 0;
+    int nflags = 0;
+    int count;
+    int origHostCount;
 
     if (hostCount == 0) {
        return;
     }
-    if (enumstart && !(held = h_Held_r(enumstart)))
-       h_Hold_r(enumstart); 
-    for (host = enumstart; host; host = next, held = nheld) {
+
+    host = enumstart;
+    enumstart = NULL;
+
+    /* find the first non-deleted host, so we know where to actually start
+     * enumerating */
+    for (count = 0; host && count < hostCount; count++) {
+       if (!(host->hostFlags & HOSTDELETED)) {
+           enumstart = host;
+           break;
+       }
+       host = host->next;
+    }
+    if (!enumstart) {
+       /* we didn't find a non-deleted host... */
+
+       if (host && count >= hostCount) {
+           /* ...because we found a loop */
+           ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", hostCount));
+           ShutDownAndCore(PANIC);
+       }
+
+       /* ...because the hostList is full of deleted hosts */
+       return;
+    }
+
+    h_Hold_r(enumstart);
+
+    /* remember hostCount, lest it change over the potential H_LOCK drop in
+     * h_Release_r */
+    origHostCount = hostCount;
+
+    for (count = 0, host = enumstart; host && count < origHostCount; host = next, flags = nflags, count++) {
        next = host->next;
-       if (next && !(nheld = h_Held_r(next)) && !H_ENUMERATE_ISSET_BAIL(held))
+
+       /* find the next non-deleted host */
+       while (next && (next->hostFlags & HOSTDELETED)) {
+           next = next->next;
+           /* inc count for the skipped-over host */
+           if (++count > origHostCount) {
+               ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
+               ShutDownAndCore(PANIC);
+           }
+       }
+       if (next && !H_ENUMERATE_ISSET_BAIL(flags))
            h_Hold_r(next);
-       held = (*proc) (host, held, param);
-       if (!H_ENUMERATE_ISSET_HELD(held))
-           h_Release_r(host); /* this might free up the host */
-       if (H_ENUMERATE_ISSET_BAIL(held)) {
-           if (!H_ENUMERATE_ISSET_HELD(nheld))
-               h_Release_r(next); /* this might free up the host */
-           break;
+
+       if (!(host->hostFlags & HOSTDELETED)) {
+           flags = (*proc) (host, flags, param);
+           if (H_ENUMERATE_ISSET_BAIL(flags)) {
+               h_Release_r(host); /* this might free up the host */
+               break;
+           }
        }
+       h_Release_r(host); /* this might free up the host */
     }
-}                              /*h_Enumerate_r */
+    if (host != NULL && count >= origHostCount) {
+       ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
+       ShutDownAndCore(PANIC);
+    }
+}      /*h_Enumerate_r */
+
 
 /* inserts a new HashChain structure corresponding to this UUID */
 void
@@ -1164,9 +1165,9 @@ h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
               return;
      afsUUID_to_string(uuid, uuid2, 127);
      ViceLog(125, 
-            ("h_AddHostToUuidHashTable_r: host %" AFS_PTR_FMT " (%s:%d) added as uuid %s\n",
+            ("h_AddHostToUuidHashTable_r: host %p (%s:%d) added as uuid %s\n",
              host, afs_inet_ntoa_r(chain->hostPtr->host, hoststr), 
-             ntohs(chain->hostPtr->port), uuid));
+             ntohs(chain->hostPtr->port), uuid2));
 }
 
 /* deletes a HashChain structure corresponding to this host */
@@ -1205,37 +1206,139 @@ h_DeleteHostFromUuidHashTable_r(struct host *host)
      return 0;
 }
 
-/* inserts a new HashChain structure corresponding to this address */
-void
-h_AddHostToAddrHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
+/*
+ * This is called with host locked and held.
+ *
+ * All addresses are in network byte order.
+ */
+static int
+invalidateInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
 {
-    int index;
-    struct h_AddrHashChain *chain;
-    int found = 0;
+    int i;
+    int number;
+    struct Interface *interface;
     char hoststr[16], hoststr2[16];
 
-    /* hash into proper bucket */
-    index = h_HashIndex(addr);
+    assert(host);
+    assert(host->interface);
 
-    /* don't add the same entry multiple times */
-    for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
-       if (chain->hostPtr == host) {
-           if (chain->addr != addr || chain->port != port) {
-               ViceLog(0, 
-                       ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " exists as %s:%d when adding %s:%d\n",
-                        host, afs_inet_ntoa_r(chain->addr, hoststr), 
-                        ntohs(chain->port), afs_inet_ntoa_r(addr, hoststr2), 
-                        ntohs(port)));
-           } else
-               ViceLog(125, 
-                       ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) already hashed\n",
-                        host, afs_inet_ntoa_r(chain->addr, hoststr), 
-                        ntohs(chain->port)));
-           
-           return;
+    ViceLog(125, ("invalidateInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
+                 host, afs_inet_ntoa_r(host->host, hoststr),
+                 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
+                 ntohs(port)));
+
+    /*
+     * Make sure this address is on the list of known addresses
+     * for this host.
+     */
+    interface = host->interface;
+    number = host->interface->numberOfInterfaces;
+    for (i = 0; i < number; i++) {
+       if (interface->interface[i].addr == addr &&
+           interface->interface[i].port == port) {
+            if (interface->interface[i].valid) {
+                h_DeleteHostFromAddrHashTable_r(addr, port, host);
+               interface->interface[i].valid = 0;
+           }
+           return 0;
        }
     }
 
+    /* not found */
+    return 0;
+}
+
+/*
+ * This is called with host locked and held.  This function differs
+ * from removeInterfaceAddr_r in that it is called when the address
+ * is being removed from the host regardless of whether or not there
+ * is an interface list for the host.  This function will delete the
+ * host if there are no addresses left on it.
+ *
+ * All addresses are in network byte order.
+ */
+static int
+removeAddress_r(struct host *host, afs_uint32 addr, afs_uint16 port)
+{
+    int i;
+    char hoststr[16], hoststr2[16];
+    struct rx_connection *rxconn;
+
+    if (!host->interface || host->interface->numberOfInterfaces == 1) {
+        if (host->host == addr && host->port == port) {
+            ViceLog(25,
+                    ("Removing only address for host %" AFS_PTR_FMT " (%s:%d), deleting host.\n",
+                     host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
+            host->hostFlags |= HOSTDELETED;
+            /*
+             * Do not remove the primary addr/port from the hash table.
+             * It will be ignored due to the HOSTDELETED flag and will
+             * be removed when h_TossStuff_r() cleans up the HOSTDELETED
+             * host.  Removing it here will only result in a search for
+             * the host/addr/port in the hash chain which will fail.
+             */
+        } else {
+            ViceLog(0,
+                    ("Removing address that does not belong to host %" AFS_PTR_FMT " (%s:%d).\n",
+                     host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
+        }
+    } else {
+        if (host->host == addr && host->port == port)  {
+            removeInterfaceAddr_r(host, addr, port);
+
+            for (i=0; i < host->interface->numberOfInterfaces; i++) {
+                if (host->interface->interface[i].valid) {
+                    ViceLog(25,
+                             ("Removed address for host %" AFS_PTR_FMT " (%s:%d), new primary interface %s:%d.\n",
+                               host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
+                               afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr2),
+                               ntohs(host->interface->interface[i].port)));
+                    host->host = host->interface->interface[i].addr;
+                    host->port = host->interface->interface[i].port;
+                    h_AddHostToAddrHashTable_r(host->host, host->port, host);
+                    break;
+                }
+            }
+
+            if (i == host->interface->numberOfInterfaces) {
+                ViceLog(25,
+                         ("Removed only address for host %" AFS_PTR_FMT " (%s:%d), no valid alternate interfaces, deleting host.\n",
+                           host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
+                host->hostFlags |= HOSTDELETED;
+                /* addr/port was removed from the hash table */
+                host->host = 0;
+                host->port = 0;
+            } else {
+                rxconn = host->callback_rxcon;
+                host->callback_rxcon = NULL;
+
+                if (rxconn) {
+                    rx_DestroyConnection(rxconn);
+                    rxconn = NULL;
+                }
+
+                if (!sc)
+                    sc = rxnull_NewClientSecurityObject();
+                host->callback_rxcon =
+                    rx_NewConnection(host->host, host->port, 1, sc, 0);
+                rx_SetConnDeadTime(host->callback_rxcon, 50);
+                rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
+            }
+        } else {
+            /* not the primary addr/port, just invalidate it */
+            invalidateInterfaceAddr_r(host, addr, port);
+        }
+    }
+
+    return 0;
+}
+
+static void
+createHostAddrHashChain_r(int index, afs_uint32 addr, afs_uint16 port, struct host *host)
+{
+    struct h_AddrHashChain *chain;
+    char hoststr[16];
+
     /* insert into beginning of list for this bucket */
     chain = (struct h_AddrHashChain *)malloc(sizeof(struct h_AddrHashChain));
     if (!chain) {
@@ -1251,6 +1354,166 @@ h_AddHostToAddrHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
                  host, afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
 }
 
+/**
+ * Resolve host address conflicts when hashing by address.
+ *
+ * @param[in]  addr    an ip address of the interface
+ * @param[in]  port    the port of the interface
+ * @param[in]  newHost the host being added with this address
+ * @param[in]  oldHost the host previously added with this address
+ */
+static void
+reconcileHosts_r(afs_uint32 addr, afs_uint16 port, struct host *newHost,
+                struct host *oldHost)
+{
+    struct rx_connection *cb = NULL;
+    int code = 0;
+    struct interfaceAddr interf;
+    Capabilities caps;
+    afsUUID *newHostUuid = &nulluuid;
+    afsUUID *oldHostUuid = &nulluuid;
+    char hoststr[16];
+
+    ViceLog(125,
+           ("reconcileHosts_r: addr %s:%d newHost %" AFS_PTR_FMT " oldHost %"
+            AFS_PTR_FMT, afs_inet_ntoa_r(addr, hoststr), ntohs(port),
+            newHost, oldHost));
+
+    assert(oldHost != newHost);
+    caps.Capabilities_val = NULL;
+
+    if (!sc) {
+       sc = rxnull_NewClientSecurityObject();
+    }
+
+    cb = rx_NewConnection(addr, port, 1, sc, 0);
+    rx_SetConnDeadTime(cb, 50);
+    rx_SetConnHardDeadTime(cb, AFS_HARDDEADTIME);
+
+    h_Hold_r(newHost);
+    h_Hold_r(oldHost);
+    H_UNLOCK;
+    code = RXAFSCB_TellMeAboutYourself(cb, &interf, &caps);
+    if (code == RXGEN_OPCODE) {
+       code = RXAFSCB_WhoAreYou(cb, &interf);
+    }
+    H_LOCK;
+
+    if (code == RXGEN_OPCODE ||
+       (code == 0 && afs_uuid_equal(&interf.uuid, &nulluuid))) {
+       ViceLog(0,
+               ("reconcileHosts_r: WhoAreYou not supported for connection (%s:%d), error %d\n",
+                afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
+       goto fail;
+    }
+    if (code != 0) {
+       ViceLog(0,
+               ("reconcileHosts_r: WhoAreYou failed for connection (%s:%d), error %d\n",
+                afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
+       goto fail;
+    }
+
+    /* Since lock was dropped, the hosts may have been deleted during the rpcs. */
+    if ((newHost->hostFlags & HOSTDELETED)
+       && (oldHost->hostFlags & HOSTDELETED)) {
+       ViceLog(5,
+               ("reconcileHosts_r: new and old hosts were deleted during probe.\n"));
+       goto done;
+    }
+
+    /* A check can be done if at least one of the hosts has a uuid. It
+     * is an error if the hosts have the same (not null) uuid. */
+    if ((!(newHost->hostFlags & HOSTDELETED)) && newHost->interface) {
+       newHostUuid = &(newHost->interface->uuid);
+    }
+    if ((!(oldHost->hostFlags & HOSTDELETED)) && oldHost->interface) {
+       oldHostUuid = &(oldHost->interface->uuid);
+    }
+    if (afs_uuid_equal(newHostUuid, &nulluuid) &&
+       afs_uuid_equal(oldHostUuid, &nulluuid)) {
+       ViceLog(0,
+               ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), no uuids\n",
+                afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
+       goto done;
+    }
+    if (afs_uuid_equal(newHostUuid, oldHostUuid)) {
+       ViceLog(0,
+               ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), same uuids\n",
+                afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
+       goto done;
+    }
+
+    /* Determine which host should be hashed */
+    if ((!(newHost->hostFlags & HOSTDELETED))
+       && afs_uuid_equal(newHostUuid, &(interf.uuid))) {
+       /* Install the new host into the hash before removing the stale
+        * addresses. Walk the hash chain again since the hash table may have
+        * been changed when the host lock was dropped to get the uuid. */
+       struct h_AddrHashChain *chain;
+       int index = h_HashIndex(addr);
+       for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
+           if (chain->addr == addr && chain->port == port) {
+               chain->hostPtr = newHost;
+               removeAddress_r(oldHost, addr, port);
+               goto done;
+           }
+       }
+       createHostAddrHashChain_r(index, addr, port, newHost);
+       removeAddress_r(oldHost, addr, port);
+       goto done;
+    }
+    if ((!(oldHost->hostFlags & HOSTDELETED))
+       && afs_uuid_equal(oldHostUuid, &(interf.uuid))) {
+       removeAddress_r(newHost, addr, port);
+       goto done;
+    }
+
+  fail:
+    if (!(newHost->hostFlags & HOSTDELETED)) {
+       removeAddress_r(newHost, addr, port);
+    }
+    if (!(oldHost->hostFlags & HOSTDELETED)) {
+       removeAddress_r(oldHost, addr, port);
+    }
+
+  done:
+    h_Release_r(newHost);
+    h_Release_r(oldHost);
+    rx_DestroyConnection(cb);
+    return;
+}
+
+/* inserts a new HashChain structure corresponding to this address */
+void
+h_AddHostToAddrHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
+{
+    int index;
+    struct h_AddrHashChain *chain;
+    char hoststr[16];
+
+    /* hash into proper bucket */
+    index = h_HashIndex(addr);
+
+    /* don't add the same address:port pair entry multiple times */
+    for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
+       if (chain->addr == addr && chain->port == port) {
+           if (chain->hostPtr == host) {
+               ViceLog(125,
+                       ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) already hashed\n",
+                         host, afs_inet_ntoa_r(chain->addr, hoststr),
+                         ntohs(chain->port)));
+               return;
+           }
+           if (!(chain->hostPtr->hostFlags & HOSTDELETED)) {
+               /* attempt to resolve host address collision */
+               reconcileHosts_r(addr, port, host, chain->hostPtr);
+               return;
+           }
+       }
+    }
+    createHostAddrHashChain_r(index, addr, port, host);
+}
+
 /*
  * This is called with host locked and held. 
  * It is called to either validate or add an additional interface
@@ -1364,141 +1627,9 @@ removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
     return 0;
 }
 
-/*
- * This is called with host locked and held.
- *
- * All addresses are in network byte order.
- */
-int
-invalidateInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
-{
-    int i;
-    int number;
-    struct Interface *interface;
-    char hoststr[16], hoststr2[16];
-    
-    assert(host);
-    assert(host->interface);
-    
-    ViceLog(125, ("invalidateInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n", 
-                 host, afs_inet_ntoa_r(host->host, hoststr), 
-                 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2), 
-                 ntohs(port)));
-    
-    /*
-     * Make sure this address is on the list of known addresses
-     * for this host.
-     */
-    interface = host->interface;
-    number = host->interface->numberOfInterfaces;
-    for (i = 0; i < number; i++) {
-       if (interface->interface[i].addr == addr &&
-           interface->interface[i].port == port) {
-            if (interface->interface[i].valid) {
-                h_DeleteHostFromAddrHashTable_r(addr, port, host);
-               interface->interface[i].valid = 0;
-           }
-           return 0;
-       }
-    }
-    
-    /* not found */
-    return 0;
-}
-
-/*
- * This is called with host locked and held.  This function differs
- * from removeInterfaceAddr_r in that it is called when the address
- * is being removed from the host regardless of whether or not there
- * is an interface list for the host.  This function will delete the
- * host if there are no addresses left on it.
- *
- * All addresses are in network byte order.
- */
-int
-removeAddress_r(struct host *host, afs_uint32 addr, afs_uint16 port)
-{
-    int i;
-    char hoststr[16], hoststr2[16];
-    struct rx_connection *rxconn;
-
-    if (!host->interface || host->interface->numberOfInterfaces == 1) {
-        if (host->host == addr && host->port == port) {
-            ViceLog(25,
-                    ("Removing only address for host %" AFS_PTR_FMT " (%s:%d), deleting host.\n",
-                     host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
-            host->hostFlags |= HOSTDELETED;
-            /* 
-             * Do not remove the primary addr/port from the hash table.
-             * It will be ignored due to the HOSTDELETED flag and will
-             * be removed when h_TossStuff_r() cleans up the HOSTDELETED
-             * host.  Removing it here will only result in a search for 
-             * the host/addr/port in the hash chain which will fail.
-             */
-        } else {
-            ViceLog(0,
-                    ("Removing address that does not belong to host %" AFS_PTR_FMT " (%s:%d).\n",
-                     host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
-        }
-    } else {
-        if (host->host == addr && host->port == port)  {
-            removeInterfaceAddr_r(host, addr, port);
-
-            rxconn = host->callback_rxcon;
-            host->callback_rxcon = NULL;
-
-            if (rxconn) {
-                struct client *client;
-                /*
-                 * If rx_DestroyConnection calls h_FreeConnection we will
-                 * deadlock on the host_glock_mutex. Work around the problem
-                 * by unhooking the client from the connection before
-                 * destroying the connection.
-                 */
-                client = rx_GetSpecific(rxconn, rxcon_client_key);
-                rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
-                rx_DestroyConnection(rxconn);
-            }
-
-            for (i=0; i < host->interface->numberOfInterfaces; i++) {
-                if (host->interface->interface[i].valid) {
-                    ViceLog(25,
-                             ("Removed address for host %" AFS_PTR_FMT " (%s:%d), new primary interface %s:%d.\n",
-                               host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
-                               afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr2), 
-                               ntohs(host->interface->interface[i].port)));
-                    host->host = host->interface->interface[i].addr;
-                    host->port = host->interface->interface[i].port;
-                    h_AddHostToAddrHashTable_r(host->host, host->port, host);
-                    break;
-                }
-            }
 
-            if (i == host->interface->numberOfInterfaces) {
-                ViceLog(25,
-                         ("Removed only address for host %" AFS_PTR_FMT " (%s:%d), no valid alternate interfaces, deleting host.\n",
-                           host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
-                host->hostFlags |= HOSTDELETED;
-                /* addr/port was removed from the hash table */
-                host->host = 0;
-                host->port = 0;
-            } else {
-                if (!sc)
-                    sc = rxnull_NewClientSecurityObject();
-                host->callback_rxcon =
-                    rx_NewConnection(host->host, host->port, 1, sc, 0);
-                rx_SetConnDeadTime(host->callback_rxcon, 50);
-                rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
-            }
-        } else {
-            /* not the primary addr/port, just invalidate it */
-            invalidateInterfaceAddr_r(host, addr, port);
-        }
-    }
 
-    return 0;
-}
-int 
+static int
 h_threadquota(int waiting) 
 {
     if (lwps > 64) {
@@ -1517,14 +1648,13 @@ h_threadquota(int waiting)
     return 0;
 }
 
-/* Host is returned held */
+/* If found, host is returned with refCount incremented */
 struct host *
 h_GetHost_r(struct rx_connection *tcon)
 {
     struct host *host;
     struct host *oldHost;
     int code;
-    int held;
     struct interfaceAddr interf;
     int interfValid = 0;
     struct Identity *identP = NULL;
@@ -1550,7 +1680,7 @@ h_GetHost_r(struct rx_connection *tcon)
     caps.Capabilities_len = 0;
 
     code = 0;
-    if (h_Lookup_r(haddr, hport, &held, &host))
+    if (h_Lookup_r(haddr, hport, &host))
        return 0;
     identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
     if (host && !identP && !(host->Console & 1)) {
@@ -1560,20 +1690,22 @@ h_GetHost_r(struct rx_connection *tcon)
         */
        if ((host->hostFlags & HWHO_INPROGRESS) && 
            h_threadquota(host->lock.num_waiting)) {
-           if (!held)
                h_Release_r(host);
-           return 0;
+           host = NULL;
+           goto gethost_out;
        }
        h_Lock_r(host);
-       if (!(host->hostFlags & ALTADDR)) {
-           /* Another thread is doing initialization */
+       if (!(host->hostFlags & ALTADDR) ||
+            (host->hostFlags & HOSTDELETED)) {
+           /* Another thread is doing initialization
+             * or this host was deleted while we
+             * waited for the lock. */
            h_Unlock_r(host);
-           if (!held)
-               h_Release_r(host);
            ViceLog(125,
                    ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
                     host, afs_inet_ntoa_r(host->host, hoststr),
                     ntohs(host->port)));
+           h_Release_r(host);
            goto retry;
        }
        host->hostFlags |= HWHO_INPROGRESS;
@@ -1643,8 +1775,7 @@ h_GetHost_r(struct rx_connection *tcon)
                    host->hostFlags |= HOSTDELETED;
                    host->hostFlags &= ~HWHO_INPROGRESS;
                    h_Unlock_r(host);
-                   if (!held)
-                       h_Release_r(host);
+                   h_Release_r(host);
                    host = NULL;
                    goto retry;
                }
@@ -1659,8 +1790,7 @@ h_GetHost_r(struct rx_connection *tcon)
                 host->hostFlags &= ~HWHO_INPROGRESS;
                 host->hostFlags |= ALTADDR;
                 h_Unlock_r(host);
-               if (!held)
-                    h_Release_r(host);
+               h_Release_r(host);
                 host = NULL;
                 goto retry;
            }
@@ -1680,11 +1810,10 @@ h_GetHost_r(struct rx_connection *tcon)
            if (!host->interface
                || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
                if (cb_in) {
-                    ViceLog(25,
-                           ("Uuid doesn't match connection (%s:%d).\n",
-                            afs_inet_ntoa_r(haddr, hoststr), ntohs(hport)));
-                   
-                    removeAddress_r(host, haddr, hport);
+                       ViceLog(25,
+                                       ("Uuid doesn't match connection (%s:%d).\n",
+                                        afs_inet_ntoa_r(haddr, hoststr), ntohs(hport)));
+                       removeAddress_r(host, haddr, hport);
                } else {
                    ViceLog(25,
                            ("Uuid doesn't match host %" AFS_PTR_FMT " (%s:%d).\n",
@@ -1695,8 +1824,7 @@ h_GetHost_r(struct rx_connection *tcon)
                host->hostFlags &= ~HWHO_INPROGRESS;
                 host->hostFlags |= ALTADDR;
                h_Unlock_r(host);
-               if (!held)
-                   h_Release_r(host);
+               h_Release_r(host);
                host = NULL;
                goto retry;
            } else if (cb_in) {
@@ -1744,14 +1872,12 @@ h_GetHost_r(struct rx_connection *tcon)
                     cb_in = NULL;
                    
                     if (rxconn) {
-                        struct client *client;
                         /*
-                         * If rx_DestroyConnection calls h_FreeConnection we will
-                        * deadlock on the host_glock_mutex. Work around the problem
-                         * by unhooking the client from the connection before
-                         * destroying the connection.
+                         * If rx_DestroyConnection calls h_FreeConnection we
+                        * will deadlock on the host_glock_mutex. Work around
+                        * the problem by unhooking the client from the
+                        * connection before destroying the connection.
                          */
-                        client = rx_GetSpecific(rxconn, rxcon_client_key);
                         rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
                         rx_DestroyConnection(rxconn);
                    }
@@ -1770,11 +1896,11 @@ h_GetHost_r(struct rx_connection *tcon)
                 host->hostFlags &= ~HWHO_INPROGRESS;
                 host->hostFlags |= ALTADDR;
                 h_Unlock_r(host);
-                if (!held)
-                    h_Release_r(host);
+               h_Release_r(host);
                 host = NULL;
                 rx_DestroyConnection(cb_in);
-                return 0;
+               cb_in = NULL;
+               goto gethost_out;
            } else {
                ViceLog(0,
                        ("CB: WhoAreYou failed for host %" AFS_PTR_FMT " (%s:%d), error %d\n",
@@ -1800,12 +1926,11 @@ h_GetHost_r(struct rx_connection *tcon)
                     ntohs(host->port)));
            h_Lock_r(host);
            h_Unlock_r(host);
-           if (!held)
-               h_Release_r(host);
            ViceLog(125,
                    ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
                     host, afs_inet_ntoa_r(host->host, hoststr),
                     ntohs(host->port)));
+           h_Release_r(host);
            goto retry;
        }
        /* We need to check whether the identity in the host structure
@@ -1823,7 +1948,8 @@ h_GetHost_r(struct rx_connection *tcon)
            if (host->interface)
                afsUUID_to_string(&host->interface->uuid, uuid2, 127);
            ViceLog(0,
-                   ("CB: new identity for host %" AFS_PTR_FMT " (%s:%d), deleting(%x %x %s %s)\n",
+                   ("CB: new identity for host %p (%s:%d), "
+                    "deleting(%x %p %s %s)\n",
                     host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
                     identP->valid, host->interface,
                     identP->valid ? uuid1 : "no_uuid",
@@ -1833,8 +1959,7 @@ h_GetHost_r(struct rx_connection *tcon)
             h_Lock_r(host);
            host->hostFlags |= HOSTDELETED;
            h_Unlock_r(host);
-           if (!held)
-               h_Release_r(host);
+           h_Release_r(host);
            goto retry;
        }
     } else {
@@ -1905,11 +2030,19 @@ h_GetHost_r(struct rx_connection *tcon)
            } else if (code == 0) {
                oldHost = h_LookupUuid_r(&identP->uuid);
                 if (oldHost) {
-                    int probefail = 0;
-
-                   if (!h_Held_r(oldHost))
-                       h_Hold_r(oldHost);
+                   h_Hold_r(oldHost);
                    h_Lock_r(oldHost);
+
+                   if (oldHost->hostFlags & HOSTDELETED) {
+                       h_Unlock_r(oldHost);
+                       h_Release_r(oldHost);
+                       oldHost = NULL;
+                   }
+               }
+
+               if (oldHost) {
+                   int probefail = 0;
+
                    oldHost->hostFlags |= HWHO_INPROGRESS;
 
                     if (oldHost->interface) {
@@ -1998,20 +2131,10 @@ h_GetHost_r(struct rx_connection *tcon)
                        oldHost->port = hport;
                        rxconn = oldHost->callback_rxcon;
                        oldHost->callback_rxcon = host->callback_rxcon;
-                       host->callback_rxcon = NULL;
+                       host->callback_rxcon = rxconn;
                        
-                       if (rxconn) {
-                           struct client *client;
-                           /*
-                            * If rx_DestroyConnection calls h_FreeConnection we will
-                            * deadlock on the host_glock_mutex. Work around the problem
-                            * by unhooking the client from the connection before
-                            * destroying the connection.
-                            */
-                           client = rx_GetSpecific(rxconn, rxcon_client_key);
-                           rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
-                           rx_DestroyConnection(rxconn);
-                       }
+                        /* don't destroy rxconn here; let h_TossStuff_r
+                         * take care of that via h_Release_r below */
                    }
                    host->hostFlags &= ~HWHO_INPROGRESS;
                    h_Unlock_r(host);
@@ -2062,10 +2185,16 @@ h_GetHost_r(struct rx_connection *tcon)
        host->hostFlags &= ~HWHO_INPROGRESS;
        h_Unlock_r(host);
     }
+
+ gethost_out:
     if (caps.Capabilities_val)
        free(caps.Capabilities_val);
     caps.Capabilities_val = NULL;
     caps.Capabilities_len = 0;
+    if (cb_in) {
+        rx_DestroyConnection(cb_in);
+        cb_in = NULL;
+    }
     return host;
 
 }                              /*h_GetHost_r */
@@ -2163,13 +2292,13 @@ MapName_r(char *aname, char *acell, afs_int32 * aval)
            if (*aval == AnonymousID) {
                ViceLog(2,
                        ("MapName: NameToId on %s returns anonymousID\n",
-                        lnames.namelist_val));
+                        lnames.namelist_val[0]));
            }
            free(lids.idlist_val);      /* return parms are not malloced in stub if server proc aborts */
        } else {
            ViceLog(0,
                    ("MapName: NameToId on '%s' is unknown\n",
-                    lnames.namelist_val));
+                    lnames.namelist_val[0]));
            code = -1;
        }
     }
@@ -2189,9 +2318,10 @@ h_ID2Client(afs_int32 vid)
 {
     register struct client *client;
     register struct host *host;
+    int count;
 
     H_LOCK;
-    for (host = hostList; host; host = host->next) {
+    for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
        if (host->hostFlags & HOSTDELETED)
            continue;
        for (client = host->FirstClient; client; client = client->next) {
@@ -2203,6 +2333,12 @@ h_ID2Client(afs_int32 vid)
            }
        }
     }
+    if (count != hostCount) {
+       ViceLog(0, ("h_ID2Client found %d of %d hosts\n", count, hostCount));
+    } else if (host != NULL) {
+       ViceLog(0, ("h_ID2Client found more than %d hosts\n", hostCount));
+       ShutDownAndCore(PANIC);
+    }
 
     H_UNLOCK;
     return NULL;
@@ -2215,8 +2351,8 @@ h_ID2Client(afs_int32 vid)
  * by one. The caller must call h_ReleaseClient_r when finished with
  * the client.
  *
- * the client->host is returned held.  h_ReleaseClient_r does not release
- * the hold on client->host.
+ * The refCount on client->host is returned incremented.  h_ReleaseClient_r
+ * does not decrement the refCount on client->host.
  */
 struct client *
 h_FindClient_r(struct rx_connection *tcon)
@@ -2240,7 +2376,9 @@ h_FindClient_r(struct rx_connection *tcon)
 
     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
     if (client && client->sid == rxr_CidOf(tcon) 
-       && client->VenusEpoch == rxr_GetEpoch(tcon)) {
+       && client->VenusEpoch == rxr_GetEpoch(tcon)
+       && !(client->host->hostFlags & HOSTDELETED)) {
+
        client->refCount++;
        h_Hold_r(client->host);
        if (!client->deleted && client->prfail != 2) {  
@@ -2272,7 +2410,7 @@ h_FindClient_r(struct rx_connection *tcon)
        afs_int32 kvno;
     
        /* kerberos ticket */
-       code = rxkad_GetServerInfo(tcon, /*level */ 0, &expTime,
+       code = rxkad_GetServerInfo(tcon, /*level */ 0, (afs_uint32 *)&expTime,
                                   tname, tinst, tcell, &kvno);
        if (code) {
            ViceLog(1, ("Failed to get rxkad ticket info\n"));
@@ -2308,10 +2446,10 @@ h_FindClient_r(struct rx_connection *tcon)
     }
 
     if (!client) { /* loop */
-       host = h_GetHost_r(tcon);       /* Returns it h_Held */
+       host = h_GetHost_r(tcon);       /* Returns with incremented refCount  */
 
        if (!host) 
-           return 0;
+           return NULL;
 
     retryfirstclient:
        /* First try to find the client structure */
@@ -2329,6 +2467,11 @@ h_FindClient_r(struct rx_connection *tcon)
        /* Still no client structure - get one */
        if (!client) {
            h_Lock_r(host);
+            if (host->hostFlags & HOSTDELETED) {
+                h_Unlock_r(host);
+                h_Release_r(host);
+                return NULL;
+            }
            /* Retry to find the client structure */
            for (client = host->FirstClient; client; client = client->next) {
                if (!client->deleted && (client->sid == rxr_CidOf(tcon))
@@ -2416,7 +2559,8 @@ h_FindClient_r(struct rx_connection *tcon)
        if (!oldClient->deleted) {
            /* if we didn't create it, it's not ours to put back */
            if (created) {
-               ViceLog(0, ("FindClient: stillborn client %x(%x); conn %x (host %s:%d) had client %x(%x)\n", 
+               ViceLog(0, ("FindClient: stillborn client %p(%x); "
+                           "conn %p (host %s:%d) had client %p(%x)\n",
                            client, client->sid, tcon, 
                            afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
                            ntohs(rxr_PortOf(tcon)),
@@ -2439,7 +2583,8 @@ h_FindClient_r(struct rx_connection *tcon)
            H_LOCK;
            client = oldClient;
        } else {
-           ViceLog(0, ("FindClient: deleted client %x(%x) already had conn %x (host %s:%d), stolen by client %x(%x)\n", 
+           ViceLog(0, ("FindClient: deleted client %p(%x) already had "
+                       "conn %p (host %s:%d), stolen by client %p(%x)\n",
                        oldClient, oldClient->sid, tcon, 
                        afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
                        ntohs(rxr_PortOf(tcon)),
@@ -2450,6 +2595,25 @@ h_FindClient_r(struct rx_connection *tcon)
     /* Avoid chaining in more than once. */
     if (created) {
        h_Lock_r(host);
+
+        if (host->hostFlags & HOSTDELETED) {
+            h_Unlock_r(host);
+            h_Release_r(host);
+
+            host = NULL;
+            client->host = NULL;
+
+            if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
+                free(client->CPS.prlist_val);
+            client->CPS.prlist_val = NULL;
+            client->CPS.prlist_len = 0;
+
+            client->refCount--;
+            ReleaseWriteLock(&client->lock);
+            FreeCE(client);
+            return NULL;
+        }
+
        client->next = host->FirstClient;
        host->FirstClient = client;
        h_Unlock_r(host);
@@ -2489,7 +2653,7 @@ GetClient(struct rx_connection *tcon, struct client **cp)
     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
     if (client == NULL) {
        ViceLog(0,
-               ("GetClient: no client in conn %x (host %s:%d), VBUSYING\n",
+               ("GetClient: no client in conn %p (host %s:%d), VBUSYING\n",
                 tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
                  ntohs(rxr_PortOf(tcon))));
        H_UNLOCK;
@@ -2497,7 +2661,7 @@ GetClient(struct rx_connection *tcon, struct client **cp)
     }
     if (rxr_CidOf(tcon) != client->sid || rxr_GetEpoch(tcon) != client->VenusEpoch) {
        ViceLog(0,
-               ("GetClient: tcon %x tcon sid %d client sid %d\n",
+               ("GetClient: tcon %p tcon sid %d client sid %d\n",
                 tcon, rxr_CidOf(tcon), client->sid));
        H_UNLOCK;
        return VBUSY;
@@ -2571,7 +2735,7 @@ h_PrintStats(void)
 
 
 static int
-h_PrintClient(register struct host *host, int held, void *rock)
+h_PrintClient(register struct host *host, int flags, void *rock)
 {
     StreamHandle_t *file = (StreamHandle_t *)rock;
     register struct client *client;
@@ -2585,7 +2749,7 @@ h_PrintClient(register struct host *host, int held, void *rock)
     LastCall = host->LastCall;
     if (host->hostFlags & HOSTDELETED) {
        H_UNLOCK;
-       return held;
+       return flags;
     }
     (void)afs_snprintf(tmpStr, sizeof tmpStr,
                       "Host %s:%d down = %d, LastCall %s",
@@ -2623,7 +2787,7 @@ h_PrintClient(register struct host *host, int held, void *rock)
        }
     }
     H_UNLOCK;
-    return held;
+    return flags;
 
 }                              /*h_PrintClient */
 
@@ -2661,7 +2825,7 @@ h_PrintClients(void)
 
 
 static int
-h_DumpHost(register struct host *host, int held, void *rock)
+h_DumpHost(register struct host *host, int flags, void *rock)
 {
     StreamHandle_t *file = (StreamHandle_t *)rock;
     
@@ -2695,18 +2859,11 @@ h_DumpHost(register struct host *host, int held, void *rock)
                     ntohs(host->interface->interface[i].port));
            (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
        }
-    sprintf(tmpStr, "] holds: ");
-    (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
-
-    for (i = 0; i < h_maxSlots; i++) {
-       sprintf(tmpStr, "%04x", host->holds[i]);
-       (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
-    }
-    sprintf(tmpStr, " slot/bit: %d/%d\n", h_holdSlot(), h_holdbit());
+    sprintf(tmpStr, "] refCount:%d hostFlags:%hu\n", host->refCount, host->hostFlags);
     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
 
     H_UNLOCK;
-    return held;
+    return flags;
 
 }                              /*h_DumpHost */
 
@@ -2743,11 +2900,12 @@ h_DumpHosts(void)
 static int h_stateFillHeader(struct host_state_header * hdr);
 static int h_stateCheckHeader(struct host_state_header * hdr);
 static int h_stateAllocMap(struct fs_dump_state * state);
-static int h_stateSaveHost(register struct host * host, int held, struct fs_dump_state * state);
+static int h_stateSaveHost(struct host * host, int flags, void *rock);
 static int h_stateRestoreHost(struct fs_dump_state * state);
-static int h_stateRestoreIndex(struct host * h, int held, struct fs_dump_state * state);
-static int h_stateVerifyHost(struct host * h, int held, struct fs_dump_state * state);
-static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port);
+static int h_stateRestoreIndex(struct host * h, int flags, void *rock);
+static int h_stateVerifyHost(struct host * h, int flags, void *rock);
+static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
+                                 afs_uint32 addr, afs_uint16 port, int valid);
 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
@@ -2838,12 +2996,13 @@ h_stateRestoreIndices(struct fs_dump_state * state)
 }
 
 static int
-h_stateRestoreIndex(struct host * h, int held, struct fs_dump_state * state)
+h_stateRestoreIndex(struct host * h, int flags, void *rock)
 {
+    struct fs_dump_state *state = (struct fs_dump_state *)rock;
     if (cb_OldToNew(state, h->cblist, &h->cblist)) {
-       return H_ENUMERATE_BAIL(held);
+       return H_ENUMERATE_BAIL(flags);
     }
-    return held;
+    return flags;
 }
 
 int
@@ -2854,26 +3013,28 @@ h_stateVerify(struct fs_dump_state * state)
 }
 
 static int
-h_stateVerifyHost(struct host * h, int held, struct fs_dump_state * state)
+h_stateVerifyHost(struct host * h, int flags, void* rock)
 {
+    struct fs_dump_state *state = (struct fs_dump_state *)rock;
     int i;
 
     if (h == NULL) {
        ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
-       return H_ENUMERATE_BAIL(held);
+       return H_ENUMERATE_BAIL(flags);
     }
 
     if (h->interface) {
        for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
            if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr, 
-                                     h->interface->interface[i].port)) {
+                                     h->interface->interface[i].port,
+                                     h->interface->interface[i].valid)) {
                state->bail = 1;
            }
        }
        if (h_stateVerifyUuidHash(state, h)) {
            state->bail = 1;
        }
-    } else if (h_stateVerifyAddrHash(state, h, h->host, h->port)) {
+    } else if (h_stateVerifyAddrHash(state, h, h->host, h->port, 1)) {
        state->bail = 1;
     }
 
@@ -2881,12 +3042,28 @@ h_stateVerifyHost(struct host * h, int held, struct fs_dump_state * state)
        state->bail = 1;
     }
 
- done:
-    return held;
+    return flags;
 }
 
+/**
+ * verify a host is either in, or absent from, the addr hash table.
+ *
+ * @param[in] state  fs dump state
+ * @param[in] h      host we're dealing with
+ * @param[in] addr   addr to look for (NBO)
+ * @param[in] port   port to look for (NBO)
+ * @param[in] valid  1 if we're verifying that the specified addr and port
+ *                   in the hash table point to the specified host. 0 if we're
+ *                   verifying that the specified addr and port do NOT point
+ *                   to the specified host
+ *
+ * @return operation status
+ *  @retval 1 failed to verify, bail out
+ *  @retval 0 verified successfully, all is well
+ */
 static int
-h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port)
+h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
+                      afs_uint32 addr, afs_uint16 port, int valid)
 {
     int ret = 0, found = 0;
     struct host *host = NULL;
@@ -2905,9 +3082,21 @@ h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32
        }
        if ((chain->addr == addr) && (chain->port == port)) {
            if (host != h) {
-               ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry points to different host struct (%d, %d)\n", 
-                           h->index, host->index));
-               state->flags.warnings_generated = 1;
+               if (valid) {
+                   ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry "
+                               "points to different host struct (%d, %d)\n",
+                               h->index, host->index));
+                   state->flags.warnings_generated = 1;
+               }
+           } else {
+               if (!valid) {
+                   ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u is "
+                               "marked invalid, but points to the containing "
+                               "host\n", afs_inet_ntoa_r(addr, tmp),
+                               (unsigned)htons(port)));
+                   ret = 1;
+                   goto done;
+               }
            }
            found = 1;
            break;
@@ -2921,14 +3110,16 @@ h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32
        chain_len++;
     }
 
-    if (!found) {
+    if (!found && valid) {
        afs_inet_ntoa_r(addr, tmp);
        if (state->mode == FS_STATE_LOAD_MODE) {
-           ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s not found in hash\n", tmp));
+           ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u not found in hash\n",
+                       tmp, (unsigned)htons(port)));
            ret = 1;
            goto done;
        } else {
-           ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s not found in hash\n", tmp));
+           ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s:%u not found in hash\n",
+                       tmp, (unsigned)htons(port)));
            state->flags.warnings_generated = 1;
        }
     }
@@ -2997,6 +3188,7 @@ h_stateFillHeader(struct host_state_header * hdr)
 {
     hdr->stamp.magic = HOST_STATE_MAGIC;
     hdr->stamp.version = HOST_STATE_VERSION;
+    return 0;
 }
 
 /* check the contents of the host state header structure */
@@ -3028,9 +3220,10 @@ h_stateAllocMap(struct fs_dump_state * state)
 
 /* function called by h_Enumerate to save a host to disk */
 static int
-h_stateSaveHost(register struct host * host, int held, struct fs_dump_state * state)
+h_stateSaveHost(struct host * host, int flags, void* rock)
 {
-    int i, if_len=0, hcps_len=0;
+    struct fs_dump_state *state = (struct fs_dump_state *) rock;
+    int if_len=0, hcps_len=0;
     struct hostDiskEntry hdsk;
     struct host_state_entry_header hdr;
     struct Interface * ifp = NULL;
@@ -3088,15 +3281,14 @@ h_stateSaveHost(register struct host * host, int held, struct fs_dump_state * st
 
     state->h_hdr->records++;
 
- done:
     if (ifp)
        free(ifp);
     if (hcps)
        free(hcps);
     if (state->bail) {
-       return H_ENUMERATE_BAIL(held);
+       return H_ENUMERATE_BAIL(flags);
     }
-    return held;
+    return flags;
 }
 
 /* restores a host from disk */
@@ -3268,7 +3460,6 @@ h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
        *new = state->h_map.entries[old].new_idx;
     }
 
- done:
     return ret;
 }
 #endif /* AFS_DEMAND_ATTACH_FS */
@@ -3285,9 +3476,10 @@ h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
 {
     register struct host *host;
     register int num = 0, active = 0, del = 0;
+    int count;
 
     H_LOCK;
-    for (host = hostList; host; host = host->next) {
+    for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
        if (!(host->hostFlags & HOSTDELETED)) {
            num++;
            if (host->ActiveCall > cutofftime)
@@ -3296,6 +3488,12 @@ h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
                del++;
        }
     }
+    if (count != hostCount) {
+       ViceLog(0, ("h_GetWorkStats found %d of %d hosts\n", count, hostCount));
+    } else if (host != NULL) {
+       ViceLog(0, ("h_GetWorkStats found more than %d hosts\n", hostCount));
+       ShutDownAndCore(PANIC);
+    }
     H_UNLOCK;
     if (nump)
        *nump = num;
@@ -3450,6 +3648,7 @@ h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
 
     register struct host *hostP;       /*Ptr to current host entry */
     register afs_uint32 currAddr_HBO;  /*Curr host addr, host byte order */
+    int count;
 
     /*
      * Clear out the storage pointed to by our parameters.
@@ -3460,7 +3659,7 @@ h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
     *a_diffNetworkP = (afs_int32) 0;
 
     H_LOCK;
-    for (hostP = hostList; hostP; hostP = hostP->next) {
+    for (count = 0, hostP = hostList; hostP && count < hostCount; hostP = hostP->next, count++) {
        if (!(hostP->hostFlags & HOSTDELETED)) {
            /*
             * Bump the number of undeleted host entries found.
@@ -3474,6 +3673,12 @@ h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
                              a_diffNetworkP);
        }                       /*Only look at non-deleted hosts */
     }                          /*For each host record hashed to this index */
+    if (count != hostCount) {
+       ViceLog(0, ("h_GetHostNetStats found %d of %d hosts\n", count, hostCount));
+    } else if (hostP != NULL) {
+       ViceLog(0, ("h_GetHostNetStats found more than %d hosts\n", hostCount));
+       ShutDownAndCore(PANIC);
+    }
     H_UNLOCK;
 }                              /*h_GetHostNetStats */
 
@@ -3487,8 +3692,9 @@ static struct AFSFid zerofid;
  * Since it can serialize them, and pile up, it should be a separate LWP
  * from other events.
  */
+#if 0
 static int
-CheckHost(register struct host *host, int held, void *rock)
+CheckHost(register struct host *host, int flags, void *rock)
 {
     register struct client *client;
     struct rx_connection *cb_conn = NULL;
@@ -3499,7 +3705,7 @@ CheckHost(register struct host *host, int held, void *rock)
     FS_STATE_RDLOCK;
     if (fs_state.mode == FS_MODE_SHUTDOWN) {
        FS_STATE_UNLOCK;
-       return H_ENUMERATE_BAIL(held);
+       return H_ENUMERATE_BAIL(flags);
     }
     FS_STATE_UNLOCK;
 #endif
@@ -3514,8 +3720,8 @@ CheckHost(register struct host *host, int held, void *rock)
     }
     if (host->LastCall < checktime) {
        h_Lock_r(host);
-       host->hostFlags |= HWHO_INPROGRESS;
        if (!(host->hostFlags & HOSTDELETED)) {
+            host->hostFlags |= HWHO_INPROGRESS;
            cb_conn = host->callback_rxcon;
            rx_GetConnection(cb_conn);
            if (host->LastCall < clientdeletetime) {
@@ -3583,17 +3789,18 @@ CheckHost(register struct host *host, int held, void *rock)
            rx_PutConnection(cb_conn);
            cb_conn=NULL;
            H_LOCK;
+            host->hostFlags &= ~HWHO_INPROGRESS;
        }
-       host->hostFlags &= ~HWHO_INPROGRESS;
        h_Unlock_r(host);
     }
     H_UNLOCK;
     return held;
 
 }                              /*CheckHost */
+#endif
 
 int
-CheckHost_r(register struct host *host, int held, char *dummy)
+CheckHost_r(register struct host *host, int flags, void *dummy)
 {
     register struct client *client;
     struct rx_connection *cb_conn = NULL;
@@ -3604,7 +3811,7 @@ CheckHost_r(register struct host *host, int held, char *dummy)
     FS_STATE_RDLOCK;
     if (fs_state.mode == FS_MODE_SHUTDOWN) {
        FS_STATE_UNLOCK;
-       return H_ENUMERATE_BAIL(held);
+       return H_ENUMERATE_BAIL(flags);
     }
     FS_STATE_UNLOCK;
 #endif
@@ -3689,7 +3896,7 @@ CheckHost_r(register struct host *host, int held, char *dummy)
        }
        h_Unlock_r(host);
     }
-    return held;
+    return flags;
 
 }                              /*CheckHost_r */
 
@@ -3708,7 +3915,7 @@ h_CheckHosts(void)
 {
     afs_uint32 now = FT_ApproxTime();
 
-    memset((char *)&zerofid, 0, sizeof(zerofid));
+    memset(&zerofid, 0, sizeof(zerofid));
     /*
      * Send a probe to the workstation if it hasn't been heard from in
      * 15 minutes