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