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