classifier: Lockless and robust classifier iteration.
[cascardo/ovs.git] / lib / classifier.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "classifier.h"
19 #include "classifier-private.h"
20 #include <errno.h>
21 #include <netinet/in.h>
22 #include "byte-order.h"
23 #include "dynamic-string.h"
24 #include "odp-util.h"
25 #include "ofp-util.h"
26 #include "packets.h"
27 #include "util.h"
28 #include "vlog.h"
29
30 VLOG_DEFINE_THIS_MODULE(classifier);
31
32 struct trie_ctx;
33
34 /* Ports trie depends on both ports sharing the same ovs_be32. */
35 #define TP_PORTS_OFS32 (offsetof(struct flow, tp_src) / 4)
36 BUILD_ASSERT_DECL(TP_PORTS_OFS32 == offsetof(struct flow, tp_dst) / 4);
37
38 static struct cls_match *
39 cls_match_alloc(struct cls_rule *rule)
40 {
41     int count = count_1bits(rule->match.flow.map);
42
43     struct cls_match *cls_match
44         = xmalloc(sizeof *cls_match - sizeof cls_match->flow.inline_values
45                   + MINIFLOW_VALUES_SIZE(count));
46
47     rculist_init(&cls_match->list);
48     *CONST_CAST(const struct cls_rule **, &cls_match->cls_rule) = rule;
49     *CONST_CAST(int *, &cls_match->priority) = rule->priority;
50     miniflow_clone_inline(CONST_CAST(struct miniflow *, &cls_match->flow),
51                           &rule->match.flow, count);
52
53     return cls_match;
54 }
55
56 static struct cls_subtable *find_subtable(const struct classifier *cls,
57                                           const struct minimask *);
58 static struct cls_subtable *insert_subtable(struct classifier *cls,
59                                             const struct minimask *)
60     OVS_REQUIRES(cls->mutex);
61 static void destroy_subtable(struct classifier *cls, struct cls_subtable *)
62     OVS_REQUIRES(cls->mutex);
63
64 static const struct cls_match *find_match_wc(const struct cls_subtable *,
65                                              const struct flow *,
66                                              struct trie_ctx *,
67                                              unsigned int n_tries,
68                                              struct flow_wildcards *);
69 static struct cls_match *find_equal(const struct cls_subtable *,
70                                     const struct miniflow *, uint32_t hash);
71
72 static inline const struct cls_match *
73 next_rule_in_list__(const struct cls_match *rule)
74 {
75     const struct cls_match *next = NULL;
76     next = OBJECT_CONTAINING(rculist_next(&rule->list), next, list);
77     return next;
78 }
79
80 static inline const struct cls_match *
81 next_rule_in_list(const struct cls_match *rule)
82 {
83     const struct cls_match *next = next_rule_in_list__(rule);
84     return next->priority < rule->priority ? next : NULL;
85 }
86
87 static inline struct cls_match *
88 next_rule_in_list_protected__(struct cls_match *rule)
89 {
90     struct cls_match *next = NULL;
91     next = OBJECT_CONTAINING(rculist_next_protected(&rule->list), next, list);
92     return next;
93 }
94
95 static inline struct cls_match *
96 next_rule_in_list_protected(struct cls_match *rule)
97 {
98     struct cls_match *next = next_rule_in_list_protected__(rule);
99     return next->priority < rule->priority ? next : NULL;
100 }
101
102 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list.
103  * Classifier's mutex must be held while iterating, as the list is
104  * protoceted by it. */
105 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD)                               \
106     for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
107 #define FOR_EACH_RULE_IN_LIST_PROTECTED(RULE, HEAD)     \
108     for ((RULE) = (HEAD); (RULE) != NULL;               \
109          (RULE) = next_rule_in_list_protected(RULE))
110
111 static unsigned int minimask_get_prefix_len(const struct minimask *,
112                                             const struct mf_field *);
113 static void trie_init(struct classifier *cls, int trie_idx,
114                       const struct mf_field *)
115     OVS_REQUIRES(cls->mutex);
116 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
117                                 union mf_value *plens);
118 static unsigned int trie_lookup_value(const rcu_trie_ptr *,
119                                       const ovs_be32 value[], ovs_be32 plens[],
120                                       unsigned int value_bits);
121 static void trie_destroy(rcu_trie_ptr *);
122 static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
123 static void trie_insert_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
124                                int mlen);
125 static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
126 static void trie_remove_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
127                                int mlen);
128 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
129                                  unsigned int n_bits);
130 static bool mask_prefix_bits_set(const struct flow_wildcards *,
131                                  uint8_t be32ofs, unsigned int n_bits);
132 \f
133 /* cls_rule. */
134
135 static inline void
136 cls_rule_init__(struct cls_rule *rule, unsigned int priority)
137     OVS_NO_THREAD_SAFETY_ANALYSIS
138 {
139     rculist_init(&rule->node);
140     rule->priority = priority;
141     rule->cls_match = NULL;
142 }
143
144 /* Initializes 'rule' to match packets specified by 'match' at the given
145  * 'priority'.  'match' must satisfy the invariant described in the comment at
146  * the definition of struct match.
147  *
148  * The caller must eventually destroy 'rule' with cls_rule_destroy().
149  *
150  * Clients should not use priority INT_MIN.  (OpenFlow uses priorities between
151  * 0 and UINT16_MAX, inclusive.) */
152 void
153 cls_rule_init(struct cls_rule *rule, const struct match *match, int priority)
154 {
155     cls_rule_init__(rule, priority);
156     minimatch_init(&rule->match, match);
157 }
158
159 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
160 void
161 cls_rule_init_from_minimatch(struct cls_rule *rule,
162                              const struct minimatch *match, int priority)
163 {
164     cls_rule_init__(rule, priority);
165     minimatch_clone(&rule->match, match);
166 }
167
168 /* Initializes 'dst' as a copy of 'src'.
169  *
170  * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
171 void
172 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
173 {
174     cls_rule_init__(dst, src->priority);
175     minimatch_clone(&dst->match, &src->match);
176 }
177
178 /* Initializes 'dst' with the data in 'src', destroying 'src'.
179  * 'src' must be a cls_rule NOT in a classifier.
180  *
181  * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
182 void
183 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
184     OVS_NO_THREAD_SAFETY_ANALYSIS
185 {
186     ovs_assert(!src->cls_match);   /* Must not be in a classifier. */
187     cls_rule_init__(dst, src->priority);
188     minimatch_move(&dst->match, &src->match);
189 }
190
191 /* Frees memory referenced by 'rule'.  Doesn't free 'rule' itself (it's
192  * normally embedded into a larger structure).
193  *
194  * ('rule' must not currently be in a classifier.) */
195 void
196 cls_rule_destroy(struct cls_rule *rule)
197     OVS_NO_THREAD_SAFETY_ANALYSIS
198 {
199     ovs_assert(!rule->cls_match);   /* Must not be in a classifier. */
200
201     /* Check that the rule has been properly removed from the classifier and
202      * that the destruction only happens after the RCU grace period, or that
203      * the rule was never inserted to the classifier in the first place. */
204     ovs_assert(rculist_next_protected(&rule->node) == RCULIST_POISON
205                || rculist_is_empty(&rule->node));
206
207     minimatch_destroy(&rule->match);
208 }
209
210 /* Returns true if 'a' and 'b' match the same packets at the same priority,
211  * false if they differ in some way. */
212 bool
213 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
214 {
215     return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
216 }
217
218 /* Returns a hash value for 'rule', folding in 'basis'. */
219 uint32_t
220 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
221 {
222     return minimatch_hash(&rule->match, hash_int(rule->priority, basis));
223 }
224
225 /* Appends a string describing 'rule' to 's'. */
226 void
227 cls_rule_format(const struct cls_rule *rule, struct ds *s)
228 {
229     minimatch_format(&rule->match, s, rule->priority);
230 }
231
232 /* Returns true if 'rule' matches every packet, false otherwise. */
233 bool
234 cls_rule_is_catchall(const struct cls_rule *rule)
235 {
236     return minimask_is_catchall(&rule->match.mask);
237 }
238 \f
239 /* Initializes 'cls' as a classifier that initially contains no classification
240  * rules. */
241 void
242 classifier_init(struct classifier *cls, const uint8_t *flow_segments)
243     OVS_EXCLUDED(cls->mutex)
244 {
245     ovs_mutex_init(&cls->mutex);
246     ovs_mutex_lock(&cls->mutex);
247     cls->n_rules = 0;
248     cmap_init(&cls->subtables_map);
249     pvector_init(&cls->subtables);
250     cmap_init(&cls->partitions);
251     cls->n_flow_segments = 0;
252     if (flow_segments) {
253         while (cls->n_flow_segments < CLS_MAX_INDICES
254                && *flow_segments < FLOW_U32S) {
255             cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
256         }
257     }
258     cls->n_tries = 0;
259     for (int i = 0; i < CLS_MAX_TRIES; i++) {
260         trie_init(cls, i, NULL);
261     }
262     ovs_mutex_unlock(&cls->mutex);
263 }
264
265 /* Destroys 'cls'.  Rules within 'cls', if any, are not freed; this is the
266  * caller's responsibility.
267  * May only be called after all the readers have been terminated. */
268 void
269 classifier_destroy(struct classifier *cls)
270     OVS_EXCLUDED(cls->mutex)
271 {
272     if (cls) {
273         struct cls_partition *partition;
274         struct cls_subtable *subtable;
275         int i;
276
277         ovs_mutex_lock(&cls->mutex);
278         for (i = 0; i < cls->n_tries; i++) {
279             trie_destroy(&cls->tries[i].root);
280         }
281
282         CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
283             destroy_subtable(cls, subtable);
284         }
285         cmap_destroy(&cls->subtables_map);
286
287         CMAP_FOR_EACH (partition, cmap_node, &cls->partitions) {
288             ovsrcu_postpone(free, partition);
289         }
290         cmap_destroy(&cls->partitions);
291
292         pvector_destroy(&cls->subtables);
293         ovs_mutex_unlock(&cls->mutex);
294         ovs_mutex_destroy(&cls->mutex);
295     }
296 }
297
298 /* Set the fields for which prefix lookup should be performed. */
299 bool
300 classifier_set_prefix_fields(struct classifier *cls,
301                              const enum mf_field_id *trie_fields,
302                              unsigned int n_fields)
303     OVS_EXCLUDED(cls->mutex)
304 {
305     const struct mf_field * new_fields[CLS_MAX_TRIES];
306     struct mf_bitmap fields = MF_BITMAP_INITIALIZER;
307     int i, n_tries = 0;
308     bool changed = false;
309
310     ovs_mutex_lock(&cls->mutex);
311     for (i = 0; i < n_fields && n_tries < CLS_MAX_TRIES; i++) {
312         const struct mf_field *field = mf_from_id(trie_fields[i]);
313         if (field->flow_be32ofs < 0 || field->n_bits % 32) {
314             /* Incompatible field.  This is the only place where we
315              * enforce these requirements, but the rest of the trie code
316              * depends on the flow_be32ofs to be non-negative and the
317              * field length to be a multiple of 32 bits. */
318             continue;
319         }
320
321         if (bitmap_is_set(fields.bm, trie_fields[i])) {
322             /* Duplicate field, there is no need to build more than
323              * one index for any one field. */
324             continue;
325         }
326         bitmap_set1(fields.bm, trie_fields[i]);
327
328         new_fields[n_tries] = NULL;
329         if (n_tries >= cls->n_tries || field != cls->tries[n_tries].field) {
330             new_fields[n_tries] = field;
331             changed = true;
332         }
333         n_tries++;
334     }
335
336     if (changed || n_tries < cls->n_tries) {
337         struct cls_subtable *subtable;
338
339         /* Trie configuration needs to change.  Disable trie lookups
340          * for the tries that are changing and wait all the current readers
341          * with the old configuration to be done. */
342         changed = false;
343         CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
344             for (i = 0; i < cls->n_tries; i++) {
345                 if ((i < n_tries && new_fields[i]) || i >= n_tries) {
346                     if (subtable->trie_plen[i]) {
347                         subtable->trie_plen[i] = 0;
348                         changed = true;
349                     }
350                 }
351             }
352         }
353         /* Synchronize if any readers were using tries.  The readers may
354          * temporarily function without the trie lookup based optimizations. */
355         if (changed) {
356             /* ovsrcu_synchronize() functions as a memory barrier, so it does
357              * not matter that subtable->trie_plen is not atomic. */
358             ovsrcu_synchronize();
359         }
360
361         /* Now set up the tries. */
362         for (i = 0; i < n_tries; i++) {
363             if (new_fields[i]) {
364                 trie_init(cls, i, new_fields[i]);
365             }
366         }
367         /* Destroy the rest, if any. */
368         for (; i < cls->n_tries; i++) {
369             trie_init(cls, i, NULL);
370         }
371
372         cls->n_tries = n_tries;
373         ovs_mutex_unlock(&cls->mutex);
374         return true;
375     }
376
377     ovs_mutex_unlock(&cls->mutex);
378     return false; /* No change. */
379 }
380
381 static void
382 trie_init(struct classifier *cls, int trie_idx, const struct mf_field *field)
383     OVS_REQUIRES(cls->mutex)
384 {
385     struct cls_trie *trie = &cls->tries[trie_idx];
386     struct cls_subtable *subtable;
387
388     if (trie_idx < cls->n_tries) {
389         trie_destroy(&trie->root);
390     } else {
391         ovsrcu_set_hidden(&trie->root, NULL);
392     }
393     trie->field = field;
394
395     /* Add existing rules to the new trie. */
396     CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
397         unsigned int plen;
398
399         plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
400         if (plen) {
401             struct cls_match *head;
402
403             CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
404                 trie_insert(trie, head->cls_rule, plen);
405             }
406         }
407         /* Initialize subtable's prefix length on this field.  This will
408          * allow readers to use the trie. */
409         atomic_thread_fence(memory_order_release);
410         subtable->trie_plen[trie_idx] = plen;
411     }
412 }
413
414 /* Returns true if 'cls' contains no classification rules, false otherwise.
415  * Checking the cmap requires no locking. */
416 bool
417 classifier_is_empty(const struct classifier *cls)
418 {
419     return cmap_is_empty(&cls->subtables_map);
420 }
421
422 /* Returns the number of rules in 'cls'. */
423 int
424 classifier_count(const struct classifier *cls)
425     OVS_NO_THREAD_SAFETY_ANALYSIS
426 {
427     /* n_rules is an int, so in the presence of concurrent writers this will
428      * return either the old or a new value. */
429     return cls->n_rules;
430 }
431
432 static uint32_t
433 hash_metadata(ovs_be64 metadata_)
434 {
435     uint64_t metadata = (OVS_FORCE uint64_t) metadata_;
436     return hash_uint64(metadata);
437 }
438
439 static struct cls_partition *
440 find_partition(const struct classifier *cls, ovs_be64 metadata, uint32_t hash)
441 {
442     struct cls_partition *partition;
443
444     CMAP_FOR_EACH_WITH_HASH (partition, cmap_node, hash, &cls->partitions) {
445         if (partition->metadata == metadata) {
446             return partition;
447         }
448     }
449
450     return NULL;
451 }
452
453 static struct cls_partition *
454 create_partition(struct classifier *cls, struct cls_subtable *subtable,
455                  ovs_be64 metadata)
456     OVS_REQUIRES(cls->mutex)
457 {
458     uint32_t hash = hash_metadata(metadata);
459     struct cls_partition *partition = find_partition(cls, metadata, hash);
460     if (!partition) {
461         partition = xmalloc(sizeof *partition);
462         partition->metadata = metadata;
463         partition->tags = 0;
464         tag_tracker_init(&partition->tracker);
465         cmap_insert(&cls->partitions, &partition->cmap_node, hash);
466     }
467     tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
468     return partition;
469 }
470
471 static inline ovs_be32 minimatch_get_ports(const struct minimatch *match)
472 {
473     /* Could optimize to use the same map if needed for fast path. */
474     return MINIFLOW_GET_BE32(&match->flow, tp_src)
475         & MINIFLOW_GET_BE32(&match->mask.masks, tp_src);
476 }
477
478 static void
479 subtable_replace_head_rule(struct classifier *cls OVS_UNUSED,
480                            struct cls_subtable *subtable,
481                            struct cls_match *head, struct cls_match *new,
482                            uint32_t hash, uint32_t ihash[CLS_MAX_INDICES])
483     OVS_REQUIRES(cls->mutex)
484 {
485     /* Rule's data is already in the tries. */
486
487     new->partition = head->partition; /* Steal partition, if any. */
488     head->partition = NULL;
489
490     for (int i = 0; i < subtable->n_indices; i++) {
491         cmap_replace(&subtable->indices[i], &head->index_nodes[i],
492                      &new->index_nodes[i], ihash[i]);
493     }
494     cmap_replace(&subtable->rules, &head->cmap_node, &new->cmap_node, hash);
495 }
496
497 /* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
498  * must not modify or free it.
499  *
500  * If 'cls' already contains an identical rule (including wildcards, values of
501  * fixed fields, and priority), replaces the old rule by 'rule' and returns the
502  * rule that was replaced.  The caller takes ownership of the returned rule and
503  * is thus responsible for destroying it with cls_rule_destroy(), after RCU
504  * grace period has passed (see ovsrcu_postpone()).
505  *
506  * Returns NULL if 'cls' does not contain a rule with an identical key, after
507  * inserting the new rule.  In this case, no rules are displaced by the new
508  * rule, even rules that cannot have any effect because the new rule matches a
509  * superset of their flows and has higher priority.
510  */
511 const struct cls_rule *
512 classifier_replace(struct classifier *cls, struct cls_rule *rule)
513     OVS_EXCLUDED(cls->mutex)
514 {
515     struct cls_match *new = cls_match_alloc(rule);
516     struct cls_subtable *subtable;
517     uint32_t ihash[CLS_MAX_INDICES];
518     uint8_t prev_be32ofs = 0;
519     struct cls_match *head;
520     size_t n_rules = 0;
521     uint32_t basis;
522     uint32_t hash;
523     int i;
524
525     ovs_mutex_lock(&cls->mutex);
526     rule->cls_match = new;
527
528     subtable = find_subtable(cls, &rule->match.mask);
529     if (!subtable) {
530         subtable = insert_subtable(cls, &rule->match.mask);
531     }
532
533     /* Compute hashes in segments. */
534     basis = 0;
535     for (i = 0; i < subtable->n_indices; i++) {
536         ihash[i] = minimatch_hash_range(&rule->match, prev_be32ofs,
537                                         subtable->index_ofs[i], &basis);
538         prev_be32ofs = subtable->index_ofs[i];
539     }
540     hash = minimatch_hash_range(&rule->match, prev_be32ofs, FLOW_U32S, &basis);
541
542     head = find_equal(subtable, &rule->match.flow, hash);
543     if (!head) {
544         /* Add rule to tries.
545          *
546          * Concurrent readers might miss seeing the rule until this update,
547          * which might require being fixed up by revalidation later. */
548         for (i = 0; i < cls->n_tries; i++) {
549             if (subtable->trie_plen[i]) {
550                 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
551             }
552         }
553
554         /* Add rule to ports trie. */
555         if (subtable->ports_mask_len) {
556             /* We mask the value to be inserted to always have the wildcarded
557              * bits in known (zero) state, so we can include them in comparison
558              * and they will always match (== their original value does not
559              * matter). */
560             ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
561
562             trie_insert_prefix(&subtable->ports_trie, &masked_ports,
563                                subtable->ports_mask_len);
564         }
565
566         /* Add rule to partitions.
567          *
568          * Concurrent readers might miss seeing the rule until this update,
569          * which might require being fixed up by revalidation later. */
570         new->partition = NULL;
571         if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
572             ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
573
574             new->partition = create_partition(cls, subtable, metadata);
575         }
576
577         /* Make rule visible to lookups. */
578
579         /* Add new node to segment indices.
580          *
581          * Readers may find the rule in the indices before the rule is visible
582          * in the subtables 'rules' map.  This may result in us losing the
583          * opportunity to quit lookups earlier, resulting in sub-optimal
584          * wildcarding.  This will be fixed later by revalidation (always
585          * scheduled after flow table changes). */
586         for (i = 0; i < subtable->n_indices; i++) {
587             cmap_insert(&subtable->indices[i], &new->index_nodes[i], ihash[i]);
588         }
589         n_rules = cmap_insert(&subtable->rules, &new->cmap_node, hash);
590     } else {   /* Equal rules exist in the classifier already. */
591         struct cls_match *iter;
592
593         /* Scan the list for the insertion point that will keep the list in
594          * order of decreasing priority. */
595         FOR_EACH_RULE_IN_LIST_PROTECTED (iter, head) {
596             if (rule->priority >= iter->priority) {
597                 break;
598             }
599         }
600
601         /* 'iter' now at the insertion point or NULL it at end. */
602         if (iter) {
603             struct cls_rule *old;
604
605             if (rule->priority == iter->priority) {
606                 rculist_replace(&new->list, &iter->list);
607                 old = CONST_CAST(struct cls_rule *, iter->cls_rule);
608             } else {
609                 rculist_insert(&iter->list, &new->list);
610                 old = NULL;
611             }
612
613             /* Replace the existing head in data structures, if rule is the new
614              * head. */
615             if (iter == head) {
616                 subtable_replace_head_rule(cls, subtable, head, new, hash,
617                                            ihash);
618             }
619
620             if (old) {
621                 ovsrcu_postpone(free, iter);
622                 old->cls_match = NULL;
623
624                 /* No change in subtable's max priority or max count. */
625
626                 /* Make rule visible to iterators. */
627                 rculist_replace(&rule->node, &old->node);
628
629                 /* Return displaced rule.  Caller is responsible for keeping it
630                  * around until all threads quiesce. */
631                 ovs_mutex_unlock(&cls->mutex);
632                 return old;
633             }
634         } else {
635             rculist_push_back(&head->list, &new->list);
636         }
637     }
638
639     /* Make rule visible to iterators. */
640     rculist_push_back(&subtable->rules_list, &rule->node);
641
642     /* Rule was added, not replaced.  Update 'subtable's 'max_priority' and
643      * 'max_count', if necessary.
644      *
645      * The rule was already inserted, but concurrent readers may not see the
646      * rule yet as the subtables vector is not updated yet.  This will have to
647      * be fixed by revalidation later. */
648     if (n_rules == 1) {
649         subtable->max_priority = rule->priority;
650         subtable->max_count = 1;
651         pvector_insert(&cls->subtables, subtable, rule->priority);
652     } else if (rule->priority == subtable->max_priority) {
653         ++subtable->max_count;
654     } else if (rule->priority > subtable->max_priority) {
655         subtable->max_priority = rule->priority;
656         subtable->max_count = 1;
657         pvector_change_priority(&cls->subtables, subtable, rule->priority);
658     }
659
660     /* Nothing was replaced. */
661     cls->n_rules++;
662     ovs_mutex_unlock(&cls->mutex);
663     return NULL;
664 }
665
666 /* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
667  * must not modify or free it.
668  *
669  * 'cls' must not contain an identical rule (including wildcards, values of
670  * fixed fields, and priority).  Use classifier_find_rule_exactly() to find
671  * such a rule. */
672 void
673 classifier_insert(struct classifier *cls, struct cls_rule *rule)
674 {
675     const struct cls_rule *displaced_rule = classifier_replace(cls, rule);
676     ovs_assert(!displaced_rule);
677 }
678
679 /* Removes 'rule' from 'cls'.  It is the caller's responsibility to destroy
680  * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
681  * resides, etc., as necessary.
682  *
683  * Does nothing if 'rule' has been already removed, or was never inserted.
684  *
685  * Returns the removed rule, or NULL, if it was already removed.
686  */
687 const struct cls_rule *
688 classifier_remove(struct classifier *cls, const struct cls_rule *rule)
689     OVS_EXCLUDED(cls->mutex)
690 {
691     struct cls_partition *partition;
692     struct cls_match *cls_match;
693     struct cls_subtable *subtable;
694     struct cls_match *prev;
695     struct cls_match *next;
696     int i;
697     uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
698     uint8_t prev_be32ofs = 0;
699     size_t n_rules;
700
701     ovs_mutex_lock(&cls->mutex);
702     cls_match = rule->cls_match;
703     if (!cls_match) {
704         rule = NULL;
705         goto unlock; /* Already removed. */
706     }
707     /* Mark as removed. */
708     CONST_CAST(struct cls_rule *, rule)->cls_match = NULL;
709
710     /* Remove 'rule' from the subtable's rules list. */
711     rculist_remove(&CONST_CAST(struct cls_rule *, rule)->node);
712
713     INIT_CONTAINER(prev, rculist_back_protected(&cls_match->list), list);
714     INIT_CONTAINER(next, rculist_next(&cls_match->list), list);
715
716     /* Remove from the list of equal rules. */
717     rculist_remove(&cls_match->list);
718
719     /* Check if this is NOT a head rule. */
720     if (prev->priority > rule->priority) {
721         /* Not the highest priority rule, no need to check subtable's
722          * 'max_priority'. */
723         goto free;
724     }
725
726     subtable = find_subtable(cls, &rule->match.mask);
727     ovs_assert(subtable);
728
729     for (i = 0; i < subtable->n_indices; i++) {
730         ihash[i] = minimatch_hash_range(&rule->match, prev_be32ofs,
731                                         subtable->index_ofs[i], &basis);
732         prev_be32ofs = subtable->index_ofs[i];
733     }
734     hash = minimatch_hash_range(&rule->match, prev_be32ofs, FLOW_U32S, &basis);
735
736     /* Head rule.  Check if 'next' is an identical, lower-priority rule that
737      * will replace 'rule' in the data structures. */
738     if (next->priority < rule->priority) {
739         subtable_replace_head_rule(cls, subtable, cls_match, next, hash,
740                                    ihash);
741         goto check_priority;
742     }
743
744     /* 'rule' is last of the kind in the classifier, must remove from all the
745      * data structures. */
746
747     if (subtable->ports_mask_len) {
748         ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
749
750         trie_remove_prefix(&subtable->ports_trie,
751                            &masked_ports, subtable->ports_mask_len);
752     }
753     for (i = 0; i < cls->n_tries; i++) {
754         if (subtable->trie_plen[i]) {
755             trie_remove(&cls->tries[i], rule, subtable->trie_plen[i]);
756         }
757     }
758
759     /* Remove rule node from indices. */
760     for (i = 0; i < subtable->n_indices; i++) {
761         cmap_remove(&subtable->indices[i], &cls_match->index_nodes[i],
762                     ihash[i]);
763     }
764     n_rules = cmap_remove(&subtable->rules, &cls_match->cmap_node, hash);
765
766     partition = cls_match->partition;
767     if (partition) {
768         tag_tracker_subtract(&partition->tracker, &partition->tags,
769                              subtable->tag);
770         if (!partition->tags) {
771             cmap_remove(&cls->partitions, &partition->cmap_node,
772                         hash_metadata(partition->metadata));
773             ovsrcu_postpone(free, partition);
774         }
775     }
776
777     if (n_rules == 0) {
778         destroy_subtable(cls, subtable);
779     } else {
780 check_priority:
781         if (subtable->max_priority == rule->priority
782             && --subtable->max_count == 0) {
783             /* Find the new 'max_priority' and 'max_count'. */
784             struct cls_match *head;
785             int max_priority = INT_MIN;
786
787             CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
788                 if (head->priority > max_priority) {
789                     max_priority = head->priority;
790                     subtable->max_count = 1;
791                 } else if (head->priority == max_priority) {
792                     ++subtable->max_count;
793                 }
794             }
795             subtable->max_priority = max_priority;
796             pvector_change_priority(&cls->subtables, subtable, max_priority);
797         }
798     }
799 free:
800     ovsrcu_postpone(free, cls_match);
801     cls->n_rules--;
802 unlock:
803     ovs_mutex_unlock(&cls->mutex);
804
805     return rule;
806 }
807
808 /* Prefix tree context.  Valid when 'lookup_done' is true.  Can skip all
809  * subtables which have a prefix match on the trie field, but whose prefix
810  * length is not indicated in 'match_plens'.  For example, a subtable that
811  * has a 8-bit trie field prefix match can be skipped if
812  * !be_get_bit_at(&match_plens, 8 - 1).  If skipped, 'maskbits' prefix bits
813  * must be unwildcarded to make datapath flow only match packets it should. */
814 struct trie_ctx {
815     const struct cls_trie *trie;
816     bool lookup_done;        /* Status of the lookup. */
817     uint8_t be32ofs;         /* U32 offset of the field in question. */
818     unsigned int maskbits;   /* Prefix length needed to avoid false matches. */
819     union mf_value match_plens; /* Bitmask of prefix lengths with possible
820                                  * matches. */
821 };
822
823 static void
824 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
825 {
826     ctx->trie = trie;
827     ctx->be32ofs = trie->field->flow_be32ofs;
828     ctx->lookup_done = false;
829 }
830
831 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
832  * Returns a null pointer if no rules in 'cls' match 'flow'.  If multiple rules
833  * of equal priority match 'flow', returns one arbitrarily.
834  *
835  * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
836  * set of bits that were significant in the lookup.  At some point
837  * earlier, 'wc' should have been initialized (e.g., by
838  * flow_wildcards_init_catchall()). */
839 const struct cls_rule *
840 classifier_lookup(const struct classifier *cls, const struct flow *flow,
841                   struct flow_wildcards *wc)
842 {
843     const struct cls_partition *partition;
844     tag_type tags;
845     int best_priority = INT_MIN;
846     const struct cls_match *best;
847     struct trie_ctx trie_ctx[CLS_MAX_TRIES];
848     struct cls_subtable *subtable;
849
850     /* Synchronize for cls->n_tries and subtable->trie_plen.  They can change
851      * when table configuration changes, which happens typically only on
852      * startup. */
853     atomic_thread_fence(memory_order_acquire);
854
855     /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
856      * then 'flow' cannot possibly match in 'subtable':
857      *
858      *     - If flow->metadata maps to a given 'partition', then we can use
859      *       'tags' for 'partition->tags'.
860      *
861      *     - If flow->metadata has no partition, then no rule in 'cls' has an
862      *       exact-match for flow->metadata.  That means that we don't need to
863      *       search any subtable that includes flow->metadata in its mask.
864      *
865      * In either case, we always need to search any cls_subtables that do not
866      * include flow->metadata in its mask.  One way to do that would be to
867      * check the "cls_subtable"s explicitly for that, but that would require an
868      * extra branch per subtable.  Instead, we mark such a cls_subtable's
869      * 'tags' as TAG_ALL and make sure that 'tags' is never empty.  This means
870      * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
871      * need a special case.
872      */
873     partition = (cmap_is_empty(&cls->partitions)
874                  ? NULL
875                  : find_partition(cls, flow->metadata,
876                                   hash_metadata(flow->metadata)));
877     tags = partition ? partition->tags : TAG_ARBITRARY;
878
879     /* Initialize trie contexts for find_match_wc(). */
880     for (int i = 0; i < cls->n_tries; i++) {
881         trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
882     }
883
884     best = NULL;
885     PVECTOR_FOR_EACH_PRIORITY(subtable, best_priority, 2,
886                               sizeof(struct cls_subtable), &cls->subtables) {
887         const struct cls_match *rule;
888
889         if (!tag_intersects(tags, subtable->tag)) {
890             continue;
891         }
892
893         rule = find_match_wc(subtable, flow, trie_ctx, cls->n_tries, wc);
894         if (rule && rule->priority > best_priority) {
895             best_priority = rule->priority;
896             best = rule;
897         }
898     }
899
900     return best ? best->cls_rule : NULL;
901 }
902
903 /* Finds and returns a rule in 'cls' with exactly the same priority and
904  * matching criteria as 'target'.  Returns a null pointer if 'cls' doesn't
905  * contain an exact match. */
906 const struct cls_rule *
907 classifier_find_rule_exactly(const struct classifier *cls,
908                              const struct cls_rule *target)
909 {
910     const struct cls_match *head, *rule;
911     const struct cls_subtable *subtable;
912
913     subtable = find_subtable(cls, &target->match.mask);
914     if (!subtable) {
915         return NULL;
916     }
917
918     head = find_equal(subtable, &target->match.flow,
919                       miniflow_hash_in_minimask(&target->match.flow,
920                                                 &target->match.mask, 0));
921     if (!head) {
922         return NULL;
923     }
924     FOR_EACH_RULE_IN_LIST (rule, head) {
925         if (target->priority >= rule->priority) {
926             return target->priority == rule->priority ? rule->cls_rule : NULL;
927         }
928     }
929     return NULL;
930 }
931
932 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
933  * same matching criteria as 'target'.  Returns a null pointer if 'cls' doesn't
934  * contain an exact match. */
935 const struct cls_rule *
936 classifier_find_match_exactly(const struct classifier *cls,
937                               const struct match *target, int priority)
938 {
939     const struct cls_rule *retval;
940     struct cls_rule cr;
941
942     cls_rule_init(&cr, target, priority);
943     retval = classifier_find_rule_exactly(cls, &cr);
944     cls_rule_destroy(&cr);
945
946     return retval;
947 }
948
949 /* Checks if 'target' would overlap any other rule in 'cls'.  Two rules are
950  * considered to overlap if both rules have the same priority and a packet
951  * could match both.
952  *
953  * A trivial example of overlapping rules is two rules matching disjoint sets
954  * of fields. E.g., if one rule matches only on port number, while another only
955  * on dl_type, any packet from that specific port and with that specific
956  * dl_type could match both, if the rules also have the same priority. */
957 bool
958 classifier_rule_overlaps(const struct classifier *cls,
959                          const struct cls_rule *target)
960 {
961     struct cls_subtable *subtable;
962
963     /* Iterate subtables in the descending max priority order. */
964     PVECTOR_FOR_EACH_PRIORITY (subtable, target->priority - 1, 2,
965                                sizeof(struct cls_subtable), &cls->subtables) {
966         uint32_t storage[FLOW_U32S];
967         struct minimask mask;
968         const struct cls_rule *rule;
969
970         minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
971
972         RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
973             if (rule->priority == target->priority
974                 && miniflow_equal_in_minimask(&target->match.flow,
975                                               &rule->match.flow, &mask)) {
976                 return true;
977             }
978         }
979     }
980     return false;
981 }
982
983 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
984  * specific than 'criteria'.  That is, 'rule' matches 'criteria' and this
985  * function returns true if, for every field:
986  *
987  *   - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
988  *     field, or
989  *
990  *   - 'criteria' wildcards the field,
991  *
992  * Conversely, 'rule' does not match 'criteria' and this function returns false
993  * if, for at least one field:
994  *
995  *   - 'criteria' and 'rule' specify different values for the field, or
996  *
997  *   - 'criteria' specifies a value for the field but 'rule' wildcards it.
998  *
999  * Equivalently, the truth table for whether a field matches is:
1000  *
1001  *                                     rule
1002  *
1003  *                   c         wildcard    exact
1004  *                   r        +---------+---------+
1005  *                   i   wild |   yes   |   yes   |
1006  *                   t   card |         |         |
1007  *                   e        +---------+---------+
1008  *                   r  exact |    no   |if values|
1009  *                   i        |         |are equal|
1010  *                   a        +---------+---------+
1011  *
1012  * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
1013  * commands and by OpenFlow 1.0 aggregate and flow stats.
1014  *
1015  * Ignores rule->priority. */
1016 bool
1017 cls_rule_is_loose_match(const struct cls_rule *rule,
1018                         const struct minimatch *criteria)
1019 {
1020     return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
1021             && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
1022                                           &criteria->mask));
1023 }
1024 \f
1025 /* Iteration. */
1026
1027 static bool
1028 rule_matches(const struct cls_rule *rule, const struct cls_rule *target)
1029 {
1030     return (!target
1031             || miniflow_equal_in_minimask(&rule->match.flow,
1032                                           &target->match.flow,
1033                                           &target->match.mask));
1034 }
1035
1036 static const struct cls_rule *
1037 search_subtable(const struct cls_subtable *subtable,
1038                 struct cls_cursor *cursor)
1039 {
1040     if (!cursor->target
1041         || !minimask_has_extra(&subtable->mask, &cursor->target->match.mask)) {
1042         const struct cls_rule *rule;
1043
1044         RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
1045             if (rule_matches(rule, cursor->target)) {
1046                 return rule;
1047             }
1048         }
1049     }
1050     return NULL;
1051 }
1052
1053 /* Initializes 'cursor' for iterating through rules in 'cls', and returns the
1054  * first matching cls_rule via '*pnode', or NULL if there are no matches.
1055  *
1056  *     - If 'target' is null, the cursor will visit every rule in 'cls'.
1057  *
1058  *     - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1059  *       such that cls_rule_is_loose_match(rule, target) returns true.
1060  *
1061  * Ignores target->priority. */
1062 struct cls_cursor cls_cursor_start(const struct classifier *cls,
1063                                    const struct cls_rule *target)
1064 {
1065     struct cls_cursor cursor;
1066     struct cls_subtable *subtable;
1067
1068     cursor.cls = cls;
1069     cursor.target = target && !cls_rule_is_catchall(target) ? target : NULL;
1070     cursor.rule = NULL;
1071
1072     /* Find first rule. */
1073     PVECTOR_CURSOR_FOR_EACH (subtable, &cursor.subtables,
1074                              &cursor.cls->subtables) {
1075         const struct cls_rule *rule = search_subtable(subtable, &cursor);
1076
1077         if (rule) {
1078             cursor.subtable = subtable;
1079             cursor.rule = rule;
1080             break;
1081         }
1082     }
1083
1084     return cursor;
1085 }
1086
1087 static const struct cls_rule *
1088 cls_cursor_next(struct cls_cursor *cursor)
1089 {
1090     const struct cls_rule *rule;
1091     const struct cls_subtable *subtable;
1092
1093     rule = cursor->rule;
1094     subtable = cursor->subtable;
1095     RCULIST_FOR_EACH_CONTINUE (rule, node, &subtable->rules_list) {
1096         if (rule_matches(rule, cursor->target)) {
1097             return rule;
1098         }
1099     }
1100
1101     PVECTOR_CURSOR_FOR_EACH_CONTINUE (subtable, &cursor->subtables) {
1102         rule = search_subtable(subtable, cursor);
1103         if (rule) {
1104             cursor->subtable = subtable;
1105             return rule;
1106         }
1107     }
1108
1109     return NULL;
1110 }
1111
1112 /* Sets 'cursor->rule' to the next matching cls_rule in 'cursor''s iteration,
1113  * or to null if all matching rules have been visited. */
1114 void
1115 cls_cursor_advance(struct cls_cursor *cursor)
1116 {
1117     cursor->rule = cls_cursor_next(cursor);
1118 }
1119 \f
1120 static struct cls_subtable *
1121 find_subtable(const struct classifier *cls, const struct minimask *mask)
1122 {
1123     struct cls_subtable *subtable;
1124
1125     CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, minimask_hash(mask, 0),
1126                              &cls->subtables_map) {
1127         if (minimask_equal(mask, &subtable->mask)) {
1128             return subtable;
1129         }
1130     }
1131     return NULL;
1132 }
1133
1134 /* The new subtable will be visible to the readers only after this. */
1135 static struct cls_subtable *
1136 insert_subtable(struct classifier *cls, const struct minimask *mask)
1137     OVS_REQUIRES(cls->mutex)
1138 {
1139     uint32_t hash = minimask_hash(mask, 0);
1140     struct cls_subtable *subtable;
1141     int i, index = 0;
1142     struct flow_wildcards old, new;
1143     uint8_t prev;
1144     int count = count_1bits(mask->masks.map);
1145
1146     subtable = xzalloc(sizeof *subtable - sizeof mask->masks.inline_values
1147                        + MINIFLOW_VALUES_SIZE(count));
1148     cmap_init(&subtable->rules);
1149     miniflow_clone_inline(CONST_CAST(struct miniflow *, &subtable->mask.masks),
1150                           &mask->masks, count);
1151
1152     /* Init indices for segmented lookup, if any. */
1153     flow_wildcards_init_catchall(&new);
1154     old = new;
1155     prev = 0;
1156     for (i = 0; i < cls->n_flow_segments; i++) {
1157         flow_wildcards_fold_minimask_range(&new, mask, prev,
1158                                            cls->flow_segments[i]);
1159         /* Add an index if it adds mask bits. */
1160         if (!flow_wildcards_equal(&new, &old)) {
1161             cmap_init(&subtable->indices[index]);
1162             *CONST_CAST(uint8_t *, &subtable->index_ofs[index])
1163                 = cls->flow_segments[i];
1164             index++;
1165             old = new;
1166         }
1167         prev = cls->flow_segments[i];
1168     }
1169     /* Check if the rest of the subtable's mask adds any bits,
1170      * and remove the last index if it doesn't. */
1171     if (index > 0) {
1172         flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U32S);
1173         if (flow_wildcards_equal(&new, &old)) {
1174             --index;
1175             *CONST_CAST(uint8_t *, &subtable->index_ofs[index]) = 0;
1176             cmap_destroy(&subtable->indices[index]);
1177         }
1178     }
1179     *CONST_CAST(uint8_t *, &subtable->n_indices) = index;
1180
1181     *CONST_CAST(tag_type *, &subtable->tag) =
1182         (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1183          ? tag_create_deterministic(hash)
1184          : TAG_ALL);
1185
1186     for (i = 0; i < cls->n_tries; i++) {
1187         subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1188                                                          cls->tries[i].field);
1189     }
1190
1191     /* Ports trie. */
1192     ovsrcu_set_hidden(&subtable->ports_trie, NULL);
1193     *CONST_CAST(int *, &subtable->ports_mask_len)
1194         = 32 - ctz32(ntohl(MINIFLOW_GET_BE32(&mask->masks, tp_src)));
1195
1196     /* List of rules. */
1197     rculist_init(&subtable->rules_list);
1198
1199     cmap_insert(&cls->subtables_map, &subtable->cmap_node, hash);
1200
1201     return subtable;
1202 }
1203
1204 /* RCU readers may still access the subtable before it is actually freed. */
1205 static void
1206 destroy_subtable(struct classifier *cls, struct cls_subtable *subtable)
1207     OVS_REQUIRES(cls->mutex)
1208 {
1209     int i;
1210
1211     pvector_remove(&cls->subtables, subtable);
1212     cmap_remove(&cls->subtables_map, &subtable->cmap_node,
1213                 minimask_hash(&subtable->mask, 0));
1214
1215     ovs_assert(ovsrcu_get_protected(struct trie_node *, &subtable->ports_trie)
1216                == NULL);
1217     ovs_assert(cmap_is_empty(&subtable->rules));
1218     ovs_assert(rculist_is_empty(&subtable->rules_list));
1219
1220     for (i = 0; i < subtable->n_indices; i++) {
1221         cmap_destroy(&subtable->indices[i]);
1222     }
1223     cmap_destroy(&subtable->rules);
1224     ovsrcu_postpone(free, subtable);
1225 }
1226
1227 struct range {
1228     uint8_t start;
1229     uint8_t end;
1230 };
1231
1232 static unsigned int be_get_bit_at(const ovs_be32 value[], unsigned int ofs);
1233
1234 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1235  * lookup results. */
1236 static inline bool
1237 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1238             const unsigned int field_plen[CLS_MAX_TRIES],
1239             const struct range ofs, const struct flow *flow,
1240             struct flow_wildcards *wc)
1241 {
1242     int j;
1243
1244     /* Check if we could avoid fully unwildcarding the next level of
1245      * fields using the prefix tries.  The trie checks are done only as
1246      * needed to avoid folding in additional bits to the wildcards mask. */
1247     for (j = 0; j < n_tries; j++) {
1248         /* Is the trie field relevant for this subtable? */
1249         if (field_plen[j]) {
1250             struct trie_ctx *ctx = &trie_ctx[j];
1251             uint8_t be32ofs = ctx->be32ofs;
1252
1253             /* Is the trie field within the current range of fields? */
1254             if (be32ofs >= ofs.start && be32ofs < ofs.end) {
1255                 /* On-demand trie lookup. */
1256                 if (!ctx->lookup_done) {
1257                     memset(&ctx->match_plens, 0, sizeof ctx->match_plens);
1258                     ctx->maskbits = trie_lookup(ctx->trie, flow,
1259                                                 &ctx->match_plens);
1260                     ctx->lookup_done = true;
1261                 }
1262                 /* Possible to skip the rest of the subtable if subtable's
1263                  * prefix on the field is not included in the lookup result. */
1264                 if (!be_get_bit_at(&ctx->match_plens.be32, field_plen[j] - 1)) {
1265                     /* We want the trie lookup to never result in unwildcarding
1266                      * any bits that would not be unwildcarded otherwise.
1267                      * Since the trie is shared by the whole classifier, it is
1268                      * possible that the 'maskbits' contain bits that are
1269                      * irrelevant for the partition relevant for the current
1270                      * packet.  Hence the checks below. */
1271
1272                     /* Check that the trie result will not unwildcard more bits
1273                      * than this subtable would otherwise. */
1274                     if (ctx->maskbits <= field_plen[j]) {
1275                         /* Unwildcard the bits and skip the rest. */
1276                         mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1277                         /* Note: Prerequisite already unwildcarded, as the only
1278                          * prerequisite of the supported trie lookup fields is
1279                          * the ethertype, which is always unwildcarded. */
1280                         return true;
1281                     }
1282                     /* Can skip if the field is already unwildcarded. */
1283                     if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1284                         return true;
1285                     }
1286                 }
1287             }
1288         }
1289     }
1290     return false;
1291 }
1292
1293 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1294  * for which 'flow', for which 'mask' has a bit set, specifies a particular
1295  * value has the correct value in 'target'.
1296  *
1297  * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
1298  * target, mask) but this is faster because of the invariant that
1299  * flow->map and mask->masks.map are the same, and that this version
1300  * takes the 'wc'. */
1301 static inline bool
1302 miniflow_and_mask_matches_flow(const struct miniflow *flow,
1303                                const struct minimask *mask,
1304                                const struct flow *target)
1305 {
1306     const uint32_t *flowp = miniflow_get_u32_values(flow);
1307     const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1308     uint32_t idx;
1309
1310     MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1311         uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & *maskp++;
1312
1313         if (diff) {
1314             return false;
1315         }
1316     }
1317
1318     return true;
1319 }
1320
1321 static inline const struct cls_match *
1322 find_match(const struct cls_subtable *subtable, const struct flow *flow,
1323            uint32_t hash)
1324 {
1325     const struct cls_match *rule;
1326
1327     CMAP_FOR_EACH_WITH_HASH (rule, cmap_node, hash, &subtable->rules) {
1328         if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
1329                                            flow)) {
1330             return rule;
1331         }
1332     }
1333
1334     return NULL;
1335 }
1336
1337 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1338  * for which 'flow', for which 'mask' has a bit set, specifies a particular
1339  * value has the correct value in 'target'.
1340  *
1341  * This function is equivalent to miniflow_and_mask_matches_flow() but this
1342  * version fills in the mask bits in 'wc'. */
1343 static inline bool
1344 miniflow_and_mask_matches_flow_wc(const struct miniflow *flow,
1345                                   const struct minimask *mask,
1346                                   const struct flow *target,
1347                                   struct flow_wildcards *wc)
1348 {
1349     const uint32_t *flowp = miniflow_get_u32_values(flow);
1350     const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1351     uint32_t idx;
1352
1353     MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1354         uint32_t mask = *maskp++;
1355         uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & mask;
1356
1357         if (diff) {
1358             /* Only unwildcard if none of the differing bits is already
1359              * exact-matched. */
1360             if (!(flow_u32_value(&wc->masks, idx) & diff)) {
1361                 /* Keep one bit of the difference. */
1362                 *flow_u32_lvalue(&wc->masks, idx) |= rightmost_1bit(diff);
1363             }
1364             return false;
1365         }
1366         /* Fill in the bits that were looked at. */
1367         *flow_u32_lvalue(&wc->masks, idx) |= mask;
1368     }
1369
1370     return true;
1371 }
1372
1373 /* Unwildcard the fields looked up so far, if any. */
1374 static void
1375 fill_range_wc(const struct cls_subtable *subtable, struct flow_wildcards *wc,
1376               uint8_t to)
1377 {
1378     if (to) {
1379         flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, to);
1380     }
1381 }
1382
1383 static const struct cls_match *
1384 find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
1385               struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1386               struct flow_wildcards *wc)
1387 {
1388     uint32_t basis = 0, hash;
1389     const struct cls_match *rule = NULL;
1390     int i;
1391     struct range ofs;
1392
1393     if (OVS_UNLIKELY(!wc)) {
1394         return find_match(subtable, flow,
1395                           flow_hash_in_minimask(flow, &subtable->mask, 0));
1396     }
1397
1398     ofs.start = 0;
1399     /* Try to finish early by checking fields in segments. */
1400     for (i = 0; i < subtable->n_indices; i++) {
1401         const struct cmap_node *inode;
1402
1403         ofs.end = subtable->index_ofs[i];
1404
1405         if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1406                         wc)) {
1407             /* 'wc' bits for the trie field set, now unwildcard the preceding
1408              * bits used so far. */
1409             fill_range_wc(subtable, wc, ofs.start);
1410             return NULL;
1411         }
1412         hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1413                                            ofs.end, &basis);
1414         inode = cmap_find(&subtable->indices[i], hash);
1415         if (!inode) {
1416             /* No match, can stop immediately, but must fold in the bits
1417              * used in lookup so far. */
1418             fill_range_wc(subtable, wc, ofs.end);
1419             return NULL;
1420         }
1421
1422         /* If we have narrowed down to a single rule already, check whether
1423          * that rule matches.  Either way, we're done.
1424          *
1425          * (Rare) hash collisions may cause us to miss the opportunity for this
1426          * optimization. */
1427         if (!cmap_node_next(inode)) {
1428             ASSIGN_CONTAINER(rule, inode - i, index_nodes);
1429             if (miniflow_and_mask_matches_flow_wc(&rule->flow, &subtable->mask,
1430                                                   flow, wc)) {
1431                 return rule;
1432             }
1433             return NULL;
1434         }
1435         ofs.start = ofs.end;
1436     }
1437     ofs.end = FLOW_U32S;
1438     /* Trie check for the final range. */
1439     if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1440         fill_range_wc(subtable, wc, ofs.start);
1441         return NULL;
1442     }
1443     hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1444                                        ofs.end, &basis);
1445     rule = find_match(subtable, flow, hash);
1446     if (!rule && subtable->ports_mask_len) {
1447         /* Ports are always part of the final range, if any.
1448          * No match was found for the ports.  Use the ports trie to figure out
1449          * which ports bits to unwildcard. */
1450         unsigned int mbits;
1451         ovs_be32 value, plens, mask;
1452
1453         mask = MINIFLOW_GET_BE32(&subtable->mask.masks, tp_src);
1454         value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
1455         mbits = trie_lookup_value(&subtable->ports_trie, &value, &plens, 32);
1456
1457         ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
1458             mask & be32_prefix_mask(mbits);
1459
1460         /* Unwildcard all bits in the mask upto the ports, as they were used
1461          * to determine there is no match. */
1462         fill_range_wc(subtable, wc, TP_PORTS_OFS32);
1463         return NULL;
1464     }
1465
1466     /* Must unwildcard all the fields, as they were looked at. */
1467     flow_wildcards_fold_minimask(wc, &subtable->mask);
1468     return rule;
1469 }
1470
1471 static struct cls_match *
1472 find_equal(const struct cls_subtable *subtable, const struct miniflow *flow,
1473            uint32_t hash)
1474 {
1475     struct cls_match *head;
1476
1477     CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1478         if (miniflow_equal(&head->flow, flow)) {
1479             return head;
1480         }
1481     }
1482     return NULL;
1483 }
1484 \f
1485 /* A longest-prefix match tree. */
1486
1487 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1488  * Prefixes are in the network byte order, and the offset 0 corresponds to
1489  * the most significant bit of the first byte.  The offset can be read as
1490  * "how many bits to skip from the start of the prefix starting at 'pr'". */
1491 static uint32_t
1492 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1493 {
1494     uint32_t prefix;
1495
1496     pr += ofs / 32; /* Where to start. */
1497     ofs %= 32;      /* How many bits to skip at 'pr'. */
1498
1499     prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1500     if (plen > 32 - ofs) {      /* Need more than we have already? */
1501         prefix |= ntohl(*++pr) >> (32 - ofs);
1502     }
1503     /* Return with possible unwanted bits at the end. */
1504     return prefix;
1505 }
1506
1507 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1508  * offset 'ofs'.  Prefixes are in the network byte order, and the offset 0
1509  * corresponds to the most significant bit of the first byte.  The offset can
1510  * be read as "how many bits to skip from the start of the prefix starting at
1511  * 'pr'". */
1512 static uint32_t
1513 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1514 {
1515     if (!plen) {
1516         return 0;
1517     }
1518     if (plen > TRIE_PREFIX_BITS) {
1519         plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1520     }
1521     /* Return with unwanted bits cleared. */
1522     return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1523 }
1524
1525 /* Return the number of equal bits in 'n_bits' of 'prefix's MSBs and a 'value'
1526  * starting at "MSB 0"-based offset 'ofs'. */
1527 static unsigned int
1528 prefix_equal_bits(uint32_t prefix, unsigned int n_bits, const ovs_be32 value[],
1529                   unsigned int ofs)
1530 {
1531     uint64_t diff = prefix ^ raw_get_prefix(value, ofs, n_bits);
1532     /* Set the bit after the relevant bits to limit the result. */
1533     return raw_clz64(diff << 32 | UINT64_C(1) << (63 - n_bits));
1534 }
1535
1536 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1537  * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1538 static unsigned int
1539 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1540                        unsigned int ofs, unsigned int plen)
1541 {
1542     return prefix_equal_bits(node->prefix, MIN(node->n_bits, plen - ofs),
1543                              prefix, ofs);
1544 }
1545
1546 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int.  'ofs' can
1547  * be greater than 31. */
1548 static unsigned int
1549 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1550 {
1551     return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1552 }
1553
1554 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int.  'ofs' must
1555  * be between 0 and 31, inclusive. */
1556 static unsigned int
1557 get_bit_at(const uint32_t prefix, unsigned int ofs)
1558 {
1559     return (prefix >> (31 - ofs)) & 1u;
1560 }
1561
1562 /* Create new branch. */
1563 static struct trie_node *
1564 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1565                    unsigned int n_rules)
1566 {
1567     struct trie_node *node = xmalloc(sizeof *node);
1568
1569     node->prefix = trie_get_prefix(prefix, ofs, plen);
1570
1571     if (plen <= TRIE_PREFIX_BITS) {
1572         node->n_bits = plen;
1573         ovsrcu_set_hidden(&node->edges[0], NULL);
1574         ovsrcu_set_hidden(&node->edges[1], NULL);
1575         node->n_rules = n_rules;
1576     } else { /* Need intermediate nodes. */
1577         struct trie_node *subnode = trie_branch_create(prefix,
1578                                                        ofs + TRIE_PREFIX_BITS,
1579                                                        plen - TRIE_PREFIX_BITS,
1580                                                        n_rules);
1581         int bit = get_bit_at(subnode->prefix, 0);
1582         node->n_bits = TRIE_PREFIX_BITS;
1583         ovsrcu_set_hidden(&node->edges[bit], subnode);
1584         ovsrcu_set_hidden(&node->edges[!bit], NULL);
1585         node->n_rules = 0;
1586     }
1587     return node;
1588 }
1589
1590 static void
1591 trie_node_destroy(const struct trie_node *node)
1592 {
1593     ovsrcu_postpone(free, CONST_CAST(struct trie_node *, node));
1594 }
1595
1596 /* Copy a trie node for modification and postpone delete the old one. */
1597 static struct trie_node *
1598 trie_node_rcu_realloc(const struct trie_node *node)
1599 {
1600     struct trie_node *new_node = xmalloc(sizeof *node);
1601
1602     *new_node = *node;
1603     trie_node_destroy(node);
1604
1605     return new_node;
1606 }
1607
1608 /* May only be called while holding the classifier mutex. */
1609 static void
1610 trie_destroy(rcu_trie_ptr *trie)
1611 {
1612     struct trie_node *node = ovsrcu_get_protected(struct trie_node *, trie);
1613
1614     if (node) {
1615         ovsrcu_set_hidden(trie, NULL);
1616         trie_destroy(&node->edges[0]);
1617         trie_destroy(&node->edges[1]);
1618         trie_node_destroy(node);
1619     }
1620 }
1621
1622 static bool
1623 trie_is_leaf(const struct trie_node *trie)
1624 {
1625     /* No children? */
1626     return !ovsrcu_get(struct trie_node *, &trie->edges[0])
1627         && !ovsrcu_get(struct trie_node *, &trie->edges[1]);
1628 }
1629
1630 static void
1631 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1632                      unsigned int n_bits)
1633 {
1634     ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1635     unsigned int i;
1636
1637     for (i = 0; i < n_bits / 32; i++) {
1638         mask[i] = OVS_BE32_MAX;
1639     }
1640     if (n_bits % 32) {
1641         mask[i] |= htonl(~0u << (32 - n_bits % 32));
1642     }
1643 }
1644
1645 static bool
1646 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
1647                      unsigned int n_bits)
1648 {
1649     ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1650     unsigned int i;
1651     ovs_be32 zeroes = 0;
1652
1653     for (i = 0; i < n_bits / 32; i++) {
1654         zeroes |= ~mask[i];
1655     }
1656     if (n_bits % 32) {
1657         zeroes |= ~mask[i] & htonl(~0u << (32 - n_bits % 32));
1658     }
1659
1660     return !zeroes; /* All 'n_bits' bits set. */
1661 }
1662
1663 static rcu_trie_ptr *
1664 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
1665                unsigned int ofs)
1666 {
1667     return node->edges + be_get_bit_at(value, ofs);
1668 }
1669
1670 static const struct trie_node *
1671 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
1672                unsigned int ofs)
1673 {
1674     return ovsrcu_get(struct trie_node *,
1675                       &node->edges[be_get_bit_at(value, ofs)]);
1676 }
1677
1678 /* Set the bit at ("MSB 0"-based) offset 'ofs'.  'ofs' can be greater than 31.
1679  */
1680 static void
1681 be_set_bit_at(ovs_be32 value[], unsigned int ofs)
1682 {
1683     ((uint8_t *)value)[ofs / 8] |= 1u << (7 - ofs % 8);
1684 }
1685
1686 /* Returns the number of bits in the prefix mask necessary to determine a
1687  * mismatch, in case there are longer prefixes in the tree below the one that
1688  * matched.
1689  * '*plens' will have a bit set for each prefix length that may have matching
1690  * rules.  The caller is responsible for clearing the '*plens' prior to
1691  * calling this.
1692  */
1693 static unsigned int
1694 trie_lookup_value(const rcu_trie_ptr *trie, const ovs_be32 value[],
1695                   ovs_be32 plens[], unsigned int n_bits)
1696 {
1697     const struct trie_node *prev = NULL;
1698     const struct trie_node *node = ovsrcu_get(struct trie_node *, trie);
1699     unsigned int match_len = 0; /* Number of matching bits. */
1700
1701     for (; node; prev = node, node = trie_next_node(node, value, match_len)) {
1702         unsigned int eqbits;
1703         /* Check if this edge can be followed. */
1704         eqbits = prefix_equal_bits(node->prefix, node->n_bits, value,
1705                                    match_len);
1706         match_len += eqbits;
1707         if (eqbits < node->n_bits) { /* Mismatch, nothing more to be found. */
1708             /* Bit at offset 'match_len' differed. */
1709             return match_len + 1; /* Includes the first mismatching bit. */
1710         }
1711         /* Full match, check if rules exist at this prefix length. */
1712         if (node->n_rules > 0) {
1713             be_set_bit_at(plens, match_len - 1);
1714         }
1715         if (match_len >= n_bits) {
1716             return n_bits; /* Full prefix. */
1717         }
1718     }
1719     /* node == NULL.  Full match so far, but we tried to follow an
1720      * non-existing branch.  Need to exclude the other branch if it exists
1721      * (it does not if we were called on an empty trie or 'prev' is a leaf
1722      * node). */
1723     return !prev || trie_is_leaf(prev) ? match_len : match_len + 1;
1724 }
1725
1726 static unsigned int
1727 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
1728             union mf_value *plens)
1729 {
1730     const struct mf_field *mf = trie->field;
1731
1732     /* Check that current flow matches the prerequisites for the trie
1733      * field.  Some match fields are used for multiple purposes, so we
1734      * must check that the trie is relevant for this flow. */
1735     if (mf_are_prereqs_ok(mf, flow)) {
1736         return trie_lookup_value(&trie->root,
1737                                  &((ovs_be32 *)flow)[mf->flow_be32ofs],
1738                                  &plens->be32, mf->n_bits);
1739     }
1740     memset(plens, 0xff, sizeof *plens); /* All prefixes, no skipping. */
1741     return 0; /* Value not used in this case. */
1742 }
1743
1744 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
1745  * Returns the u32 offset to the miniflow data in '*miniflow_index', if
1746  * 'miniflow_index' is not NULL. */
1747 static unsigned int
1748 minimask_get_prefix_len(const struct minimask *minimask,
1749                         const struct mf_field *mf)
1750 {
1751     unsigned int n_bits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
1752     uint8_t u32_ofs = mf->flow_be32ofs;
1753     uint8_t u32_end = u32_ofs + mf->n_bytes / 4;
1754
1755     for (; u32_ofs < u32_end; ++u32_ofs) {
1756         uint32_t mask;
1757         mask = ntohl((OVS_FORCE ovs_be32)minimask_get(minimask, u32_ofs));
1758
1759         /* Validate mask, count the mask length. */
1760         if (mask_tz) {
1761             if (mask) {
1762                 return 0; /* No bits allowed after mask ended. */
1763             }
1764         } else {
1765             if (~mask & (~mask + 1)) {
1766                 return 0; /* Mask not contiguous. */
1767             }
1768             mask_tz = ctz32(mask);
1769             n_bits += 32 - mask_tz;
1770         }
1771     }
1772
1773     return n_bits;
1774 }
1775
1776 /*
1777  * This is called only when mask prefix is known to be CIDR and non-zero.
1778  * Relies on the fact that the flow and mask have the same map, and since
1779  * the mask is CIDR, the storage for the flow field exists even if it
1780  * happened to be zeros.
1781  */
1782 static const ovs_be32 *
1783 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
1784 {
1785     return miniflow_get_be32_values(&match->flow) +
1786         count_1bits(match->flow.map & ((UINT64_C(1) << mf->flow_be32ofs) - 1));
1787 }
1788
1789 /* Insert rule in to the prefix tree.
1790  * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1791  * in 'rule'. */
1792 static void
1793 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1794 {
1795     trie_insert_prefix(&trie->root,
1796                        minimatch_get_prefix(&rule->match, trie->field), mlen);
1797 }
1798
1799 static void
1800 trie_insert_prefix(rcu_trie_ptr *edge, const ovs_be32 *prefix, int mlen)
1801 {
1802     struct trie_node *node;
1803     int ofs = 0;
1804
1805     /* Walk the tree. */
1806     for (; (node = ovsrcu_get_protected(struct trie_node *, edge));
1807          edge = trie_next_edge(node, prefix, ofs)) {
1808         unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1809         ofs += eqbits;
1810         if (eqbits < node->n_bits) {
1811             /* Mismatch, new node needs to be inserted above. */
1812             int old_branch = get_bit_at(node->prefix, eqbits);
1813             struct trie_node *new_parent;
1814
1815             new_parent = trie_branch_create(prefix, ofs - eqbits, eqbits,
1816                                             ofs == mlen ? 1 : 0);
1817             /* Copy the node to modify it. */
1818             node = trie_node_rcu_realloc(node);
1819             /* Adjust the new node for its new position in the tree. */
1820             node->prefix <<= eqbits;
1821             node->n_bits -= eqbits;
1822             ovsrcu_set_hidden(&new_parent->edges[old_branch], node);
1823
1824             /* Check if need a new branch for the new rule. */
1825             if (ofs < mlen) {
1826                 ovsrcu_set_hidden(&new_parent->edges[!old_branch],
1827                                   trie_branch_create(prefix, ofs, mlen - ofs,
1828                                                      1));
1829             }
1830             ovsrcu_set(edge, new_parent); /* Publish changes. */
1831             return;
1832         }
1833         /* Full match so far. */
1834
1835         if (ofs == mlen) {
1836             /* Full match at the current node, rule needs to be added here. */
1837             node->n_rules++;
1838             return;
1839         }
1840     }
1841     /* Must insert a new tree branch for the new rule. */
1842     ovsrcu_set(edge, trie_branch_create(prefix, ofs, mlen - ofs, 1));
1843 }
1844
1845 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1846  * in 'rule'. */
1847 static void
1848 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1849 {
1850     trie_remove_prefix(&trie->root,
1851                        minimatch_get_prefix(&rule->match, trie->field), mlen);
1852 }
1853
1854 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1855  * in 'rule'. */
1856 static void
1857 trie_remove_prefix(rcu_trie_ptr *root, const ovs_be32 *prefix, int mlen)
1858 {
1859     struct trie_node *node;
1860     rcu_trie_ptr *edges[sizeof(union mf_value) * 8];
1861     int depth = 0, ofs = 0;
1862
1863     /* Walk the tree. */
1864     for (edges[0] = root;
1865          (node = ovsrcu_get_protected(struct trie_node *, edges[depth]));
1866          edges[++depth] = trie_next_edge(node, prefix, ofs)) {
1867         unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1868
1869         if (eqbits < node->n_bits) {
1870             /* Mismatch, nothing to be removed.  This should never happen, as
1871              * only rules in the classifier are ever removed. */
1872             break; /* Log a warning. */
1873         }
1874         /* Full match so far. */
1875         ofs += eqbits;
1876
1877         if (ofs == mlen) {
1878             /* Full prefix match at the current node, remove rule here. */
1879             if (!node->n_rules) {
1880                 break; /* Log a warning. */
1881             }
1882             node->n_rules--;
1883
1884             /* Check if can prune the tree. */
1885             while (!node->n_rules) {
1886                 struct trie_node *next,
1887                     *edge0 = ovsrcu_get_protected(struct trie_node *,
1888                                                   &node->edges[0]),
1889                     *edge1 = ovsrcu_get_protected(struct trie_node *,
1890                                                   &node->edges[1]);
1891
1892                 if (edge0 && edge1) {
1893                     break; /* A branching point, cannot prune. */
1894                 }
1895
1896                 /* Else have at most one child node, remove this node. */
1897                 next = edge0 ? edge0 : edge1;
1898
1899                 if (next) {
1900                     if (node->n_bits + next->n_bits > TRIE_PREFIX_BITS) {
1901                         break;   /* Cannot combine. */
1902                     }
1903                     next = trie_node_rcu_realloc(next); /* Modify. */
1904
1905                     /* Combine node with next. */
1906                     next->prefix = node->prefix | next->prefix >> node->n_bits;
1907                     next->n_bits += node->n_bits;
1908                 }
1909                 /* Update the parent's edge. */
1910                 ovsrcu_set(edges[depth], next); /* Publish changes. */
1911                 trie_node_destroy(node);
1912
1913                 if (next || !depth) {
1914                     /* Branch not pruned or at root, nothing more to do. */
1915                     break;
1916                 }
1917                 node = ovsrcu_get_protected(struct trie_node *,
1918                                             edges[--depth]);
1919             }
1920             return;
1921         }
1922     }
1923     /* Cannot go deeper. This should never happen, since only rules
1924      * that actually exist in the classifier are ever removed. */
1925     VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");
1926 }