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