-static ipv4_t cache_ipv4_address[2];
-static subnet_t *cache_ipv4_subnet[2];
-static bool cache_ipv4_valid[2];
-static int cache_ipv4_slot;
-
-static ipv6_t cache_ipv6_address[2];
-static subnet_t *cache_ipv6_subnet[2];
-static bool cache_ipv6_valid[2];
-static int cache_ipv6_slot;
-
-static mac_t cache_mac_address[2];
-static subnet_t *cache_mac_subnet[2];
-static bool cache_mac_valid[2];
-static int cache_mac_slot;
-
-void subnet_cache_flush(void) {
- cache_ipv4_valid[0] = cache_ipv4_valid[1] = false;
- cache_ipv6_valid[0] = cache_ipv6_valid[1] = false;
- cache_mac_valid[0] = cache_mac_valid[1] = false;
+static uint32_t wrapping_add32(uint32_t a, uint32_t b) {
+ return (uint32_t)((uint64_t)a + b);
+}
+
+static uint32_t wrapping_mul32(uint32_t a, uint32_t b) {
+ return (uint32_t)((uint64_t)a * b);
+}
+
+static uint32_t hash_function_ipv4_t(const ipv4_t *p) {
+ /*
+ This basic hash works because
+ a) Most IPv4 networks routed via tinc are not /0
+ b) Most IPv4 networks have more unique low order bits
+ */
+ uint16_t *halfwidth = (uint16_t *)p;
+ uint32_t hash = hash_seed;
+
+#if __BYTE_ORDER == __LITTLE_ENDIAN
+ // 10.0.x.x/16 part
+ hash = wrapping_add32(hash, wrapping_mul32(halfwidth[1], 0x9e370001U));
+
+ // x.x.0.[0-255] part
+#if SUBNET_HASH_SIZE >= 0x10000
+ return hash ^ halfwidth[0];
+#else
+ // ensure that we have a /24 with no collisions on 32bit
+ return hash ^ ntohs(halfwidth[0]);
+#endif // _____LP64_____
+#else
+ // 10.0.x.x/16 part
+ hash = wrapping_add32(hash, wrapping_mul32(halfwidth[0], 0x9e370001U));
+
+ // x.x.0.[0-255] part (ntohs is nop on big endian)
+ return hash ^ halfwidth[1];
+#endif // __BYTE_ORDER == __LITTLE_ENDIAN
+}
+
+
+static uint32_t hash_function_ipv6_t(const ipv6_t *p) {
+ uint32_t *fullwidth = (uint32_t *)p;
+ uint32_t hash = hash_seed;
+
+ for(int i = 0; i < 4; i++) {
+ hash = wrapping_add32(hash, fullwidth[i]);
+ hash = wrapping_mul32(hash, 0x9e370001U);
+ }
+
+ return hash;
+}
+
+static uint32_t hash_function_mac_t(const mac_t *p) {
+ uint16_t *halfwidth = (uint16_t *)p;
+ uint32_t hash = hash_seed;
+
+ for(int i = 0; i < 3; i++) {
+ hash = wrapping_add32(hash, halfwidth[i]);
+ hash = wrapping_mul32(hash, 0x9e370001U);
+ }
+
+ return hash;
+}
+
+hash_define(ipv4_t, SUBNET_HASH_SIZE)
+hash_define(ipv6_t, SUBNET_HASH_SIZE)
+hash_define(mac_t, SUBNET_HASH_SIZE)
+
+hash_new(ipv4_t, ipv4_cache);
+hash_new(ipv6_t, ipv6_cache);
+hash_new(mac_t, mac_cache);
+
+
+void subnet_cache_flush_table(subnet_type_t stype) {
+ // NOTE: a subnet type of SUBNET_TYPES can be used to clear all hash tables
+
+ if(stype != SUBNET_IPV6) { // ipv4
+ hash_clear(ipv4_t, &ipv4_cache);
+ }
+
+ if(stype != SUBNET_IPV4) { // ipv6
+ hash_clear(ipv6_t, &ipv6_cache);
+ }
+
+ hash_clear(mac_t, &mac_cache);