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