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