lib/classifier: Simpilify array ordering.
[cascardo/ovs.git] / lib / classifier.c
index 74ef2ae..a0ba6ab 100644 (file)
 VLOG_DEFINE_THIS_MODULE(classifier);
 
 struct trie_node;
+struct trie_ctx;
+
+/* Ports trie depends on both ports sharing the same ovs_be32. */
+#define TP_PORTS_OFS32 (offsetof(struct flow, tp_src) / 4)
+BUILD_ASSERT_DECL(TP_PORTS_OFS32 == offsetof(struct flow, tp_dst) / 4);
 
 /* Prefix trie for a 'field' */
 struct cls_trie {
@@ -40,7 +45,6 @@ struct cls_trie {
 
 struct cls_subtable_entry {
     struct cls_subtable *subtable;
-    uint32_t *mask_values;
     tag_type tag;
     unsigned int max_priority;
 };
@@ -72,7 +76,6 @@ struct cls_subtable {
     struct hmap_node hmap_node; /* Within struct cls_classifier 'subtables'
                                  * hmap. */
     struct hmap rules;          /* Contains "struct cls_rule"s. */
-    struct minimask mask;       /* Wildcards for fields. */
     int n_rules;                /* Number of rules, including duplicates. */
     unsigned int max_priority;  /* Max priority of any rule in the subtable. */
     unsigned int max_count;     /* Count of max_priority rules. */
@@ -81,6 +84,10 @@ struct cls_subtable {
     uint8_t index_ofs[CLS_MAX_INDICES]; /* u32 flow segment boundaries. */
     struct hindex indices[CLS_MAX_INDICES]; /* Staged lookup indices. */
     unsigned int trie_plen[CLS_MAX_TRIES];  /* Trie prefix length in 'mask'. */
+    int ports_mask_len;
+    struct trie_node *ports_trie; /* NULL if none. */
+    struct minimask mask;       /* Wildcards for fields. */
+    /* 'mask' must be the last field. */
 };
 
 /* Associates a metadata value (that is, a value of the OpenFlow 1.1+ metadata
@@ -103,23 +110,27 @@ struct cls_match {
     unsigned int priority;      /* Larger numbers are higher priorities. */
     struct cls_partition *partition;
     struct list list;           /* List of identical, lower-priority rules. */
-    struct minimatch match;     /* Matching rule. */
+    struct miniflow flow;       /* Matching rule. Mask is in the subtable. */
+    /* 'flow' must be the last field. */
 };
 
 static struct cls_match *
 cls_match_alloc(struct cls_rule *rule)
 {
-    struct cls_match *cls_match = xmalloc(sizeof *cls_match);
+    int count = count_1bits(rule->match.flow.map);
+
+    struct cls_match *cls_match
+        = xmalloc(sizeof *cls_match - sizeof cls_match->flow.inline_values
+                  + MINIFLOW_VALUES_SIZE(count));
 
     cls_match->cls_rule = rule;
-    minimatch_clone(&cls_match->match, &rule->match);
+    miniflow_clone_inline(&cls_match->flow, &rule->match.flow, count);
     cls_match->priority = rule->priority;
     rule->cls_match = cls_match;
 
     return cls_match;
 }
 
-struct trie_ctx;
 static struct cls_subtable *find_subtable(const struct cls_classifier *,
                                           const struct minimask *);
 static struct cls_subtable *insert_subtable(struct cls_classifier *,
@@ -160,10 +171,16 @@ static void trie_init(struct cls_classifier *, int trie_idx,
                       const struct mf_field *);
 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
                                 unsigned int *checkbits);
-
+static unsigned int trie_lookup_value(const struct trie_node *,
+                                      const ovs_be32 value[],
+                                      unsigned int *checkbits);
 static void trie_destroy(struct trie_node *);
 static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
+static void trie_insert_prefix(struct trie_node **, const ovs_be32 *prefix,
+                               int mlen);
 static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
+static void trie_remove_prefix(struct trie_node **, const ovs_be32 *prefix,
+                               int mlen);
 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
                                  unsigned int nbits);
 static bool mask_prefix_bits_set(const struct flow_wildcards *,
@@ -195,26 +212,25 @@ cls_subtable_cache_push_back(struct cls_subtable_cache *array,
     array->subtables[array->size++] = a;
 }
 
-/* Only for rearranging entries in the same cache. */
+/* Move subtable entry at 'from' to 'to', shifting the elements in between
+ * (including the one at 'to') accordingly. */
 static inline void
-cls_subtable_cache_splice(struct cls_subtable_entry *to,
-                          struct cls_subtable_entry *start,
-                          struct cls_subtable_entry *end)
-{
-    if (to > end) {
-        /* Same as splicing entries to (start) from [end, to). */
-        struct cls_subtable_entry *temp = to;
-        to = start; start = end; end = temp;
-    }
-    if (to < start) {
-        while (start != end) {
-            struct cls_subtable_entry temp = *start;
-
-            memmove(to + 1, to, (start - to) * sizeof *to);
-            *to = temp;
-            start++;
+cls_subtable_cache_move(struct cls_subtable_entry *to,
+                        struct cls_subtable_entry *from)
+{
+    if (to != from) {
+        struct cls_subtable_entry temp = *from;
+
+        if (to > from) {
+            /* Shift entries (from,to] backwards to make space at 'to'. */
+            memmove(from, from + 1, (to - from) * sizeof *to);
+        } else {
+            /* Shift entries [to,from) forward to make space at 'to'. */
+            memmove(to + 1, to, (from - to) * sizeof *to);
         }
-    } /* Else nothing to be done. */
+
+        *to = temp;
+    }
 }
 
 /* Array removal. */
@@ -245,6 +261,125 @@ cls_subtable_cache_remove(struct cls_subtable_cache *array,
          ITER > (ARRAY)->subtables                                  \
              && OVS_LIKELY(SUBTABLE = (--ITER)->subtable);)
 
+static void
+cls_subtable_cache_verify(struct cls_subtable_cache *array)
+{
+    struct cls_subtable *table;
+    struct cls_subtable_entry *iter;
+    unsigned int priority = 0;
+
+    CLS_SUBTABLE_CACHE_FOR_EACH_REVERSE (table, iter, array) {
+        if (iter->max_priority != table->max_priority) {
+            VLOG_WARN("Subtable %p has mismatching priority in cache (%u != %u)",
+                      table, iter->max_priority, table->max_priority);
+        }
+        if (iter->max_priority < priority) {
+            VLOG_WARN("Subtable cache is out of order (%u < %u)",
+                      iter->max_priority, priority);
+        }
+        priority = iter->max_priority;
+    }
+}
+
+static void
+cls_subtable_cache_reset(struct cls_classifier *cls)
+{
+    struct cls_subtable_cache old = cls->subtables_priority;
+    struct cls_subtable *subtable;
+
+    VLOG_WARN("Resetting subtable cache.");
+
+    cls_subtable_cache_verify(&cls->subtables_priority);
+
+    cls_subtable_cache_init(&cls->subtables_priority);
+
+    HMAP_FOR_EACH (subtable, hmap_node, &cls->subtables) {
+        struct cls_match *head;
+        struct cls_subtable_entry elem;
+        struct cls_subtable *table;
+        struct cls_subtable_entry *iter, *from = NULL;
+        unsigned int new_max = 0;
+        unsigned int max_count = 0;
+        bool found;
+
+        /* Verify max_priority. */
+        HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
+            if (head->priority > new_max) {
+                new_max = head->priority;
+                max_count = 1;
+            } else if (head->priority == new_max) {
+                max_count++;
+            }
+        }
+        if (new_max != subtable->max_priority ||
+            max_count != subtable->max_count) {
+            VLOG_WARN("subtable %p (%u rules) has mismatching max_priority "
+                      "(%u) or max_count (%u). Highest priority found was %u, "
+                      "count: %u",
+                      subtable, subtable->n_rules, subtable->max_priority,
+                      subtable->max_count, new_max, max_count);
+            subtable->max_priority = new_max;
+            subtable->max_count = max_count;
+        }
+
+        /* Locate the subtable from the old cache. */
+        found = false;
+        CLS_SUBTABLE_CACHE_FOR_EACH (table, iter, &old) {
+            if (table == subtable) {
+                if (iter->max_priority != new_max) {
+                    VLOG_WARN("Subtable %p has wrong max priority (%u != %u) "
+                              "in the old cache.",
+                              subtable, iter->max_priority, new_max);
+                }
+                if (found) {
+                    VLOG_WARN("Subtable %p duplicated in the old cache.",
+                              subtable);
+                }
+                found = true;
+            }
+        }
+        if (!found) {
+            VLOG_WARN("Subtable %p not found from the old cache.", subtable);
+        }
+
+        elem.subtable = subtable;
+        elem.tag = subtable->tag;
+        elem.max_priority = subtable->max_priority;
+        cls_subtable_cache_push_back(&cls->subtables_priority, elem);
+
+        /* Possibly move 'subtable' earlier in the priority array.  If
+         * we break out of the loop, then the subtable (at 'from')
+         * should be moved to the position right after the current
+         * element.  If the loop terminates normally, then 'iter' will
+         * be at the first array element and we'll move the subtable
+         * to the front of the array. */
+        CLS_SUBTABLE_CACHE_FOR_EACH_REVERSE (table, iter,
+                                             &cls->subtables_priority) {
+            if (table == subtable) {
+                from = iter; /* Locate the subtable as we go. */
+            } else if (table->max_priority >= new_max) {
+                ovs_assert(from != NULL);
+                iter++; /* After this. */
+                break;
+            }
+        }
+
+        /* Move subtable at 'from' to 'iter'. */
+        cls_subtable_cache_move(iter, from);
+    }
+
+    /* Verify that the old and the new have the same size. */
+    if (old.size != cls->subtables_priority.size) {
+        VLOG_WARN("subtables cache sizes differ: old (%"PRIuSIZE
+                  ") != new (%"PRIuSIZE").",
+                  old.size, cls->subtables_priority.size);
+    }
+
+    cls_subtable_cache_destroy(&old);
+
+    cls_subtable_cache_verify(&cls->subtables_priority);
+}
+
 \f
 /* flow/miniflow/minimask/minimatch utilities.
  * These are only used by the classifier, so place them here to allow
@@ -278,8 +413,9 @@ static inline uint32_t
 flow_hash_in_minimask(const struct flow *flow, const struct minimask *mask,
                       uint32_t basis)
 {
+    const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
     const uint32_t *flow_u32 = (const uint32_t *)flow;
-    const uint32_t *p = mask->masks.values;
+    const uint32_t *p = mask_values;
     uint32_t hash;
     uint64_t map;
 
@@ -288,7 +424,7 @@ flow_hash_in_minimask(const struct flow *flow, const struct minimask *mask,
         hash = mhash_add(hash, flow_u32[raw_ctz(map)] & *p++);
     }
 
-    return mhash_finish(hash, (p - mask->masks.values) * 4);
+    return mhash_finish(hash, (p - mask_values) * 4);
 }
 
 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
@@ -300,7 +436,8 @@ static inline uint32_t
 miniflow_hash_in_minimask(const struct miniflow *flow,
                           const struct minimask *mask, uint32_t basis)
 {
-    const uint32_t *p = mask->masks.values;
+    const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
+    const uint32_t *p = mask_values;
     uint32_t hash = basis;
     uint32_t flow_u32;
 
@@ -308,7 +445,7 @@ miniflow_hash_in_minimask(const struct miniflow *flow,
         hash = mhash_add(hash, flow_u32 & *p++);
     }
 
-    return mhash_finish(hash, (p - mask->masks.values) * 4);
+    return mhash_finish(hash, (p - mask_values) * 4);
 }
 
 /* Returns a hash value for the bits of range [start, end) in 'flow',
@@ -321,11 +458,12 @@ flow_hash_in_minimask_range(const struct flow *flow,
                             const struct minimask *mask,
                             uint8_t start, uint8_t end, uint32_t *basis)
 {
+    const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
     const uint32_t *flow_u32 = (const uint32_t *)flow;
     unsigned int offset;
     uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
                                              &offset);
-    const uint32_t *p = mask->masks.values + offset;
+    const uint32_t *p = mask_values + offset;
     uint32_t hash = *basis;
 
     for (; map; map = zero_rightmost_1bit(map)) {
@@ -333,7 +471,7 @@ flow_hash_in_minimask_range(const struct flow *flow,
     }
 
     *basis = hash; /* Allow continuation from the unfinished value. */
-    return mhash_finish(hash, (p - mask->masks.values) * 4);
+    return mhash_finish(hash, (p - mask_values) * 4);
 }
 
 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask. */
@@ -355,7 +493,7 @@ flow_wildcards_fold_minimask_range(struct flow_wildcards *wc,
     unsigned int offset;
     uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
                                              &offset);
-    const uint32_t *p = mask->masks.values + offset;
+    const uint32_t *p = miniflow_get_u32_values(&mask->masks) + offset;
 
     for (; map; map = zero_rightmost_1bit(map)) {
         dst_u32[raw_ctz(map)] |= *p++;
@@ -366,7 +504,8 @@ flow_wildcards_fold_minimask_range(struct flow_wildcards *wc,
 static inline uint32_t
 miniflow_hash(const struct miniflow *flow, uint32_t basis)
 {
-    const uint32_t *p = flow->values;
+    const uint32_t *values = miniflow_get_u32_values(flow);
+    const uint32_t *p = values;
     uint32_t hash = basis;
     uint64_t hash_map = 0;
     uint64_t map;
@@ -381,7 +520,7 @@ miniflow_hash(const struct miniflow *flow, uint32_t basis)
     hash = mhash_add(hash, hash_map);
     hash = mhash_add(hash, hash_map >> 32);
 
-    return mhash_finish(hash, p - flow->values);
+    return mhash_finish(hash, p - values);
 }
 
 /* Returns a hash value for 'mask', given 'basis'. */
@@ -414,8 +553,8 @@ minimatch_hash_range(const struct minimatch *match, uint8_t start, uint8_t end,
 
     n = count_1bits(miniflow_get_map_in_range(&match->mask.masks, start, end,
                                               &offset));
-    q = match->mask.masks.values + offset;
-    p = match->flow.values + offset;
+    q = miniflow_get_u32_values(&match->mask.masks) + offset;
+    p = miniflow_get_u32_values(&match->flow) + offset;
 
     for (i = 0; i < n; i++) {
         hash = mhash_add(hash, p[i] & q[i]);
@@ -712,6 +851,13 @@ create_partition(struct cls_classifier *cls, struct cls_subtable *subtable,
     return partition;
 }
 
+static inline ovs_be32 minimatch_get_ports(const struct minimatch *match)
+{
+    /* Could optimize to use the same map if needed for fast path. */
+    return MINIFLOW_GET_BE32(&match->flow, tp_src)
+        & MINIFLOW_GET_BE32(&match->mask.masks, tp_src);
+}
+
 /* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
  * must not modify or free it.
  *
@@ -756,6 +902,19 @@ classifier_replace(struct classifier *cls_, struct cls_rule *rule)
                 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
             }
         }
+
+        /* Ports trie. */
+        if (subtable->ports_mask_len) {
+            /* We mask the value to be inserted to always have the wildcarded
+             * bits in known (zero) state, so we can include them in comparison
+             * and they will always match (== their original value does not
+             * matter). */
+            ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
+
+            trie_insert_prefix(&subtable->ports_trie, &masked_ports,
+                               subtable->ports_mask_len);
+        }
+
         return NULL;
     } else {
         struct cls_rule *old_cls_rule = old_rule->cls_rule;
@@ -796,9 +955,14 @@ classifier_remove(struct classifier *cls_, struct cls_rule *rule)
     ovs_assert(cls_match);
 
     subtable = find_subtable(cls, &rule->match.mask);
-
     ovs_assert(subtable);
 
+    if (subtable->ports_mask_len) {
+        ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
+
+        trie_remove_prefix(&subtable->ports_trie,
+                           &masked_ports, subtable->ports_mask_len);
+    }
     for (i = 0; i < cls->n_tries; i++) {
         if (subtable->trie_plen[i]) {
             trie_remove(&cls->tries[i], rule, subtable->trie_plen[i]);
@@ -870,7 +1034,6 @@ static inline void
 lookahead_subtable(const struct cls_subtable_entry *subtables)
 {
     ovs_prefetch_range(subtables->subtable, sizeof *subtables->subtable);
-    ovs_prefetch_range(subtables->mask_values, 1);
 }
 
 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
@@ -964,16 +1127,19 @@ classifier_lookup(const struct classifier *cls_, const struct flow *flow,
 }
 
 /* Returns true if 'target' satisifies 'match', that is, if each bit for which
- * 'match' specifies a particular value has the correct value in 'target'. */
+ * 'match' specifies a particular value has the correct value in 'target'.
+ *
+ * 'flow' and 'mask' have the same mask! */
 static bool
-minimatch_matches_miniflow(const struct minimatch *match,
-                           const struct miniflow *target)
+miniflow_and_mask_matches_miniflow(const struct miniflow *flow,
+                                   const struct minimask *mask,
+                                   const struct miniflow *target)
 {
-    const uint32_t *flowp = (const uint32_t *)match->flow.values;
-    const uint32_t *maskp = (const uint32_t *)match->mask.masks.values;
+    const uint32_t *flowp = miniflow_get_u32_values(flow);
+    const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
     uint32_t target_u32;
 
-    MINIFLOW_FOR_EACH_IN_MAP(target_u32, target, match->mask.masks.map) {
+    MINIFLOW_FOR_EACH_IN_MAP(target_u32, target, mask->masks.map) {
         if ((*flowp++ ^ target_u32) & *maskp++) {
             return false;
         }
@@ -990,7 +1156,8 @@ find_match_miniflow(const struct cls_subtable *subtable,
     struct cls_match *rule;
 
     HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &subtable->rules) {
-        if (minimatch_matches_miniflow(&rule->match, flow)) {
+        if (miniflow_and_mask_matches_miniflow(&rule->flow, &subtable->mask,
+                                               flow)) {
             return rule;
         }
     }
@@ -1108,7 +1275,7 @@ classifier_rule_overlaps(const struct classifier *cls_,
                 }
                 if (rule->priority == target->priority
                     && miniflow_equal_in_minimask(&target->match.flow,
-                                                  &rule->match.flow, &mask)) {
+                                                  &rule->flow, &mask)) {
                     return true;
                 }
             }
@@ -1166,7 +1333,7 @@ static bool
 rule_matches(const struct cls_match *rule, const struct cls_rule *target)
 {
     return (!target
-            || miniflow_equal_in_minimask(&rule->match.flow,
+            || miniflow_equal_in_minimask(&rule->flow,
                                           &target->match.flow,
                                           &target->match.mask));
 }
@@ -1280,10 +1447,12 @@ insert_subtable(struct cls_classifier *cls, const struct minimask *mask)
     struct flow_wildcards old, new;
     uint8_t prev;
     struct cls_subtable_entry elem;
+    int count = count_1bits(mask->masks.map);
 
-    subtable = xzalloc(sizeof *subtable);
+    subtable = xzalloc(sizeof *subtable - sizeof mask->masks.inline_values
+                       + MINIFLOW_VALUES_SIZE(count));
     hmap_init(&subtable->rules);
-    minimask_clone(&subtable->mask, mask);
+    miniflow_clone_inline(&subtable->mask.masks, &mask->masks, count);
 
     /* Init indices for segmented lookup, if any. */
     flow_wildcards_init_catchall(&new);
@@ -1322,9 +1491,13 @@ insert_subtable(struct cls_classifier *cls, const struct minimask *mask)
                                                          cls->tries[i].field);
     }
 
+    /* Ports trie. */
+    subtable->ports_trie = NULL;
+    subtable->ports_mask_len
+        = 32 - ctz32(ntohl(MINIFLOW_GET_BE32(&mask->masks, tp_src)));
+
     hmap_insert(&cls->subtables, &subtable->hmap_node, hash);
     elem.subtable = subtable;
-    elem.mask_values = subtable->mask.masks.values;
     elem.tag = subtable->tag;
     elem.max_priority = subtable->max_priority;
     cls_subtable_cache_push_back(&cls->subtables_priority, elem);
@@ -1346,6 +1519,8 @@ destroy_subtable(struct cls_classifier *cls, struct cls_subtable *subtable)
         }
     }
 
+    trie_destroy(subtable->ports_trie);
+
     for (i = 0; i < subtable->n_indices; i++) {
         hindex_destroy(&subtable->indices[i]);
     }
@@ -1374,31 +1549,36 @@ update_subtables_after_insertion(struct cls_classifier *cls,
         ++subtable->max_count;
     } else if (new_priority > subtable->max_priority) {
         struct cls_subtable *table;
-        struct cls_subtable_entry *iter, *subtable_iter = NULL;
+        struct cls_subtable_entry *iter, *from = NULL;
 
         subtable->max_priority = new_priority;
         subtable->max_count = 1;
 
-        /* Possibly move 'subtable' earlier in the priority list.  If we break
-         * out of the loop, then 'subtable_iter' should be moved just before
-         * 'iter'.  If the loop terminates normally, then 'iter' will be the
-         * first list element and we'll move subtable just before that
-         * (e.g. to the front of the list). */
-        CLS_SUBTABLE_CACHE_FOR_EACH_REVERSE (table, iter, &cls->subtables_priority) {
+        /* Possibly move 'subtable' earlier in the priority array.  If
+         * we break out of the loop, then the subtable (at 'from')
+         * should be moved to the position right after the current
+         * element.  If the loop terminates normally, then 'iter' will
+         * be at the first array element and we'll move the subtable
+         * to the front of the array. */
+        CLS_SUBTABLE_CACHE_FOR_EACH_REVERSE (table, iter,
+                                             &cls->subtables_priority) {
             if (table == subtable) {
-                subtable_iter = iter; /* Locate the subtable as we go. */
+                from = iter; /* Locate the subtable as we go. */
                 iter->max_priority = new_priority;
             } else if (table->max_priority >= new_priority) {
-                ovs_assert(subtable_iter != NULL);
-                iter++;
+                if (from == NULL) {
+                    /* Corrupted cache? */
+                    cls_subtable_cache_reset(cls);
+                    VLOG_ABORT("update_subtables_after_insertion(): Subtable priority list corrupted.");
+                    OVS_NOT_REACHED();
+                }
+                iter++; /* After this. */
                 break;
             }
         }
 
-        /* Move 'subtable' just before 'iter' (unless it's already there). */
-        if (iter != subtable_iter) {
-            cls_subtable_cache_splice(iter, subtable_iter, subtable_iter + 1);
-        }
+        /* Move subtable at 'from' to 'iter'. */
+        cls_subtable_cache_move(iter, from);
     }
 }
 
@@ -1420,7 +1600,7 @@ update_subtables_after_removal(struct cls_classifier *cls,
     if (del_priority == subtable->max_priority && --subtable->max_count == 0) {
         struct cls_match *head;
         struct cls_subtable *table;
-        struct cls_subtable_entry *iter, *subtable_iter = NULL;
+        struct cls_subtable_entry *iter, *from = NULL;
 
         subtable->max_priority = 0;
         HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
@@ -1432,25 +1612,30 @@ update_subtables_after_removal(struct cls_classifier *cls,
             }
         }
 
-        /* Possibly move 'subtable' later in the priority list.  If we break
-         * out of the loop, then 'subtable' should be moved just before that
-         * 'iter'.  If the loop terminates normally, then 'iter' will be the
-         * list head and we'll move subtable just before that (e.g. to the back
-         * of the list). */
+        /* Possibly move 'subtable' later in the priority array.
+         * After the loop the 'iter' will point right after the position
+         * at which the subtable should be moved (either at a subtable
+         * with an equal or lower priority, or just past the array),
+         * so it is decremented once. */
         CLS_SUBTABLE_CACHE_FOR_EACH (table, iter, &cls->subtables_priority) {
             if (table == subtable) {
-                subtable_iter = iter; /* Locate the subtable as we go. */
+                from = iter; /* Locate the subtable as we go. */
                 iter->max_priority = subtable->max_priority;
             } else if (table->max_priority <= subtable->max_priority) {
-                ovs_assert(subtable_iter != NULL);
+                if (from == NULL) {
+                    /* Corrupted cache? */
+                    cls_subtable_cache_reset(cls);
+                    VLOG_ABORT("update_subtables_after_removal(): Subtable priority list corrupted.");
+                    OVS_NOT_REACHED();
+                }
                 break;
             }
         }
+        /* Now at one past the destination. */
+        iter--;
 
-        /* Move 'subtable' just before 'iter' (unless it's already there). */
-        if (iter != subtable_iter) {
-            cls_subtable_cache_splice(iter, subtable_iter, subtable_iter + 1);
-        }
+        /* Move subtable at 'from' to 'iter'. */
+        cls_subtable_cache_move(iter, from);
     }
 }
 
@@ -1520,6 +1705,31 @@ check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
     return false;
 }
 
+/* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
+ * for which 'flow', for which 'mask' has a bit set, specifies a particular
+ * value has the correct value in 'target'.
+ *
+ * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
+ * target, mask) but it is faster because of the invariant that
+ * flow->map and mask->masks.map are the same. */
+static inline bool
+miniflow_and_mask_matches_flow(const struct miniflow *flow,
+                               const struct minimask *mask,
+                               const struct flow *target)
+{
+    const uint32_t *flowp = miniflow_get_u32_values(flow);
+    const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
+    uint32_t target_u32;
+
+    FLOW_FOR_EACH_IN_MAP(target_u32, target, mask->masks.map) {
+        if ((*flowp++ ^ target_u32) & *maskp++) {
+            return false;
+        }
+    }
+
+    return true;
+}
+
 static inline struct cls_match *
 find_match(const struct cls_subtable *subtable, const struct flow *flow,
            uint32_t hash)
@@ -1527,7 +1737,8 @@ find_match(const struct cls_subtable *subtable, const struct flow *flow,
     struct cls_match *rule;
 
     HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &subtable->rules) {
-        if (minimatch_matches_flow(&rule->match, flow)) {
+        if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
+                                           flow)) {
             return rule;
         }
     }
@@ -1575,8 +1786,8 @@ find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
          * not match, then we know that we will never get a match, but we do
          * not yet know how many wildcards we need to fold into 'wc' so we
          * continue iterating through indices to find that out.  (We won't
-         * waste time calling minimatch_matches_flow() again because we've set
-         * 'rule' nonnull.)
+         * waste time calling miniflow_and_mask_matches_flow() again because
+         * we've set 'rule' nonnull.)
          *
          * This check shows a measurable benefit with non-trivial flow tables.
          *
@@ -1584,7 +1795,8 @@ find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
          * optimization. */
         if (!inode->s && !rule) {
             ASSIGN_CONTAINER(rule, inode - i, index_nodes);
-            if (minimatch_matches_flow(&rule->match, flow)) {
+            if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
+                                               flow)) {
                 goto out;
             }
         }
@@ -1604,6 +1816,23 @@ find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
          * but it didn't match. */
         rule = NULL;
     }
+    if (!rule && subtable->ports_mask_len) {
+        /* Ports are always part of the final range, if any.
+         * No match was found for the ports.  Use the ports trie to figure out
+         * which ports bits to unwildcard. */
+        unsigned int mbits;
+        ovs_be32 value, mask;
+
+        mask = MINIFLOW_GET_BE32(&subtable->mask.masks, tp_src);
+        value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
+        trie_lookup_value(subtable->ports_trie, &value, &mbits);
+
+        ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
+            mask & htonl(~0 << (32 - mbits));
+
+        ofs.start = TP_PORTS_OFS32;
+        goto range_out;
+    }
  out:
     /* Must unwildcard all the fields, as they were looked at. */
     flow_wildcards_fold_minimask(wc, &subtable->mask);
@@ -1624,7 +1853,7 @@ find_equal(struct cls_subtable *subtable, const struct miniflow *flow,
     struct cls_match *head;
 
     HMAP_FOR_EACH_WITH_HASH (head, hmap_node, hash, &subtable->rules) {
-        if (miniflow_equal(&head->match.flow, flow)) {
+        if (miniflow_equal(&head->flow, flow)) {
             return head;
         }
     }
@@ -1987,7 +2216,7 @@ minimask_get_prefix_len(const struct minimask *minimask,
 static const ovs_be32 *
 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
 {
-    return match->flow.values +
+    return miniflow_get_be32_values(&match->flow) +
         count_1bits(match->flow.map & ((UINT64_C(1) << mf->flow_be32ofs) - 1));
 }
 
@@ -1997,14 +2226,18 @@ minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
 static void
 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
 {
-    const ovs_be32 *prefix = minimatch_get_prefix(&rule->match, trie->field);
+    trie_insert_prefix(&trie->root,
+                       minimatch_get_prefix(&rule->match, trie->field), mlen);
+}
+
+static void
+trie_insert_prefix(struct trie_node **edge, const ovs_be32 *prefix, int mlen)
+{
     struct trie_node *node;
-    struct trie_node **edge;
     int ofs = 0;
 
     /* Walk the tree. */
-    for (edge = &trie->root;
-         (node = *edge) != NULL;
+    for (; (node = *edge) != NULL;
          edge = trie_next_edge(node, prefix, ofs)) {
         unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
         ofs += eqbits;
@@ -2045,16 +2278,25 @@ trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
 static void
 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
 {
-    const ovs_be32 *prefix = minimatch_get_prefix(&rule->match, trie->field);
+    trie_remove_prefix(&trie->root,
+                       minimatch_get_prefix(&rule->match, trie->field), mlen);
+}
+
+/* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
+ * in 'rule'. */
+static void
+trie_remove_prefix(struct trie_node **root, const ovs_be32 *prefix, int mlen)
+{
     struct trie_node *node;
     struct trie_node **edges[sizeof(union mf_value) * 8];
     int depth = 0, ofs = 0;
 
     /* Walk the tree. */
-    for (edges[depth] = &trie->root;
+    for (edges[0] = root;
          (node = *edges[depth]) != NULL;
          edges[++depth] = trie_next_edge(node, prefix, ofs)) {
         unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
+
         if (eqbits < node->nbits) {
             /* Mismatch, nothing to be removed.  This should never happen, as
              * only rules in the classifier are ever removed. */