miniflow: Use 64-bit data.
[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 const struct cls_rule *
821 classifier_lookup(const struct classifier *cls, const struct flow *flow,
822                   struct flow_wildcards *wc)
823 {
824     const struct cls_partition *partition;
825     tag_type tags;
826     int best_priority = INT_MIN;
827     const struct cls_match *best;
828     struct trie_ctx trie_ctx[CLS_MAX_TRIES];
829     struct cls_subtable *subtable;
830
831     /* Synchronize for cls->n_tries and subtable->trie_plen.  They can change
832      * when table configuration changes, which happens typically only on
833      * startup. */
834     atomic_thread_fence(memory_order_acquire);
835
836     /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
837      * then 'flow' cannot possibly match in 'subtable':
838      *
839      *     - If flow->metadata maps to a given 'partition', then we can use
840      *       'tags' for 'partition->tags'.
841      *
842      *     - If flow->metadata has no partition, then no rule in 'cls' has an
843      *       exact-match for flow->metadata.  That means that we don't need to
844      *       search any subtable that includes flow->metadata in its mask.
845      *
846      * In either case, we always need to search any cls_subtables that do not
847      * include flow->metadata in its mask.  One way to do that would be to
848      * check the "cls_subtable"s explicitly for that, but that would require an
849      * extra branch per subtable.  Instead, we mark such a cls_subtable's
850      * 'tags' as TAG_ALL and make sure that 'tags' is never empty.  This means
851      * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
852      * need a special case.
853      */
854     partition = (cmap_is_empty(&cls->partitions)
855                  ? NULL
856                  : find_partition(cls, flow->metadata,
857                                   hash_metadata(flow->metadata)));
858     tags = partition ? partition->tags : TAG_ARBITRARY;
859
860     /* Initialize trie contexts for find_match_wc(). */
861     for (int i = 0; i < cls->n_tries; i++) {
862         trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
863     }
864
865     best = NULL;
866     PVECTOR_FOR_EACH_PRIORITY(subtable, best_priority, 2,
867                               sizeof(struct cls_subtable), &cls->subtables) {
868         const struct cls_match *rule;
869
870         if (!tag_intersects(tags, subtable->tag)) {
871             continue;
872         }
873
874         rule = find_match_wc(subtable, flow, trie_ctx, cls->n_tries, wc);
875         if (rule && rule->priority > best_priority) {
876             best_priority = rule->priority;
877             best = rule;
878         }
879     }
880
881     return best ? best->cls_rule : NULL;
882 }
883
884 /* Finds and returns a rule in 'cls' with exactly the same priority and
885  * matching criteria as 'target'.  Returns a null pointer if 'cls' doesn't
886  * contain an exact match. */
887 const struct cls_rule *
888 classifier_find_rule_exactly(const struct classifier *cls,
889                              const struct cls_rule *target)
890 {
891     const struct cls_match *head, *rule;
892     const struct cls_subtable *subtable;
893
894     subtable = find_subtable(cls, &target->match.mask);
895     if (!subtable) {
896         return NULL;
897     }
898
899     head = find_equal(subtable, &target->match.flow,
900                       miniflow_hash_in_minimask(&target->match.flow,
901                                                 &target->match.mask, 0));
902     if (!head) {
903         return NULL;
904     }
905     FOR_EACH_RULE_IN_LIST (rule, head) {
906         if (target->priority >= rule->priority) {
907             return target->priority == rule->priority ? rule->cls_rule : NULL;
908         }
909     }
910     return NULL;
911 }
912
913 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
914  * same matching criteria as 'target'.  Returns a null pointer if 'cls' doesn't
915  * contain an exact match. */
916 const struct cls_rule *
917 classifier_find_match_exactly(const struct classifier *cls,
918                               const struct match *target, int priority)
919 {
920     const struct cls_rule *retval;
921     struct cls_rule cr;
922
923     cls_rule_init(&cr, target, priority);
924     retval = classifier_find_rule_exactly(cls, &cr);
925     cls_rule_destroy(&cr);
926
927     return retval;
928 }
929
930 /* Checks if 'target' would overlap any other rule in 'cls'.  Two rules are
931  * considered to overlap if both rules have the same priority and a packet
932  * could match both.
933  *
934  * A trivial example of overlapping rules is two rules matching disjoint sets
935  * of fields. E.g., if one rule matches only on port number, while another only
936  * on dl_type, any packet from that specific port and with that specific
937  * dl_type could match both, if the rules also have the same priority. */
938 bool
939 classifier_rule_overlaps(const struct classifier *cls,
940                          const struct cls_rule *target)
941 {
942     struct cls_subtable *subtable;
943
944     /* Iterate subtables in the descending max priority order. */
945     PVECTOR_FOR_EACH_PRIORITY (subtable, target->priority - 1, 2,
946                                sizeof(struct cls_subtable), &cls->subtables) {
947         uint64_t storage[FLOW_U64S];
948         struct minimask mask;
949         const struct cls_rule *rule;
950
951         minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
952
953         RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
954             if (rule->priority == target->priority
955                 && miniflow_equal_in_minimask(&target->match.flow,
956                                               &rule->match.flow, &mask)) {
957                 return true;
958             }
959         }
960     }
961     return false;
962 }
963
964 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
965  * specific than 'criteria'.  That is, 'rule' matches 'criteria' and this
966  * function returns true if, for every field:
967  *
968  *   - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
969  *     field, or
970  *
971  *   - 'criteria' wildcards the field,
972  *
973  * Conversely, 'rule' does not match 'criteria' and this function returns false
974  * if, for at least one field:
975  *
976  *   - 'criteria' and 'rule' specify different values for the field, or
977  *
978  *   - 'criteria' specifies a value for the field but 'rule' wildcards it.
979  *
980  * Equivalently, the truth table for whether a field matches is:
981  *
982  *                                     rule
983  *
984  *                   c         wildcard    exact
985  *                   r        +---------+---------+
986  *                   i   wild |   yes   |   yes   |
987  *                   t   card |         |         |
988  *                   e        +---------+---------+
989  *                   r  exact |    no   |if values|
990  *                   i        |         |are equal|
991  *                   a        +---------+---------+
992  *
993  * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
994  * commands and by OpenFlow 1.0 aggregate and flow stats.
995  *
996  * Ignores rule->priority. */
997 bool
998 cls_rule_is_loose_match(const struct cls_rule *rule,
999                         const struct minimatch *criteria)
1000 {
1001     return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
1002             && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
1003                                           &criteria->mask));
1004 }
1005 \f
1006 /* Iteration. */
1007
1008 static bool
1009 rule_matches(const struct cls_rule *rule, const struct cls_rule *target)
1010 {
1011     return (!target
1012             || miniflow_equal_in_minimask(&rule->match.flow,
1013                                           &target->match.flow,
1014                                           &target->match.mask));
1015 }
1016
1017 static const struct cls_rule *
1018 search_subtable(const struct cls_subtable *subtable,
1019                 struct cls_cursor *cursor)
1020 {
1021     if (!cursor->target
1022         || !minimask_has_extra(&subtable->mask, &cursor->target->match.mask)) {
1023         const struct cls_rule *rule;
1024
1025         RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
1026             if (rule_matches(rule, cursor->target)) {
1027                 return rule;
1028             }
1029         }
1030     }
1031     return NULL;
1032 }
1033
1034 /* Initializes 'cursor' for iterating through rules in 'cls', and returns the
1035  * first matching cls_rule via '*pnode', or NULL if there are no matches.
1036  *
1037  *     - If 'target' is null, the cursor will visit every rule in 'cls'.
1038  *
1039  *     - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1040  *       such that cls_rule_is_loose_match(rule, target) returns true.
1041  *
1042  * Ignores target->priority. */
1043 struct cls_cursor cls_cursor_start(const struct classifier *cls,
1044                                    const struct cls_rule *target)
1045 {
1046     struct cls_cursor cursor;
1047     struct cls_subtable *subtable;
1048
1049     cursor.cls = cls;
1050     cursor.target = target && !cls_rule_is_catchall(target) ? target : NULL;
1051     cursor.rule = NULL;
1052
1053     /* Find first rule. */
1054     PVECTOR_CURSOR_FOR_EACH (subtable, &cursor.subtables,
1055                              &cursor.cls->subtables) {
1056         const struct cls_rule *rule = search_subtable(subtable, &cursor);
1057
1058         if (rule) {
1059             cursor.subtable = subtable;
1060             cursor.rule = rule;
1061             break;
1062         }
1063     }
1064
1065     return cursor;
1066 }
1067
1068 static const struct cls_rule *
1069 cls_cursor_next(struct cls_cursor *cursor)
1070 {
1071     const struct cls_rule *rule;
1072     const struct cls_subtable *subtable;
1073
1074     rule = cursor->rule;
1075     subtable = cursor->subtable;
1076     RCULIST_FOR_EACH_CONTINUE (rule, node, &subtable->rules_list) {
1077         if (rule_matches(rule, cursor->target)) {
1078             return rule;
1079         }
1080     }
1081
1082     PVECTOR_CURSOR_FOR_EACH_CONTINUE (subtable, &cursor->subtables) {
1083         rule = search_subtable(subtable, cursor);
1084         if (rule) {
1085             cursor->subtable = subtable;
1086             return rule;
1087         }
1088     }
1089
1090     return NULL;
1091 }
1092
1093 /* Sets 'cursor->rule' to the next matching cls_rule in 'cursor''s iteration,
1094  * or to null if all matching rules have been visited. */
1095 void
1096 cls_cursor_advance(struct cls_cursor *cursor)
1097 {
1098     cursor->rule = cls_cursor_next(cursor);
1099 }
1100 \f
1101 static struct cls_subtable *
1102 find_subtable(const struct classifier *cls, const struct minimask *mask)
1103 {
1104     struct cls_subtable *subtable;
1105
1106     CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, minimask_hash(mask, 0),
1107                              &cls->subtables_map) {
1108         if (minimask_equal(mask, &subtable->mask)) {
1109             return subtable;
1110         }
1111     }
1112     return NULL;
1113 }
1114
1115 /* The new subtable will be visible to the readers only after this. */
1116 static struct cls_subtable *
1117 insert_subtable(struct classifier *cls, const struct minimask *mask)
1118 {
1119     uint32_t hash = minimask_hash(mask, 0);
1120     struct cls_subtable *subtable;
1121     int i, index = 0;
1122     struct flow_wildcards old, new;
1123     uint8_t prev;
1124     int count = count_1bits(mask->masks.map);
1125
1126     subtable = xzalloc(sizeof *subtable - sizeof mask->masks.inline_values
1127                        + MINIFLOW_VALUES_SIZE(count));
1128     cmap_init(&subtable->rules);
1129     miniflow_clone_inline(CONST_CAST(struct miniflow *, &subtable->mask.masks),
1130                           &mask->masks, count);
1131
1132     /* Init indices for segmented lookup, if any. */
1133     flow_wildcards_init_catchall(&new);
1134     old = new;
1135     prev = 0;
1136     for (i = 0; i < cls->n_flow_segments; i++) {
1137         flow_wildcards_fold_minimask_range(&new, mask, prev,
1138                                            cls->flow_segments[i]);
1139         /* Add an index if it adds mask bits. */
1140         if (!flow_wildcards_equal(&new, &old)) {
1141             cmap_init(&subtable->indices[index]);
1142             *CONST_CAST(uint8_t *, &subtable->index_ofs[index])
1143                 = cls->flow_segments[i];
1144             index++;
1145             old = new;
1146         }
1147         prev = cls->flow_segments[i];
1148     }
1149     /* Check if the rest of the subtable's mask adds any bits,
1150      * and remove the last index if it doesn't. */
1151     if (index > 0) {
1152         flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U64S);
1153         if (flow_wildcards_equal(&new, &old)) {
1154             --index;
1155             *CONST_CAST(uint8_t *, &subtable->index_ofs[index]) = 0;
1156             cmap_destroy(&subtable->indices[index]);
1157         }
1158     }
1159     *CONST_CAST(uint8_t *, &subtable->n_indices) = index;
1160
1161     *CONST_CAST(tag_type *, &subtable->tag) =
1162         (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1163          ? tag_create_deterministic(hash)
1164          : TAG_ALL);
1165
1166     for (i = 0; i < cls->n_tries; i++) {
1167         subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1168                                                          cls->tries[i].field);
1169     }
1170
1171     /* Ports trie. */
1172     ovsrcu_set_hidden(&subtable->ports_trie, NULL);
1173     *CONST_CAST(int *, &subtable->ports_mask_len)
1174         = 32 - ctz32(ntohl(MINIFLOW_GET_BE32(&mask->masks, tp_src)));
1175
1176     /* List of rules. */
1177     rculist_init(&subtable->rules_list);
1178
1179     cmap_insert(&cls->subtables_map, &subtable->cmap_node, hash);
1180
1181     return subtable;
1182 }
1183
1184 /* RCU readers may still access the subtable before it is actually freed. */
1185 static void
1186 destroy_subtable(struct classifier *cls, struct cls_subtable *subtable)
1187 {
1188     int i;
1189
1190     pvector_remove(&cls->subtables, subtable);
1191     cmap_remove(&cls->subtables_map, &subtable->cmap_node,
1192                 minimask_hash(&subtable->mask, 0));
1193
1194     ovs_assert(ovsrcu_get_protected(struct trie_node *, &subtable->ports_trie)
1195                == NULL);
1196     ovs_assert(cmap_is_empty(&subtable->rules));
1197     ovs_assert(rculist_is_empty(&subtable->rules_list));
1198
1199     for (i = 0; i < subtable->n_indices; i++) {
1200         cmap_destroy(&subtable->indices[i]);
1201     }
1202     cmap_destroy(&subtable->rules);
1203     ovsrcu_postpone(free, subtable);
1204 }
1205
1206 struct range {
1207     uint8_t start;
1208     uint8_t end;
1209 };
1210
1211 static unsigned int be_get_bit_at(const ovs_be32 value[], unsigned int ofs);
1212
1213 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1214  * lookup results. */
1215 static inline bool
1216 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1217             const unsigned int field_plen[CLS_MAX_TRIES],
1218             const struct range ofs, const struct flow *flow,
1219             struct flow_wildcards *wc)
1220 {
1221     int j;
1222
1223     /* Check if we could avoid fully unwildcarding the next level of
1224      * fields using the prefix tries.  The trie checks are done only as
1225      * needed to avoid folding in additional bits to the wildcards mask. */
1226     for (j = 0; j < n_tries; j++) {
1227         /* Is the trie field relevant for this subtable? */
1228         if (field_plen[j]) {
1229             struct trie_ctx *ctx = &trie_ctx[j];
1230             uint8_t be32ofs = ctx->be32ofs;
1231             uint8_t be64ofs = be32ofs / 2;
1232
1233             /* Is the trie field within the current range of fields? */
1234             if (be64ofs >= ofs.start && be64ofs < ofs.end) {
1235                 /* On-demand trie lookup. */
1236                 if (!ctx->lookup_done) {
1237                     memset(&ctx->match_plens, 0, sizeof ctx->match_plens);
1238                     ctx->maskbits = trie_lookup(ctx->trie, flow,
1239                                                 &ctx->match_plens);
1240                     ctx->lookup_done = true;
1241                 }
1242                 /* Possible to skip the rest of the subtable if subtable's
1243                  * prefix on the field is not included in the lookup result. */
1244                 if (!be_get_bit_at(&ctx->match_plens.be32, field_plen[j] - 1)) {
1245                     /* We want the trie lookup to never result in unwildcarding
1246                      * any bits that would not be unwildcarded otherwise.
1247                      * Since the trie is shared by the whole classifier, it is
1248                      * possible that the 'maskbits' contain bits that are
1249                      * irrelevant for the partition relevant for the current
1250                      * packet.  Hence the checks below. */
1251
1252                     /* Check that the trie result will not unwildcard more bits
1253                      * than this subtable would otherwise. */
1254                     if (ctx->maskbits <= field_plen[j]) {
1255                         /* Unwildcard the bits and skip the rest. */
1256                         mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1257                         /* Note: Prerequisite already unwildcarded, as the only
1258                          * prerequisite of the supported trie lookup fields is
1259                          * the ethertype, which is always unwildcarded. */
1260                         return true;
1261                     }
1262                     /* Can skip if the field is already unwildcarded. */
1263                     if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1264                         return true;
1265                     }
1266                 }
1267             }
1268         }
1269     }
1270     return false;
1271 }
1272
1273 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1274  * for which 'flow', for which 'mask' has a bit set, specifies a particular
1275  * value has the correct value in 'target'.
1276  *
1277  * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
1278  * target, mask) but this is faster because of the invariant that
1279  * flow->map and mask->masks.map are the same, and that this version
1280  * takes the 'wc'. */
1281 static inline bool
1282 miniflow_and_mask_matches_flow(const struct miniflow *flow,
1283                                const struct minimask *mask,
1284                                const struct flow *target)
1285 {
1286     const uint64_t *flowp = miniflow_get_values(flow);
1287     const uint64_t *maskp = miniflow_get_values(&mask->masks);
1288     int idx;
1289
1290     MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1291         uint64_t diff = (*flowp++ ^ flow_u64_value(target, idx)) & *maskp++;
1292
1293         if (diff) {
1294             return false;
1295         }
1296     }
1297
1298     return true;
1299 }
1300
1301 static inline const struct cls_match *
1302 find_match(const struct cls_subtable *subtable, const struct flow *flow,
1303            uint32_t hash)
1304 {
1305     const struct cls_match *rule;
1306
1307     CMAP_FOR_EACH_WITH_HASH (rule, cmap_node, hash, &subtable->rules) {
1308         if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
1309                                            flow)) {
1310             return rule;
1311         }
1312     }
1313
1314     return NULL;
1315 }
1316
1317 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1318  * for which 'flow', for which 'mask' has a bit set, specifies a particular
1319  * value has the correct value in 'target'.
1320  *
1321  * This function is equivalent to miniflow_and_mask_matches_flow() but this
1322  * version fills in the mask bits in 'wc'. */
1323 static inline bool
1324 miniflow_and_mask_matches_flow_wc(const struct miniflow *flow,
1325                                   const struct minimask *mask,
1326                                   const struct flow *target,
1327                                   struct flow_wildcards *wc)
1328 {
1329     const uint64_t *flowp = miniflow_get_values(flow);
1330     const uint64_t *maskp = miniflow_get_values(&mask->masks);
1331     int idx;
1332
1333     MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1334         uint64_t mask = *maskp++;
1335         uint64_t diff = (*flowp++ ^ flow_u64_value(target, idx)) & mask;
1336
1337         if (diff) {
1338             /* Only unwildcard if none of the differing bits is already
1339              * exact-matched. */
1340             if (!(flow_u64_value(&wc->masks, idx) & diff)) {
1341                 /* Keep one bit of the difference.  The selected bit may be
1342                  * different in big-endian v.s. little-endian systems. */
1343                 *flow_u64_lvalue(&wc->masks, idx) |= rightmost_1bit(diff);
1344             }
1345             return false;
1346         }
1347         /* Fill in the bits that were looked at. */
1348         *flow_u64_lvalue(&wc->masks, idx) |= mask;
1349     }
1350
1351     return true;
1352 }
1353
1354 /* Unwildcard the fields looked up so far, if any. */
1355 static void
1356 fill_range_wc(const struct cls_subtable *subtable, struct flow_wildcards *wc,
1357               uint8_t to)
1358 {
1359     if (to) {
1360         flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, to);
1361     }
1362 }
1363
1364 static const struct cls_match *
1365 find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
1366               struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1367               struct flow_wildcards *wc)
1368 {
1369     uint32_t basis = 0, hash;
1370     const struct cls_match *rule = NULL;
1371     int i;
1372     struct range ofs;
1373
1374     if (OVS_UNLIKELY(!wc)) {
1375         return find_match(subtable, flow,
1376                           flow_hash_in_minimask(flow, &subtable->mask, 0));
1377     }
1378
1379     ofs.start = 0;
1380     /* Try to finish early by checking fields in segments. */
1381     for (i = 0; i < subtable->n_indices; i++) {
1382         const struct cmap_node *inode;
1383
1384         ofs.end = subtable->index_ofs[i];
1385
1386         if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1387                         wc)) {
1388             /* 'wc' bits for the trie field set, now unwildcard the preceding
1389              * bits used so far. */
1390             fill_range_wc(subtable, wc, ofs.start);
1391             return NULL;
1392         }
1393         hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1394                                            ofs.end, &basis);
1395         inode = cmap_find(&subtable->indices[i], hash);
1396         if (!inode) {
1397             /* No match, can stop immediately, but must fold in the bits
1398              * used in lookup so far. */
1399             fill_range_wc(subtable, wc, ofs.end);
1400             return NULL;
1401         }
1402
1403         /* If we have narrowed down to a single rule already, check whether
1404          * that rule matches.  Either way, we're done.
1405          *
1406          * (Rare) hash collisions may cause us to miss the opportunity for this
1407          * optimization. */
1408         if (!cmap_node_next(inode)) {
1409             ASSIGN_CONTAINER(rule, inode - i, index_nodes);
1410             if (miniflow_and_mask_matches_flow_wc(&rule->flow, &subtable->mask,
1411                                                   flow, wc)) {
1412                 return rule;
1413             }
1414             return NULL;
1415         }
1416         ofs.start = ofs.end;
1417     }
1418     ofs.end = FLOW_U64S;
1419     /* Trie check for the final range. */
1420     if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1421         fill_range_wc(subtable, wc, ofs.start);
1422         return NULL;
1423     }
1424     hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1425                                        ofs.end, &basis);
1426     rule = find_match(subtable, flow, hash);
1427     if (!rule && subtable->ports_mask_len) {
1428         /* Ports are always part of the final range, if any.
1429          * No match was found for the ports.  Use the ports trie to figure out
1430          * which ports bits to unwildcard. */
1431         unsigned int mbits;
1432         ovs_be32 value, plens, mask;
1433
1434         mask = MINIFLOW_GET_BE32(&subtable->mask.masks, tp_src);
1435         value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
1436         mbits = trie_lookup_value(&subtable->ports_trie, &value, &plens, 32);
1437
1438         ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
1439             mask & be32_prefix_mask(mbits);
1440
1441         /* Unwildcard all bits in the mask upto the ports, as they were used
1442          * to determine there is no match. */
1443         fill_range_wc(subtable, wc, TP_PORTS_OFS64);
1444         return NULL;
1445     }
1446
1447     /* Must unwildcard all the fields, as they were looked at. */
1448     flow_wildcards_fold_minimask(wc, &subtable->mask);
1449     return rule;
1450 }
1451
1452 static struct cls_match *
1453 find_equal(const struct cls_subtable *subtable, const struct miniflow *flow,
1454            uint32_t hash)
1455 {
1456     struct cls_match *head;
1457
1458     CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1459         if (miniflow_equal(&head->flow, flow)) {
1460             return head;
1461         }
1462     }
1463     return NULL;
1464 }
1465 \f
1466 /* A longest-prefix match tree. */
1467
1468 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1469  * Prefixes are in the network byte order, and the offset 0 corresponds to
1470  * the most significant bit of the first byte.  The offset can be read as
1471  * "how many bits to skip from the start of the prefix starting at 'pr'". */
1472 static uint32_t
1473 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1474 {
1475     uint32_t prefix;
1476
1477     pr += ofs / 32; /* Where to start. */
1478     ofs %= 32;      /* How many bits to skip at 'pr'. */
1479
1480     prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1481     if (plen > 32 - ofs) {      /* Need more than we have already? */
1482         prefix |= ntohl(*++pr) >> (32 - ofs);
1483     }
1484     /* Return with possible unwanted bits at the end. */
1485     return prefix;
1486 }
1487
1488 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1489  * offset 'ofs'.  Prefixes are in the network byte order, and the offset 0
1490  * corresponds to the most significant bit of the first byte.  The offset can
1491  * be read as "how many bits to skip from the start of the prefix starting at
1492  * 'pr'". */
1493 static uint32_t
1494 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1495 {
1496     if (!plen) {
1497         return 0;
1498     }
1499     if (plen > TRIE_PREFIX_BITS) {
1500         plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1501     }
1502     /* Return with unwanted bits cleared. */
1503     return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1504 }
1505
1506 /* Return the number of equal bits in 'n_bits' of 'prefix's MSBs and a 'value'
1507  * starting at "MSB 0"-based offset 'ofs'. */
1508 static unsigned int
1509 prefix_equal_bits(uint32_t prefix, unsigned int n_bits, const ovs_be32 value[],
1510                   unsigned int ofs)
1511 {
1512     uint64_t diff = prefix ^ raw_get_prefix(value, ofs, n_bits);
1513     /* Set the bit after the relevant bits to limit the result. */
1514     return raw_clz64(diff << 32 | UINT64_C(1) << (63 - n_bits));
1515 }
1516
1517 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1518  * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1519 static unsigned int
1520 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1521                        unsigned int ofs, unsigned int plen)
1522 {
1523     return prefix_equal_bits(node->prefix, MIN(node->n_bits, plen - ofs),
1524                              prefix, ofs);
1525 }
1526
1527 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int.  'ofs' can
1528  * be greater than 31. */
1529 static unsigned int
1530 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1531 {
1532     return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1533 }
1534
1535 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int.  'ofs' must
1536  * be between 0 and 31, inclusive. */
1537 static unsigned int
1538 get_bit_at(const uint32_t prefix, unsigned int ofs)
1539 {
1540     return (prefix >> (31 - ofs)) & 1u;
1541 }
1542
1543 /* Create new branch. */
1544 static struct trie_node *
1545 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1546                    unsigned int n_rules)
1547 {
1548     struct trie_node *node = xmalloc(sizeof *node);
1549
1550     node->prefix = trie_get_prefix(prefix, ofs, plen);
1551
1552     if (plen <= TRIE_PREFIX_BITS) {
1553         node->n_bits = plen;
1554         ovsrcu_set_hidden(&node->edges[0], NULL);
1555         ovsrcu_set_hidden(&node->edges[1], NULL);
1556         node->n_rules = n_rules;
1557     } else { /* Need intermediate nodes. */
1558         struct trie_node *subnode = trie_branch_create(prefix,
1559                                                        ofs + TRIE_PREFIX_BITS,
1560                                                        plen - TRIE_PREFIX_BITS,
1561                                                        n_rules);
1562         int bit = get_bit_at(subnode->prefix, 0);
1563         node->n_bits = TRIE_PREFIX_BITS;
1564         ovsrcu_set_hidden(&node->edges[bit], subnode);
1565         ovsrcu_set_hidden(&node->edges[!bit], NULL);
1566         node->n_rules = 0;
1567     }
1568     return node;
1569 }
1570
1571 static void
1572 trie_node_destroy(const struct trie_node *node)
1573 {
1574     ovsrcu_postpone(free, CONST_CAST(struct trie_node *, node));
1575 }
1576
1577 /* Copy a trie node for modification and postpone delete the old one. */
1578 static struct trie_node *
1579 trie_node_rcu_realloc(const struct trie_node *node)
1580 {
1581     struct trie_node *new_node = xmalloc(sizeof *node);
1582
1583     *new_node = *node;
1584     trie_node_destroy(node);
1585
1586     return new_node;
1587 }
1588
1589 static void
1590 trie_destroy(rcu_trie_ptr *trie)
1591 {
1592     struct trie_node *node = ovsrcu_get_protected(struct trie_node *, trie);
1593
1594     if (node) {
1595         ovsrcu_set_hidden(trie, NULL);
1596         trie_destroy(&node->edges[0]);
1597         trie_destroy(&node->edges[1]);
1598         trie_node_destroy(node);
1599     }
1600 }
1601
1602 static bool
1603 trie_is_leaf(const struct trie_node *trie)
1604 {
1605     /* No children? */
1606     return !ovsrcu_get(struct trie_node *, &trie->edges[0])
1607         && !ovsrcu_get(struct trie_node *, &trie->edges[1]);
1608 }
1609
1610 static void
1611 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1612                      unsigned int n_bits)
1613 {
1614     ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1615     unsigned int i;
1616
1617     for (i = 0; i < n_bits / 32; i++) {
1618         mask[i] = OVS_BE32_MAX;
1619     }
1620     if (n_bits % 32) {
1621         mask[i] |= htonl(~0u << (32 - n_bits % 32));
1622     }
1623 }
1624
1625 static bool
1626 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
1627                      unsigned int n_bits)
1628 {
1629     ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1630     unsigned int i;
1631     ovs_be32 zeroes = 0;
1632
1633     for (i = 0; i < n_bits / 32; i++) {
1634         zeroes |= ~mask[i];
1635     }
1636     if (n_bits % 32) {
1637         zeroes |= ~mask[i] & htonl(~0u << (32 - n_bits % 32));
1638     }
1639
1640     return !zeroes; /* All 'n_bits' bits set. */
1641 }
1642
1643 static rcu_trie_ptr *
1644 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
1645                unsigned int ofs)
1646 {
1647     return node->edges + be_get_bit_at(value, ofs);
1648 }
1649
1650 static const struct trie_node *
1651 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
1652                unsigned int ofs)
1653 {
1654     return ovsrcu_get(struct trie_node *,
1655                       &node->edges[be_get_bit_at(value, ofs)]);
1656 }
1657
1658 /* Set the bit at ("MSB 0"-based) offset 'ofs'.  'ofs' can be greater than 31.
1659  */
1660 static void
1661 be_set_bit_at(ovs_be32 value[], unsigned int ofs)
1662 {
1663     ((uint8_t *)value)[ofs / 8] |= 1u << (7 - ofs % 8);
1664 }
1665
1666 /* Returns the number of bits in the prefix mask necessary to determine a
1667  * mismatch, in case there are longer prefixes in the tree below the one that
1668  * matched.
1669  * '*plens' will have a bit set for each prefix length that may have matching
1670  * rules.  The caller is responsible for clearing the '*plens' prior to
1671  * calling this.
1672  */
1673 static unsigned int
1674 trie_lookup_value(const rcu_trie_ptr *trie, const ovs_be32 value[],
1675                   ovs_be32 plens[], unsigned int n_bits)
1676 {
1677     const struct trie_node *prev = NULL;
1678     const struct trie_node *node = ovsrcu_get(struct trie_node *, trie);
1679     unsigned int match_len = 0; /* Number of matching bits. */
1680
1681     for (; node; prev = node, node = trie_next_node(node, value, match_len)) {
1682         unsigned int eqbits;
1683         /* Check if this edge can be followed. */
1684         eqbits = prefix_equal_bits(node->prefix, node->n_bits, value,
1685                                    match_len);
1686         match_len += eqbits;
1687         if (eqbits < node->n_bits) { /* Mismatch, nothing more to be found. */
1688             /* Bit at offset 'match_len' differed. */
1689             return match_len + 1; /* Includes the first mismatching bit. */
1690         }
1691         /* Full match, check if rules exist at this prefix length. */
1692         if (node->n_rules > 0) {
1693             be_set_bit_at(plens, match_len - 1);
1694         }
1695         if (match_len >= n_bits) {
1696             return n_bits; /* Full prefix. */
1697         }
1698     }
1699     /* node == NULL.  Full match so far, but we tried to follow an
1700      * non-existing branch.  Need to exclude the other branch if it exists
1701      * (it does not if we were called on an empty trie or 'prev' is a leaf
1702      * node). */
1703     return !prev || trie_is_leaf(prev) ? match_len : match_len + 1;
1704 }
1705
1706 static unsigned int
1707 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
1708             union mf_value *plens)
1709 {
1710     const struct mf_field *mf = trie->field;
1711
1712     /* Check that current flow matches the prerequisites for the trie
1713      * field.  Some match fields are used for multiple purposes, so we
1714      * must check that the trie is relevant for this flow. */
1715     if (mf_are_prereqs_ok(mf, flow)) {
1716         return trie_lookup_value(&trie->root,
1717                                  &((ovs_be32 *)flow)[mf->flow_be32ofs],
1718                                  &plens->be32, mf->n_bits);
1719     }
1720     memset(plens, 0xff, sizeof *plens); /* All prefixes, no skipping. */
1721     return 0; /* Value not used in this case. */
1722 }
1723
1724 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
1725  * Returns the u32 offset to the miniflow data in '*miniflow_index', if
1726  * 'miniflow_index' is not NULL. */
1727 static unsigned int
1728 minimask_get_prefix_len(const struct minimask *minimask,
1729                         const struct mf_field *mf)
1730 {
1731     unsigned int n_bits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
1732     uint8_t be32_ofs = mf->flow_be32ofs;
1733     uint8_t be32_end = be32_ofs + mf->n_bytes / 4;
1734
1735     for (; be32_ofs < be32_end; ++be32_ofs) {
1736         uint32_t mask = ntohl(minimask_get_be32(minimask, be32_ofs));
1737
1738         /* Validate mask, count the mask length. */
1739         if (mask_tz) {
1740             if (mask) {
1741                 return 0; /* No bits allowed after mask ended. */
1742             }
1743         } else {
1744             if (~mask & (~mask + 1)) {
1745                 return 0; /* Mask not contiguous. */
1746             }
1747             mask_tz = ctz32(mask);
1748             n_bits += 32 - mask_tz;
1749         }
1750     }
1751
1752     return n_bits;
1753 }
1754
1755 /*
1756  * This is called only when mask prefix is known to be CIDR and non-zero.
1757  * Relies on the fact that the flow and mask have the same map, and since
1758  * the mask is CIDR, the storage for the flow field exists even if it
1759  * happened to be zeros.
1760  */
1761 static const ovs_be32 *
1762 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
1763 {
1764     return (OVS_FORCE const ovs_be32 *)
1765         (miniflow_get_values(&match->flow)
1766          + count_1bits(match->flow.map &
1767                        ((UINT64_C(1) << mf->flow_be32ofs / 2) - 1)))
1768         + (mf->flow_be32ofs & 1);
1769 }
1770
1771 /* Insert rule in to the prefix tree.
1772  * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1773  * in 'rule'. */
1774 static void
1775 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1776 {
1777     trie_insert_prefix(&trie->root,
1778                        minimatch_get_prefix(&rule->match, trie->field), mlen);
1779 }
1780
1781 static void
1782 trie_insert_prefix(rcu_trie_ptr *edge, const ovs_be32 *prefix, int mlen)
1783 {
1784     struct trie_node *node;
1785     int ofs = 0;
1786
1787     /* Walk the tree. */
1788     for (; (node = ovsrcu_get_protected(struct trie_node *, edge));
1789          edge = trie_next_edge(node, prefix, ofs)) {
1790         unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1791         ofs += eqbits;
1792         if (eqbits < node->n_bits) {
1793             /* Mismatch, new node needs to be inserted above. */
1794             int old_branch = get_bit_at(node->prefix, eqbits);
1795             struct trie_node *new_parent;
1796
1797             new_parent = trie_branch_create(prefix, ofs - eqbits, eqbits,
1798                                             ofs == mlen ? 1 : 0);
1799             /* Copy the node to modify it. */
1800             node = trie_node_rcu_realloc(node);
1801             /* Adjust the new node for its new position in the tree. */
1802             node->prefix <<= eqbits;
1803             node->n_bits -= eqbits;
1804             ovsrcu_set_hidden(&new_parent->edges[old_branch], node);
1805
1806             /* Check if need a new branch for the new rule. */
1807             if (ofs < mlen) {
1808                 ovsrcu_set_hidden(&new_parent->edges[!old_branch],
1809                                   trie_branch_create(prefix, ofs, mlen - ofs,
1810                                                      1));
1811             }
1812             ovsrcu_set(edge, new_parent); /* Publish changes. */
1813             return;
1814         }
1815         /* Full match so far. */
1816
1817         if (ofs == mlen) {
1818             /* Full match at the current node, rule needs to be added here. */
1819             node->n_rules++;
1820             return;
1821         }
1822     }
1823     /* Must insert a new tree branch for the new rule. */
1824     ovsrcu_set(edge, trie_branch_create(prefix, ofs, mlen - ofs, 1));
1825 }
1826
1827 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1828  * in 'rule'. */
1829 static void
1830 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1831 {
1832     trie_remove_prefix(&trie->root,
1833                        minimatch_get_prefix(&rule->match, trie->field), mlen);
1834 }
1835
1836 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1837  * in 'rule'. */
1838 static void
1839 trie_remove_prefix(rcu_trie_ptr *root, const ovs_be32 *prefix, int mlen)
1840 {
1841     struct trie_node *node;
1842     rcu_trie_ptr *edges[sizeof(union mf_value) * 8];
1843     int depth = 0, ofs = 0;
1844
1845     /* Walk the tree. */
1846     for (edges[0] = root;
1847          (node = ovsrcu_get_protected(struct trie_node *, edges[depth]));
1848          edges[++depth] = trie_next_edge(node, prefix, ofs)) {
1849         unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1850
1851         if (eqbits < node->n_bits) {
1852             /* Mismatch, nothing to be removed.  This should never happen, as
1853              * only rules in the classifier are ever removed. */
1854             break; /* Log a warning. */
1855         }
1856         /* Full match so far. */
1857         ofs += eqbits;
1858
1859         if (ofs == mlen) {
1860             /* Full prefix match at the current node, remove rule here. */
1861             if (!node->n_rules) {
1862                 break; /* Log a warning. */
1863             }
1864             node->n_rules--;
1865
1866             /* Check if can prune the tree. */
1867             while (!node->n_rules) {
1868                 struct trie_node *next,
1869                     *edge0 = ovsrcu_get_protected(struct trie_node *,
1870                                                   &node->edges[0]),
1871                     *edge1 = ovsrcu_get_protected(struct trie_node *,
1872                                                   &node->edges[1]);
1873
1874                 if (edge0 && edge1) {
1875                     break; /* A branching point, cannot prune. */
1876                 }
1877
1878                 /* Else have at most one child node, remove this node. */
1879                 next = edge0 ? edge0 : edge1;
1880
1881                 if (next) {
1882                     if (node->n_bits + next->n_bits > TRIE_PREFIX_BITS) {
1883                         break;   /* Cannot combine. */
1884                     }
1885                     next = trie_node_rcu_realloc(next); /* Modify. */
1886
1887                     /* Combine node with next. */
1888                     next->prefix = node->prefix | next->prefix >> node->n_bits;
1889                     next->n_bits += node->n_bits;
1890                 }
1891                 /* Update the parent's edge. */
1892                 ovsrcu_set(edges[depth], next); /* Publish changes. */
1893                 trie_node_destroy(node);
1894
1895                 if (next || !depth) {
1896                     /* Branch not pruned or at root, nothing more to do. */
1897                     break;
1898                 }
1899                 node = ovsrcu_get_protected(struct trie_node *,
1900                                             edges[--depth]);
1901             }
1902             return;
1903         }
1904     }
1905     /* Cannot go deeper. This should never happen, since only rules
1906      * that actually exist in the classifier are ever removed. */
1907     VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");
1908 }