2 * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Nicira, Inc.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include "classifier.h"
19 #include "classifier-private.h"
21 #include <netinet/in.h>
22 #include "byte-order.h"
23 #include "dynamic-string.h"
28 #include "openvswitch/vlog.h"
30 VLOG_DEFINE_THIS_MODULE(classifier);
34 /* A collection of "struct cls_conjunction"s currently embedded into a
36 struct cls_conjunction_set {
37 /* Link back to the cls_match.
39 * cls_conjunction_set is mostly used during classifier lookup, and, in
40 * turn, during classifier lookup the most used member of
41 * cls_conjunction_set is the rule's priority, so we cache it here for fast
43 struct cls_match *match;
44 int priority; /* Cached copy of match->priority. */
46 /* Conjunction information.
48 * 'min_n_clauses' allows some optimization during classifier lookup. */
49 unsigned int n; /* Number of elements in 'conj'. */
50 unsigned int min_n_clauses; /* Smallest 'n' among elements of 'conj'. */
51 struct cls_conjunction conj[];
54 /* Ports trie depends on both ports sharing the same ovs_be32. */
55 #define TP_PORTS_OFS32 (offsetof(struct flow, tp_src) / 4)
56 BUILD_ASSERT_DECL(TP_PORTS_OFS32 == offsetof(struct flow, tp_dst) / 4);
57 BUILD_ASSERT_DECL(TP_PORTS_OFS32 % 2 == 0);
58 #define TP_PORTS_OFS64 (TP_PORTS_OFS32 / 2)
61 cls_conjunction_set_size(size_t n)
63 return (sizeof(struct cls_conjunction_set)
64 + n * sizeof(struct cls_conjunction));
67 static struct cls_conjunction_set *
68 cls_conjunction_set_alloc(struct cls_match *match,
69 const struct cls_conjunction conj[], size_t n)
72 size_t min_n_clauses = conj[0].n_clauses;
73 for (size_t i = 1; i < n; i++) {
74 min_n_clauses = MIN(min_n_clauses, conj[i].n_clauses);
77 struct cls_conjunction_set *set = xmalloc(cls_conjunction_set_size(n));
79 set->priority = match->priority;
81 set->min_n_clauses = min_n_clauses;
82 memcpy(set->conj, conj, n * sizeof *conj);
89 static struct cls_match *
90 cls_match_alloc(const struct cls_rule *rule, cls_version_t version,
91 const struct cls_conjunction conj[], size_t n)
93 size_t count = miniflow_n_values(rule->match.flow);
95 struct cls_match *cls_match
96 = xmalloc(sizeof *cls_match + MINIFLOW_VALUES_SIZE(count));
98 ovsrcu_init(&cls_match->next, NULL);
99 *CONST_CAST(const struct cls_rule **, &cls_match->cls_rule) = rule;
100 *CONST_CAST(int *, &cls_match->priority) = rule->priority;
101 *CONST_CAST(cls_version_t *, &cls_match->add_version) = version;
102 atomic_init(&cls_match->remove_version, version); /* Initially
104 miniflow_clone(CONST_CAST(struct miniflow *, &cls_match->flow),
105 rule->match.flow, count);
106 ovsrcu_set_hidden(&cls_match->conj_set,
107 cls_conjunction_set_alloc(cls_match, conj, n));
112 static struct cls_subtable *find_subtable(const struct classifier *cls,
113 const struct minimask *);
114 static struct cls_subtable *insert_subtable(struct classifier *cls,
115 const struct minimask *);
116 static void destroy_subtable(struct classifier *cls, struct cls_subtable *);
118 static const struct cls_match *find_match_wc(const struct cls_subtable *,
119 cls_version_t version,
122 unsigned int n_tries,
123 struct flow_wildcards *);
124 static struct cls_match *find_equal(const struct cls_subtable *,
125 const struct miniflow *, uint32_t hash);
127 /* Return the next visible (lower-priority) rule in the list. Multiple
128 * identical rules with the same priority may exist transitionally, but when
129 * versioning is used at most one of them is ever visible for lookups on any
130 * given 'version'. */
131 static inline const struct cls_match *
132 next_visible_rule_in_list(const struct cls_match *rule, cls_version_t version)
135 rule = cls_match_next(rule);
136 } while (rule && !cls_match_visible_in_version(rule, version));
141 /* Type with maximum supported prefix length. */
143 struct in6_addr ipv6; /* For sizing. */
144 ovs_be32 be32; /* For access. */
147 static unsigned int minimask_get_prefix_len(const struct minimask *,
148 const struct mf_field *);
149 static void trie_init(struct classifier *cls, int trie_idx,
150 const struct mf_field *);
151 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
152 union trie_prefix *plens);
153 static unsigned int trie_lookup_value(const rcu_trie_ptr *,
154 const ovs_be32 value[], ovs_be32 plens[],
155 unsigned int value_bits);
156 static void trie_destroy(rcu_trie_ptr *);
157 static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
158 static void trie_insert_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
160 static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
161 static void trie_remove_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
163 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
164 unsigned int n_bits);
165 static bool mask_prefix_bits_set(const struct flow_wildcards *,
166 uint8_t be32ofs, unsigned int n_bits);
171 cls_rule_init__(struct cls_rule *rule, unsigned int priority)
173 rculist_init(&rule->node);
174 *CONST_CAST(int *, &rule->priority) = priority;
175 rule->cls_match = NULL;
178 /* Initializes 'rule' to match packets specified by 'match' at the given
179 * 'priority'. 'match' must satisfy the invariant described in the comment at
180 * the definition of struct match.
182 * The caller must eventually destroy 'rule' with cls_rule_destroy().
184 * Clients should not use priority INT_MIN. (OpenFlow uses priorities between
185 * 0 and UINT16_MAX, inclusive.) */
187 cls_rule_init(struct cls_rule *rule, const struct match *match, int priority)
189 cls_rule_init__(rule, priority);
190 minimatch_init(CONST_CAST(struct minimatch *, &rule->match), match);
193 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
195 cls_rule_init_from_minimatch(struct cls_rule *rule,
196 const struct minimatch *match, int priority)
198 cls_rule_init__(rule, priority);
199 minimatch_clone(CONST_CAST(struct minimatch *, &rule->match), match);
202 /* Initializes 'dst' as a copy of 'src'.
204 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
206 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
208 cls_rule_init__(dst, src->priority);
209 minimatch_clone(CONST_CAST(struct minimatch *, &dst->match), &src->match);
212 /* Initializes 'dst' with the data in 'src', destroying 'src'.
214 * 'src' must be a cls_rule NOT in a classifier.
216 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
218 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
220 cls_rule_init__(dst, src->priority);
221 minimatch_move(CONST_CAST(struct minimatch *, &dst->match),
222 CONST_CAST(struct minimatch *, &src->match));
225 /* Frees memory referenced by 'rule'. Doesn't free 'rule' itself (it's
226 * normally embedded into a larger structure).
228 * ('rule' must not currently be in a classifier.) */
230 cls_rule_destroy(struct cls_rule *rule)
231 OVS_NO_THREAD_SAFETY_ANALYSIS
233 ovs_assert(!rule->cls_match); /* Must not be in a classifier. */
235 /* Check that the rule has been properly removed from the classifier. */
236 ovs_assert(rule->node.prev == RCULIST_POISON
237 || rculist_is_empty(&rule->node));
238 rculist_poison__(&rule->node); /* Poisons also the next pointer. */
240 minimatch_destroy(CONST_CAST(struct minimatch *, &rule->match));
244 cls_rule_set_conjunctions(struct cls_rule *cr,
245 const struct cls_conjunction *conj, size_t n)
247 struct cls_match *match = cr->cls_match;
248 struct cls_conjunction_set *old
249 = ovsrcu_get_protected(struct cls_conjunction_set *, &match->conj_set);
250 struct cls_conjunction *old_conj = old ? old->conj : NULL;
251 unsigned int old_n = old ? old->n : 0;
253 if (old_n != n || (n && memcmp(old_conj, conj, n * sizeof *conj))) {
255 ovsrcu_postpone(free, old);
257 ovsrcu_set(&match->conj_set,
258 cls_conjunction_set_alloc(match, conj, n));
263 /* Returns true if 'a' and 'b' match the same packets at the same priority,
264 * false if they differ in some way. */
266 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
268 return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
271 /* Appends a string describing 'rule' to 's'. */
273 cls_rule_format(const struct cls_rule *rule, struct ds *s)
275 minimatch_format(&rule->match, s, rule->priority);
278 /* Returns true if 'rule' matches every packet, false otherwise. */
280 cls_rule_is_catchall(const struct cls_rule *rule)
282 return minimask_is_catchall(rule->match.mask);
285 /* Makes 'rule' invisible in 'remove_version'. Once that version is used in
286 * lookups, the caller should remove 'rule' via ovsrcu_postpone().
288 * 'rule' must be in a classifier. */
290 cls_rule_make_invisible_in_version(const struct cls_rule *rule,
291 cls_version_t remove_version)
293 ovs_assert(remove_version >= rule->cls_match->add_version);
295 cls_match_set_remove_version(rule->cls_match, remove_version);
298 /* This undoes the change made by cls_rule_make_invisible_in_version().
300 * 'rule' must be in a classifier. */
302 cls_rule_restore_visibility(const struct cls_rule *rule)
304 cls_match_set_remove_version(rule->cls_match, CLS_NOT_REMOVED_VERSION);
307 /* Return true if 'rule' is visible in 'version'.
309 * 'rule' must be in a classifier. */
311 cls_rule_visible_in_version(const struct cls_rule *rule, cls_version_t version)
313 return cls_match_visible_in_version(rule->cls_match, version);
316 /* Initializes 'cls' as a classifier that initially contains no classification
319 classifier_init(struct classifier *cls, const uint8_t *flow_segments)
322 cmap_init(&cls->subtables_map);
323 pvector_init(&cls->subtables);
324 cmap_init(&cls->partitions);
325 cls->n_flow_segments = 0;
327 while (cls->n_flow_segments < CLS_MAX_INDICES
328 && *flow_segments < FLOW_U64S) {
329 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
333 for (int i = 0; i < CLS_MAX_TRIES; i++) {
334 trie_init(cls, i, NULL);
339 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
340 * caller's responsibility.
341 * May only be called after all the readers have been terminated. */
343 classifier_destroy(struct classifier *cls)
346 struct cls_partition *partition;
347 struct cls_subtable *subtable;
350 for (i = 0; i < cls->n_tries; i++) {
351 trie_destroy(&cls->tries[i].root);
354 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
355 destroy_subtable(cls, subtable);
357 cmap_destroy(&cls->subtables_map);
359 CMAP_FOR_EACH (partition, cmap_node, &cls->partitions) {
360 ovsrcu_postpone(free, partition);
362 cmap_destroy(&cls->partitions);
364 pvector_destroy(&cls->subtables);
368 /* Set the fields for which prefix lookup should be performed. */
370 classifier_set_prefix_fields(struct classifier *cls,
371 const enum mf_field_id *trie_fields,
372 unsigned int n_fields)
374 const struct mf_field * new_fields[CLS_MAX_TRIES];
375 struct mf_bitmap fields = MF_BITMAP_INITIALIZER;
377 bool changed = false;
379 for (i = 0; i < n_fields && n_tries < CLS_MAX_TRIES; i++) {
380 const struct mf_field *field = mf_from_id(trie_fields[i]);
381 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
382 /* Incompatible field. This is the only place where we
383 * enforce these requirements, but the rest of the trie code
384 * depends on the flow_be32ofs to be non-negative and the
385 * field length to be a multiple of 32 bits. */
389 if (bitmap_is_set(fields.bm, trie_fields[i])) {
390 /* Duplicate field, there is no need to build more than
391 * one index for any one field. */
394 bitmap_set1(fields.bm, trie_fields[i]);
396 new_fields[n_tries] = NULL;
397 if (n_tries >= cls->n_tries || field != cls->tries[n_tries].field) {
398 new_fields[n_tries] = field;
404 if (changed || n_tries < cls->n_tries) {
405 struct cls_subtable *subtable;
407 /* Trie configuration needs to change. Disable trie lookups
408 * for the tries that are changing and wait all the current readers
409 * with the old configuration to be done. */
411 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
412 for (i = 0; i < cls->n_tries; i++) {
413 if ((i < n_tries && new_fields[i]) || i >= n_tries) {
414 if (subtable->trie_plen[i]) {
415 subtable->trie_plen[i] = 0;
421 /* Synchronize if any readers were using tries. The readers may
422 * temporarily function without the trie lookup based optimizations. */
424 /* ovsrcu_synchronize() functions as a memory barrier, so it does
425 * not matter that subtable->trie_plen is not atomic. */
426 ovsrcu_synchronize();
429 /* Now set up the tries. */
430 for (i = 0; i < n_tries; i++) {
432 trie_init(cls, i, new_fields[i]);
435 /* Destroy the rest, if any. */
436 for (; i < cls->n_tries; i++) {
437 trie_init(cls, i, NULL);
440 cls->n_tries = n_tries;
444 return false; /* No change. */
448 trie_init(struct classifier *cls, int trie_idx, const struct mf_field *field)
450 struct cls_trie *trie = &cls->tries[trie_idx];
451 struct cls_subtable *subtable;
453 if (trie_idx < cls->n_tries) {
454 trie_destroy(&trie->root);
456 ovsrcu_set_hidden(&trie->root, NULL);
460 /* Add existing rules to the new trie. */
461 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
464 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
466 struct cls_match *head;
468 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
469 trie_insert(trie, head->cls_rule, plen);
472 /* Initialize subtable's prefix length on this field. This will
473 * allow readers to use the trie. */
474 atomic_thread_fence(memory_order_release);
475 subtable->trie_plen[trie_idx] = plen;
479 /* Returns true if 'cls' contains no classification rules, false otherwise.
480 * Checking the cmap requires no locking. */
482 classifier_is_empty(const struct classifier *cls)
484 return cmap_is_empty(&cls->subtables_map);
487 /* Returns the number of rules in 'cls'. */
489 classifier_count(const struct classifier *cls)
491 /* n_rules is an int, so in the presence of concurrent writers this will
492 * return either the old or a new value. */
497 hash_metadata(ovs_be64 metadata)
499 return hash_uint64((OVS_FORCE uint64_t) metadata);
502 static struct cls_partition *
503 find_partition(const struct classifier *cls, ovs_be64 metadata, uint32_t hash)
505 struct cls_partition *partition;
507 CMAP_FOR_EACH_WITH_HASH (partition, cmap_node, hash, &cls->partitions) {
508 if (partition->metadata == metadata) {
516 static struct cls_partition *
517 create_partition(struct classifier *cls, struct cls_subtable *subtable,
520 uint32_t hash = hash_metadata(metadata);
521 struct cls_partition *partition = find_partition(cls, metadata, hash);
523 partition = xmalloc(sizeof *partition);
524 partition->metadata = metadata;
526 tag_tracker_init(&partition->tracker);
527 cmap_insert(&cls->partitions, &partition->cmap_node, hash);
529 tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
533 static inline ovs_be32 minimatch_get_ports(const struct minimatch *match)
535 /* Could optimize to use the same map if needed for fast path. */
536 return MINIFLOW_GET_BE32(match->flow, tp_src)
537 & MINIFLOW_GET_BE32(&match->mask->masks, tp_src);
541 subtable_replace_head_rule(struct classifier *cls OVS_UNUSED,
542 struct cls_subtable *subtable,
543 struct cls_match *head, struct cls_match *new,
544 uint32_t hash, uint32_t ihash[CLS_MAX_INDICES])
546 /* Rule's data is already in the tries. */
548 new->partition = head->partition; /* Steal partition, if any. */
549 head->partition = NULL;
551 for (int i = 0; i < subtable->n_indices; i++) {
552 cmap_replace(&subtable->indices[i], &head->index_nodes[i],
553 &new->index_nodes[i], ihash[i]);
555 cmap_replace(&subtable->rules, &head->cmap_node, &new->cmap_node, hash);
558 /* Inserts 'rule' into 'cls' in 'version'. Until 'rule' is removed from 'cls',
559 * the caller must not modify or free it.
561 * If 'cls' already contains an identical rule (including wildcards, values of
562 * fixed fields, and priority) that is visible in 'version', replaces the old
563 * rule by 'rule' and returns the rule that was replaced. The caller takes
564 * ownership of the returned rule and is thus responsible for destroying it
565 * with cls_rule_destroy(), after RCU grace period has passed (see
566 * ovsrcu_postpone()).
568 * Returns NULL if 'cls' does not contain a rule with an identical key, after
569 * inserting the new rule. In this case, no rules are displaced by the new
570 * rule, even rules that cannot have any effect because the new rule matches a
571 * superset of their flows and has higher priority.
573 const struct cls_rule *
574 classifier_replace(struct classifier *cls, const struct cls_rule *rule,
575 cls_version_t version,
576 const struct cls_conjunction *conjs, size_t n_conjs)
578 struct cls_match *new;
579 struct cls_subtable *subtable;
580 uint32_t ihash[CLS_MAX_INDICES];
581 struct cls_match *head;
582 unsigned int mask_offset;
588 /* 'new' is initially invisible to lookups. */
589 new = cls_match_alloc(rule, version, conjs, n_conjs);
591 CONST_CAST(struct cls_rule *, rule)->cls_match = new;
593 subtable = find_subtable(cls, rule->match.mask);
595 subtable = insert_subtable(cls, rule->match.mask);
598 /* Compute hashes in segments. */
601 for (i = 0; i < subtable->n_indices; i++) {
602 ihash[i] = minimatch_hash_range(&rule->match, subtable->index_maps[i],
603 &mask_offset, &basis);
605 hash = minimatch_hash_range(&rule->match, subtable->index_maps[i],
606 &mask_offset, &basis);
608 head = find_equal(subtable, rule->match.flow, hash);
610 /* Add rule to tries.
612 * Concurrent readers might miss seeing the rule until this update,
613 * which might require being fixed up by revalidation later. */
614 for (i = 0; i < cls->n_tries; i++) {
615 if (subtable->trie_plen[i]) {
616 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
620 /* Add rule to ports trie. */
621 if (subtable->ports_mask_len) {
622 /* We mask the value to be inserted to always have the wildcarded
623 * bits in known (zero) state, so we can include them in comparison
624 * and they will always match (== their original value does not
626 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
628 trie_insert_prefix(&subtable->ports_trie, &masked_ports,
629 subtable->ports_mask_len);
632 /* Add rule to partitions.
634 * Concurrent readers might miss seeing the rule until this update,
635 * which might require being fixed up by revalidation later. */
636 new->partition = NULL;
637 if (minimask_get_metadata_mask(rule->match.mask) == OVS_BE64_MAX) {
638 ovs_be64 metadata = miniflow_get_metadata(rule->match.flow);
640 new->partition = create_partition(cls, subtable, metadata);
643 /* Add new node to segment indices.
645 * Readers may find the rule in the indices before the rule is visible
646 * in the subtables 'rules' map. This may result in us losing the
647 * opportunity to quit lookups earlier, resulting in sub-optimal
648 * wildcarding. This will be fixed later by revalidation (always
649 * scheduled after flow table changes). */
650 for (i = 0; i < subtable->n_indices; i++) {
651 cmap_insert(&subtable->indices[i], &new->index_nodes[i], ihash[i]);
653 n_rules = cmap_insert(&subtable->rules, &new->cmap_node, hash);
654 } else { /* Equal rules exist in the classifier already. */
655 struct cls_match *prev, *iter;
657 /* Scan the list for the insertion point that will keep the list in
658 * order of decreasing priority. Insert after rules marked invisible
659 * in any version of the same priority. */
660 FOR_EACH_RULE_IN_LIST_PROTECTED (iter, prev, head) {
661 if (rule->priority > iter->priority
662 || (rule->priority == iter->priority
663 && !cls_match_is_eventually_invisible(iter))) {
668 /* Replace 'iter' with 'new' or insert 'new' between 'prev' and
671 struct cls_rule *old;
673 if (rule->priority == iter->priority) {
674 cls_match_replace(prev, iter, new);
675 old = CONST_CAST(struct cls_rule *, iter->cls_rule);
677 cls_match_insert(prev, iter, new);
681 /* Replace the existing head in data structures, if rule is the new
684 subtable_replace_head_rule(cls, subtable, head, new, hash,
689 struct cls_conjunction_set *conj_set;
691 conj_set = ovsrcu_get_protected(struct cls_conjunction_set *,
694 ovsrcu_postpone(free, conj_set);
697 ovsrcu_postpone(cls_match_free_cb, iter);
698 old->cls_match = NULL;
700 /* No change in subtable's max priority or max count. */
702 /* Make 'new' visible to lookups in the appropriate version. */
703 cls_match_set_remove_version(new, CLS_NOT_REMOVED_VERSION);
705 /* Make rule visible to iterators (immediately). */
706 rculist_replace(CONST_CAST(struct rculist *, &rule->node),
709 /* Return displaced rule. Caller is responsible for keeping it
710 * around until all threads quiesce. */
714 /* 'new' is new node after 'prev' */
715 cls_match_insert(prev, iter, new);
719 /* Make 'new' visible to lookups in the appropriate version. */
720 cls_match_set_remove_version(new, CLS_NOT_REMOVED_VERSION);
722 /* Make rule visible to iterators (immediately). */
723 rculist_push_back(&subtable->rules_list,
724 CONST_CAST(struct rculist *, &rule->node));
726 /* Rule was added, not replaced. Update 'subtable's 'max_priority' and
727 * 'max_count', if necessary.
729 * The rule was already inserted, but concurrent readers may not see the
730 * rule yet as the subtables vector is not updated yet. This will have to
731 * be fixed by revalidation later. */
733 subtable->max_priority = rule->priority;
734 subtable->max_count = 1;
735 pvector_insert(&cls->subtables, subtable, rule->priority);
736 } else if (rule->priority == subtable->max_priority) {
737 ++subtable->max_count;
738 } else if (rule->priority > subtable->max_priority) {
739 subtable->max_priority = rule->priority;
740 subtable->max_count = 1;
741 pvector_change_priority(&cls->subtables, subtable, rule->priority);
744 /* Nothing was replaced. */
748 pvector_publish(&cls->subtables);
754 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
755 * must not modify or free it.
757 * 'cls' must not contain an identical rule (including wildcards, values of
758 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
761 classifier_insert(struct classifier *cls, const struct cls_rule *rule,
762 cls_version_t version, const struct cls_conjunction conj[],
765 const struct cls_rule *displaced_rule
766 = classifier_replace(cls, rule, version, conj, n_conj);
767 ovs_assert(!displaced_rule);
770 /* Removes 'rule' from 'cls'. It is the caller's responsibility to destroy
771 * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
772 * resides, etc., as necessary.
774 * Does nothing if 'rule' has been already removed, or was never inserted.
776 * Returns the removed rule, or NULL, if it was already removed.
778 const struct cls_rule *
779 classifier_remove(struct classifier *cls, const struct cls_rule *cls_rule)
781 struct cls_match *rule, *prev, *next, *head;
782 struct cls_partition *partition;
783 struct cls_conjunction_set *conj_set;
784 struct cls_subtable *subtable;
785 uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
786 unsigned int mask_offset;
790 rule = cls_rule->cls_match;
794 /* Mark as removed. */
795 CONST_CAST(struct cls_rule *, cls_rule)->cls_match = NULL;
797 /* Remove 'cls_rule' from the subtable's rules list. */
798 rculist_remove(CONST_CAST(struct rculist *, &cls_rule->node));
800 subtable = find_subtable(cls, cls_rule->match.mask);
801 ovs_assert(subtable);
804 for (i = 0; i < subtable->n_indices; i++) {
805 ihash[i] = minimatch_hash_range(&cls_rule->match,
806 subtable->index_maps[i],
807 &mask_offset, &basis);
809 hash = minimatch_hash_range(&cls_rule->match, subtable->index_maps[i],
810 &mask_offset, &basis);
812 head = find_equal(subtable, cls_rule->match.flow, hash);
814 /* Check if the rule is not the head rule. */
816 struct cls_match *iter;
818 /* Not the head rule, but potentially one with the same priority. */
819 /* Remove from the list of equal rules. */
820 FOR_EACH_RULE_IN_LIST_PROTECTED (iter, prev, head) {
825 ovs_assert(iter == rule);
827 cls_match_remove(prev, rule);
832 /* 'rule' is the head rule. Check if there is another rule to
833 * replace 'rule' in the data structures. */
834 next = cls_match_next_protected(rule);
836 subtable_replace_head_rule(cls, subtable, rule, next, hash, ihash);
840 /* 'rule' is last of the kind in the classifier, must remove from all the
841 * data structures. */
843 if (subtable->ports_mask_len) {
844 ovs_be32 masked_ports = minimatch_get_ports(&cls_rule->match);
846 trie_remove_prefix(&subtable->ports_trie,
847 &masked_ports, subtable->ports_mask_len);
849 for (i = 0; i < cls->n_tries; i++) {
850 if (subtable->trie_plen[i]) {
851 trie_remove(&cls->tries[i], cls_rule, subtable->trie_plen[i]);
855 /* Remove rule node from indices. */
856 for (i = 0; i < subtable->n_indices; i++) {
857 cmap_remove(&subtable->indices[i], &rule->index_nodes[i], ihash[i]);
859 n_rules = cmap_remove(&subtable->rules, &rule->cmap_node, hash);
861 partition = rule->partition;
863 tag_tracker_subtract(&partition->tracker, &partition->tags,
865 if (!partition->tags) {
866 cmap_remove(&cls->partitions, &partition->cmap_node,
867 hash_metadata(partition->metadata));
868 ovsrcu_postpone(free, partition);
873 destroy_subtable(cls, subtable);
876 if (subtable->max_priority == rule->priority
877 && --subtable->max_count == 0) {
878 /* Find the new 'max_priority' and 'max_count'. */
879 int max_priority = INT_MIN;
880 struct cls_match *head;
882 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
883 if (head->priority > max_priority) {
884 max_priority = head->priority;
885 subtable->max_count = 1;
886 } else if (head->priority == max_priority) {
887 ++subtable->max_count;
890 subtable->max_priority = max_priority;
891 pvector_change_priority(&cls->subtables, subtable, max_priority);
896 pvector_publish(&cls->subtables);
900 conj_set = ovsrcu_get_protected(struct cls_conjunction_set *,
903 ovsrcu_postpone(free, conj_set);
905 ovsrcu_postpone(cls_match_free_cb, rule);
911 /* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
912 * subtables which have a prefix match on the trie field, but whose prefix
913 * length is not indicated in 'match_plens'. For example, a subtable that
914 * has a 8-bit trie field prefix match can be skipped if
915 * !be_get_bit_at(&match_plens, 8 - 1). If skipped, 'maskbits' prefix bits
916 * must be unwildcarded to make datapath flow only match packets it should. */
918 const struct cls_trie *trie;
919 bool lookup_done; /* Status of the lookup. */
920 uint8_t be32ofs; /* U32 offset of the field in question. */
921 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
922 union trie_prefix match_plens; /* Bitmask of prefix lengths with possible
927 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
930 ctx->be32ofs = trie->field->flow_be32ofs;
931 ctx->lookup_done = false;
934 struct conjunctive_match {
935 struct hmap_node hmap_node;
940 static struct conjunctive_match *
941 find_conjunctive_match__(struct hmap *matches, uint64_t id, uint32_t hash)
943 struct conjunctive_match *m;
945 HMAP_FOR_EACH_IN_BUCKET (m, hmap_node, hash, matches) {
954 find_conjunctive_match(const struct cls_conjunction_set *set,
955 unsigned int max_n_clauses, struct hmap *matches,
956 struct conjunctive_match *cm_stubs, size_t n_cm_stubs,
959 const struct cls_conjunction *c;
961 if (max_n_clauses < set->min_n_clauses) {
965 for (c = set->conj; c < &set->conj[set->n]; c++) {
966 struct conjunctive_match *cm;
969 if (c->n_clauses > max_n_clauses) {
973 hash = hash_int(c->id, 0);
974 cm = find_conjunctive_match__(matches, c->id, hash);
976 size_t n = hmap_count(matches);
978 cm = n < n_cm_stubs ? &cm_stubs[n] : xmalloc(sizeof *cm);
979 hmap_insert(matches, &cm->hmap_node, hash);
981 cm->clauses = UINT64_MAX << (c->n_clauses & 63);
983 cm->clauses |= UINT64_C(1) << c->clause;
984 if (cm->clauses == UINT64_MAX) {
993 free_conjunctive_matches(struct hmap *matches,
994 struct conjunctive_match *cm_stubs, size_t n_cm_stubs)
996 if (hmap_count(matches) > n_cm_stubs) {
997 struct conjunctive_match *cm, *next;
999 HMAP_FOR_EACH_SAFE (cm, next, hmap_node, matches) {
1000 if (!(cm >= cm_stubs && cm < &cm_stubs[n_cm_stubs])) {
1005 hmap_destroy(matches);
1008 /* Like classifier_lookup(), except that support for conjunctive matches can be
1009 * configured with 'allow_conjunctive_matches'. That feature is not exposed
1010 * externally because turning off conjunctive matches is only useful to avoid
1011 * recursion within this function itself.
1013 * 'flow' is non-const to allow for temporary modifications during the lookup.
1014 * Any changes are restored before returning. */
1015 static const struct cls_rule *
1016 classifier_lookup__(const struct classifier *cls, cls_version_t version,
1017 struct flow *flow, struct flow_wildcards *wc,
1018 bool allow_conjunctive_matches)
1020 const struct cls_partition *partition;
1021 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
1022 const struct cls_match *match;
1025 /* Highest-priority flow in 'cls' that certainly matches 'flow'. */
1026 const struct cls_match *hard = NULL;
1027 int hard_pri = INT_MIN; /* hard ? hard->priority : INT_MIN. */
1029 /* Highest-priority conjunctive flows in 'cls' matching 'flow'. Since
1030 * these are (components of) conjunctive flows, we can only know whether
1031 * the full conjunctive flow matches after seeing multiple of them. Thus,
1032 * we refer to these as "soft matches". */
1033 struct cls_conjunction_set *soft_stub[64];
1034 struct cls_conjunction_set **soft = soft_stub;
1035 size_t n_soft = 0, allocated_soft = ARRAY_SIZE(soft_stub);
1036 int soft_pri = INT_MIN; /* n_soft ? MAX(soft[*]->priority) : INT_MIN. */
1038 /* Synchronize for cls->n_tries and subtable->trie_plen. They can change
1039 * when table configuration changes, which happens typically only on
1041 atomic_thread_fence(memory_order_acquire);
1043 /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
1044 * then 'flow' cannot possibly match in 'subtable':
1046 * - If flow->metadata maps to a given 'partition', then we can use
1047 * 'tags' for 'partition->tags'.
1049 * - If flow->metadata has no partition, then no rule in 'cls' has an
1050 * exact-match for flow->metadata. That means that we don't need to
1051 * search any subtable that includes flow->metadata in its mask.
1053 * In either case, we always need to search any cls_subtables that do not
1054 * include flow->metadata in its mask. One way to do that would be to
1055 * check the "cls_subtable"s explicitly for that, but that would require an
1056 * extra branch per subtable. Instead, we mark such a cls_subtable's
1057 * 'tags' as TAG_ALL and make sure that 'tags' is never empty. This means
1058 * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
1059 * need a special case.
1061 partition = (cmap_is_empty(&cls->partitions)
1063 : find_partition(cls, flow->metadata,
1064 hash_metadata(flow->metadata)));
1065 tags = partition ? partition->tags : TAG_ARBITRARY;
1067 /* Initialize trie contexts for find_match_wc(). */
1068 for (int i = 0; i < cls->n_tries; i++) {
1069 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
1073 struct cls_subtable *subtable;
1074 PVECTOR_FOR_EACH_PRIORITY (subtable, hard_pri, 2, sizeof *subtable,
1076 struct cls_conjunction_set *conj_set;
1078 /* Skip subtables not in our partition. */
1079 if (!tag_intersects(tags, subtable->tag)) {
1083 /* Skip subtables with no match, or where the match is lower-priority
1084 * than some certain match we've already found. */
1085 match = find_match_wc(subtable, version, flow, trie_ctx, cls->n_tries,
1087 if (!match || match->priority <= hard_pri) {
1091 conj_set = ovsrcu_get(struct cls_conjunction_set *, &match->conj_set);
1093 /* 'match' isn't part of a conjunctive match. It's the best
1094 * certain match we've got so far, since we know that it's
1095 * higher-priority than hard_pri.
1097 * (There might be a higher-priority conjunctive match. We can't
1100 hard_pri = hard->priority;
1101 } else if (allow_conjunctive_matches) {
1102 /* 'match' is part of a conjunctive match. Add it to the list. */
1103 if (OVS_UNLIKELY(n_soft >= allocated_soft)) {
1104 struct cls_conjunction_set **old_soft = soft;
1106 allocated_soft *= 2;
1107 soft = xmalloc(allocated_soft * sizeof *soft);
1108 memcpy(soft, old_soft, n_soft * sizeof *soft);
1109 if (old_soft != soft_stub) {
1113 soft[n_soft++] = conj_set;
1115 /* Keep track of the highest-priority soft match. */
1116 if (soft_pri < match->priority) {
1117 soft_pri = match->priority;
1122 /* In the common case, at this point we have no soft matches and we can
1123 * return immediately. (We do the same thing if we have potential soft
1124 * matches but none of them are higher-priority than our hard match.) */
1125 if (hard_pri >= soft_pri) {
1126 if (soft != soft_stub) {
1129 return hard ? hard->cls_rule : NULL;
1132 /* At this point, we have some soft matches. We might also have a hard
1133 * match; if so, its priority is lower than the highest-priority soft
1138 * Check whether soft matches are real matches. */
1140 /* Delete soft matches that are null. This only happens in second and
1141 * subsequent iterations of the soft match loop, when we drop back from
1142 * a high-priority soft match to a lower-priority one.
1144 * Also, delete soft matches whose priority is less than or equal to
1145 * the hard match's priority. In the first iteration of the soft
1146 * match, these can be in 'soft' because the earlier main loop found
1147 * the soft match before the hard match. In second and later iteration
1148 * of the soft match loop, these can be in 'soft' because we dropped
1149 * back from a high-priority soft match to a lower-priority soft match.
1151 * It is tempting to delete soft matches that cannot be satisfied
1152 * because there are fewer soft matches than required to satisfy any of
1153 * their conjunctions, but we cannot do that because there might be
1154 * lower priority soft or hard matches with otherwise identical
1155 * matches. (We could special case those here, but there's no
1156 * need--we'll do so at the bottom of the soft match loop anyway and
1157 * this duplicates less code.)
1159 * It's also tempting to break out of the soft match loop if 'n_soft ==
1160 * 1' but that would also miss lower-priority hard matches. We could
1161 * special case that also but again there's no need. */
1162 for (int i = 0; i < n_soft; ) {
1163 if (!soft[i] || soft[i]->priority <= hard_pri) {
1164 soft[i] = soft[--n_soft];
1173 /* Find the highest priority among the soft matches. (We know this
1174 * must be higher than the hard match's priority; otherwise we would
1175 * have deleted all of the soft matches in the previous loop.) Count
1176 * the number of soft matches that have that priority. */
1179 for (int i = 0; i < n_soft; i++) {
1180 if (soft[i]->priority > soft_pri) {
1181 soft_pri = soft[i]->priority;
1183 } else if (soft[i]->priority == soft_pri) {
1187 ovs_assert(soft_pri > hard_pri);
1189 /* Look for a real match among the highest-priority soft matches.
1191 * It's unusual to have many conjunctive matches, so we use stubs to
1192 * avoid calling malloc() in the common case. An hmap has a built-in
1193 * stub for up to 2 hmap_nodes; possibly, we would benefit a variant
1194 * with a bigger stub. */
1195 struct conjunctive_match cm_stubs[16];
1196 struct hmap matches;
1198 hmap_init(&matches);
1199 for (int i = 0; i < n_soft; i++) {
1202 if (soft[i]->priority == soft_pri
1203 && find_conjunctive_match(soft[i], n_soft_pri, &matches,
1204 cm_stubs, ARRAY_SIZE(cm_stubs),
1206 uint32_t saved_conj_id = flow->conj_id;
1207 const struct cls_rule *rule;
1210 rule = classifier_lookup__(cls, version, flow, wc, false);
1211 flow->conj_id = saved_conj_id;
1214 free_conjunctive_matches(&matches,
1215 cm_stubs, ARRAY_SIZE(cm_stubs));
1216 if (soft != soft_stub) {
1223 free_conjunctive_matches(&matches, cm_stubs, ARRAY_SIZE(cm_stubs));
1225 /* There's no real match among the highest-priority soft matches.
1226 * However, if any of those soft matches has a lower-priority but
1227 * otherwise identical flow match, then we need to consider those for
1228 * soft or hard matches.
1230 * The next iteration of the soft match loop will delete any null
1231 * pointers we put into 'soft' (and some others too). */
1232 for (int i = 0; i < n_soft; i++) {
1233 if (soft[i]->priority != soft_pri) {
1237 /* Find next-lower-priority flow with identical flow match. */
1238 match = next_visible_rule_in_list(soft[i]->match, version);
1240 soft[i] = ovsrcu_get(struct cls_conjunction_set *,
1243 /* The flow is a hard match; don't treat as a soft
1245 if (match->priority > hard_pri) {
1247 hard_pri = hard->priority;
1251 /* No such lower-priority flow (probably the common case). */
1257 if (soft != soft_stub) {
1260 return hard ? hard->cls_rule : NULL;
1263 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow' and
1264 * that is visible in 'version'. Returns a null pointer if no rules in 'cls'
1265 * match 'flow'. If multiple rules of equal priority match 'flow', returns one
1268 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
1269 * set of bits that were significant in the lookup. At some point
1270 * earlier, 'wc' should have been initialized (e.g., by
1271 * flow_wildcards_init_catchall()).
1273 * 'flow' is non-const to allow for temporary modifications during the lookup.
1274 * Any changes are restored before returning. */
1275 const struct cls_rule *
1276 classifier_lookup(const struct classifier *cls, cls_version_t version,
1277 struct flow *flow, struct flow_wildcards *wc)
1279 return classifier_lookup__(cls, version, flow, wc, true);
1282 /* Finds and returns a rule in 'cls' with exactly the same priority and
1283 * matching criteria as 'target', and that is visible in 'version'.
1284 * Only one such rule may ever exist. Returns a null pointer if 'cls' doesn't
1285 * contain an exact match. */
1286 const struct cls_rule *
1287 classifier_find_rule_exactly(const struct classifier *cls,
1288 const struct cls_rule *target,
1289 cls_version_t version)
1291 const struct cls_match *head, *rule;
1292 const struct cls_subtable *subtable;
1294 subtable = find_subtable(cls, target->match.mask);
1299 head = find_equal(subtable, target->match.flow,
1300 miniflow_hash_in_minimask(target->match.flow,
1301 target->match.mask, 0));
1305 CLS_MATCH_FOR_EACH (rule, head) {
1306 if (rule->priority < target->priority) {
1307 break; /* Not found. */
1309 if (rule->priority == target->priority
1310 && cls_match_visible_in_version(rule, version)) {
1311 return rule->cls_rule;
1317 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
1318 * same matching criteria as 'target', and that is visible in 'version'.
1319 * Returns a null pointer if 'cls' doesn't contain an exact match visible in
1321 const struct cls_rule *
1322 classifier_find_match_exactly(const struct classifier *cls,
1323 const struct match *target, int priority,
1324 cls_version_t version)
1326 const struct cls_rule *retval;
1329 cls_rule_init(&cr, target, priority);
1330 retval = classifier_find_rule_exactly(cls, &cr, version);
1331 cls_rule_destroy(&cr);
1336 /* Checks if 'target' would overlap any other rule in 'cls' in 'version'. Two
1337 * rules are considered to overlap if both rules have the same priority and a
1338 * packet could match both, and if both rules are visible in the same version.
1340 * A trivial example of overlapping rules is two rules matching disjoint sets
1341 * of fields. E.g., if one rule matches only on port number, while another only
1342 * on dl_type, any packet from that specific port and with that specific
1343 * dl_type could match both, if the rules also have the same priority. */
1345 classifier_rule_overlaps(const struct classifier *cls,
1346 const struct cls_rule *target, cls_version_t version)
1348 struct cls_subtable *subtable;
1350 /* Iterate subtables in the descending max priority order. */
1351 PVECTOR_FOR_EACH_PRIORITY (subtable, target->priority - 1, 2,
1352 sizeof(struct cls_subtable), &cls->subtables) {
1354 struct minimask mask;
1355 uint64_t storage[FLOW_U64S];
1357 const struct cls_rule *rule;
1359 minimask_combine(&m.mask, target->match.mask, &subtable->mask,
1362 RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
1363 if (rule->priority == target->priority
1364 && miniflow_equal_in_minimask(target->match.flow,
1365 rule->match.flow, &m.mask)
1366 && cls_match_visible_in_version(rule->cls_match, version)) {
1374 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
1375 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
1376 * function returns true if, for every field:
1378 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
1381 * - 'criteria' wildcards the field,
1383 * Conversely, 'rule' does not match 'criteria' and this function returns false
1384 * if, for at least one field:
1386 * - 'criteria' and 'rule' specify different values for the field, or
1388 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
1390 * Equivalently, the truth table for whether a field matches is:
1395 * r +---------+---------+
1396 * i wild | yes | yes |
1398 * e +---------+---------+
1399 * r exact | no |if values|
1401 * a +---------+---------+
1403 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
1404 * commands and by OpenFlow 1.0 aggregate and flow stats.
1406 * Ignores rule->priority. */
1408 cls_rule_is_loose_match(const struct cls_rule *rule,
1409 const struct minimatch *criteria)
1411 return (!minimask_has_extra(rule->match.mask, criteria->mask)
1412 && miniflow_equal_in_minimask(rule->match.flow, criteria->flow,
1419 rule_matches(const struct cls_rule *rule, const struct cls_rule *target,
1420 cls_version_t version)
1422 /* Rule may only match a target if it is visible in target's version. */
1423 return cls_match_visible_in_version(rule->cls_match, version)
1424 && (!target || miniflow_equal_in_minimask(rule->match.flow,
1426 target->match.mask));
1429 static const struct cls_rule *
1430 search_subtable(const struct cls_subtable *subtable,
1431 struct cls_cursor *cursor)
1434 || !minimask_has_extra(&subtable->mask, cursor->target->match.mask)) {
1435 const struct cls_rule *rule;
1437 RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
1438 if (rule_matches(rule, cursor->target, cursor->version)) {
1446 /* Initializes 'cursor' for iterating through rules in 'cls', and returns the
1449 * - If 'target' is null, or if the 'target' is a catchall target, the
1450 * cursor will visit every rule in 'cls' that is visible in 'version'.
1452 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1453 * such that cls_rule_is_loose_match(rule, target) returns true and that
1454 * the rule is visible in 'version'.
1456 * Ignores target->priority. */
1458 cls_cursor_start(const struct classifier *cls, const struct cls_rule *target,
1459 cls_version_t version)
1461 struct cls_cursor cursor;
1462 struct cls_subtable *subtable;
1465 cursor.target = target && !cls_rule_is_catchall(target) ? target : NULL;
1466 cursor.version = version;
1469 /* Find first rule. */
1470 PVECTOR_CURSOR_FOR_EACH (subtable, &cursor.subtables,
1471 &cursor.cls->subtables) {
1472 const struct cls_rule *rule = search_subtable(subtable, &cursor);
1475 cursor.subtable = subtable;
1484 static const struct cls_rule *
1485 cls_cursor_next(struct cls_cursor *cursor)
1487 const struct cls_rule *rule;
1488 const struct cls_subtable *subtable;
1490 rule = cursor->rule;
1491 subtable = cursor->subtable;
1492 RCULIST_FOR_EACH_CONTINUE (rule, node, &subtable->rules_list) {
1493 if (rule_matches(rule, cursor->target, cursor->version)) {
1498 PVECTOR_CURSOR_FOR_EACH_CONTINUE (subtable, &cursor->subtables) {
1499 rule = search_subtable(subtable, cursor);
1501 cursor->subtable = subtable;
1509 /* Sets 'cursor->rule' to the next matching cls_rule in 'cursor''s iteration,
1510 * or to null if all matching rules have been visited. */
1512 cls_cursor_advance(struct cls_cursor *cursor)
1514 cursor->rule = cls_cursor_next(cursor);
1517 static struct cls_subtable *
1518 find_subtable(const struct classifier *cls, const struct minimask *mask)
1520 struct cls_subtable *subtable;
1522 CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, minimask_hash(mask, 0),
1523 &cls->subtables_map) {
1524 if (minimask_equal(mask, &subtable->mask)) {
1531 /* Initializes 'map' with a subset of 'miniflow''s maps that includes only the
1532 * portions with u64-offset 'i' such that 'start' <= i < 'end'. Does not copy
1533 * any data from 'miniflow' to 'map'. */
1534 static struct flowmap
1535 miniflow_get_map_in_range(const struct miniflow *miniflow, uint8_t start,
1541 map = miniflow->map;
1543 /* Clear the bits before 'start'. */
1544 while (start >= MAP_T_BITS) {
1545 start -= MAP_T_BITS;
1547 map.bits[start / MAP_T_BITS] = 0;
1550 flowmap_clear(&map, ofs, start);
1553 /* Clear the bits starting at 'end'. */
1554 if (end < FLOW_U64S) {
1555 /* flowmap_clear() can handle at most MAP_T_BITS at a time. */
1556 ovs_assert(FLOW_U64S - end <= MAP_T_BITS);
1557 flowmap_clear(&map, end, FLOW_U64S - end);
1562 /* The new subtable will be visible to the readers only after this. */
1563 static struct cls_subtable *
1564 insert_subtable(struct classifier *cls, const struct minimask *mask)
1566 uint32_t hash = minimask_hash(mask, 0);
1567 struct cls_subtable *subtable;
1569 struct flowmap stage_map;
1571 size_t count = miniflow_n_values(&mask->masks);
1573 subtable = xzalloc(sizeof *subtable + MINIFLOW_VALUES_SIZE(count));
1574 cmap_init(&subtable->rules);
1575 miniflow_clone(CONST_CAST(struct miniflow *, &subtable->mask.masks),
1576 &mask->masks, count);
1578 /* Init indices for segmented lookup, if any. */
1580 for (i = 0; i < cls->n_flow_segments; i++) {
1581 stage_map = miniflow_get_map_in_range(&mask->masks, prev,
1582 cls->flow_segments[i]);
1583 /* Add an index if it adds mask bits. */
1584 if (!flowmap_is_empty(stage_map)) {
1585 cmap_init(&subtable->indices[index]);
1586 *CONST_CAST(struct flowmap *, &subtable->index_maps[index])
1590 prev = cls->flow_segments[i];
1592 /* Map for the final stage. */
1593 *CONST_CAST(struct flowmap *, &subtable->index_maps[index])
1594 = miniflow_get_map_in_range(&mask->masks, prev, FLOW_U64S);
1595 /* Check if the final stage adds any bits,
1596 * and remove the last index if it doesn't. */
1598 if (flowmap_equal(subtable->index_maps[index],
1599 subtable->index_maps[index - 1])) {
1601 cmap_destroy(&subtable->indices[index]);
1604 *CONST_CAST(uint8_t *, &subtable->n_indices) = index;
1606 *CONST_CAST(tag_type *, &subtable->tag) =
1607 (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1608 ? tag_create_deterministic(hash)
1611 for (i = 0; i < cls->n_tries; i++) {
1612 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1613 cls->tries[i].field);
1617 ovsrcu_set_hidden(&subtable->ports_trie, NULL);
1618 *CONST_CAST(int *, &subtable->ports_mask_len)
1619 = 32 - ctz32(ntohl(MINIFLOW_GET_BE32(&mask->masks, tp_src)));
1621 /* List of rules. */
1622 rculist_init(&subtable->rules_list);
1624 cmap_insert(&cls->subtables_map, &subtable->cmap_node, hash);
1629 /* RCU readers may still access the subtable before it is actually freed. */
1631 destroy_subtable(struct classifier *cls, struct cls_subtable *subtable)
1635 pvector_remove(&cls->subtables, subtable);
1636 cmap_remove(&cls->subtables_map, &subtable->cmap_node,
1637 minimask_hash(&subtable->mask, 0));
1639 ovs_assert(ovsrcu_get_protected(struct trie_node *, &subtable->ports_trie)
1641 ovs_assert(cmap_is_empty(&subtable->rules));
1642 ovs_assert(rculist_is_empty(&subtable->rules_list));
1644 for (i = 0; i < subtable->n_indices; i++) {
1645 cmap_destroy(&subtable->indices[i]);
1647 cmap_destroy(&subtable->rules);
1648 ovsrcu_postpone(free, subtable);
1651 static unsigned int be_get_bit_at(const ovs_be32 value[], unsigned int ofs);
1653 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1654 * lookup results. */
1656 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1657 const unsigned int field_plen[CLS_MAX_TRIES],
1658 const struct flowmap range_map, const struct flow *flow,
1659 struct flow_wildcards *wc)
1663 /* Check if we could avoid fully unwildcarding the next level of
1664 * fields using the prefix tries. The trie checks are done only as
1665 * needed to avoid folding in additional bits to the wildcards mask. */
1666 for (j = 0; j < n_tries; j++) {
1667 /* Is the trie field relevant for this subtable, and
1668 is the trie field within the current range of fields? */
1669 if (field_plen[j] &&
1670 flowmap_is_set(&range_map, trie_ctx[j].be32ofs / 2)) {
1671 struct trie_ctx *ctx = &trie_ctx[j];
1673 /* On-demand trie lookup. */
1674 if (!ctx->lookup_done) {
1675 memset(&ctx->match_plens, 0, sizeof ctx->match_plens);
1676 ctx->maskbits = trie_lookup(ctx->trie, flow, &ctx->match_plens);
1677 ctx->lookup_done = true;
1679 /* Possible to skip the rest of the subtable if subtable's
1680 * prefix on the field is not included in the lookup result. */
1681 if (!be_get_bit_at(&ctx->match_plens.be32, field_plen[j] - 1)) {
1682 /* We want the trie lookup to never result in unwildcarding
1683 * any bits that would not be unwildcarded otherwise.
1684 * Since the trie is shared by the whole classifier, it is
1685 * possible that the 'maskbits' contain bits that are
1686 * irrelevant for the partition relevant for the current
1687 * packet. Hence the checks below. */
1689 /* Check that the trie result will not unwildcard more bits
1690 * than this subtable would otherwise. */
1691 if (ctx->maskbits <= field_plen[j]) {
1692 /* Unwildcard the bits and skip the rest. */
1693 mask_set_prefix_bits(wc, ctx->be32ofs, ctx->maskbits);
1694 /* Note: Prerequisite already unwildcarded, as the only
1695 * prerequisite of the supported trie lookup fields is
1696 * the ethertype, which is always unwildcarded. */
1699 /* Can skip if the field is already unwildcarded. */
1700 if (mask_prefix_bits_set(wc, ctx->be32ofs, ctx->maskbits)) {
1709 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1710 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1711 * value has the correct value in 'target'.
1713 * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
1714 * target, mask) but this is faster because of the invariant that
1715 * flow->map and mask->masks.map are the same, and that this version
1716 * takes the 'wc'. */
1718 miniflow_and_mask_matches_flow(const struct miniflow *flow,
1719 const struct minimask *mask,
1720 const struct flow *target)
1722 const uint64_t *flowp = miniflow_get_values(flow);
1723 const uint64_t *maskp = miniflow_get_values(&mask->masks);
1724 const uint64_t *target_u64 = (const uint64_t *)target;
1727 FLOWMAP_FOR_EACH_MAP (map, mask->masks.map) {
1730 MAP_FOR_EACH_INDEX (idx, map) {
1731 if ((*flowp++ ^ target_u64[idx]) & *maskp++) {
1735 target_u64 += MAP_T_BITS;
1740 static inline const struct cls_match *
1741 find_match(const struct cls_subtable *subtable, cls_version_t version,
1742 const struct flow *flow, uint32_t hash)
1744 const struct cls_match *head, *rule;
1746 CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1747 if (OVS_LIKELY(miniflow_and_mask_matches_flow(&head->flow,
1750 /* Return highest priority rule that is visible. */
1751 CLS_MATCH_FOR_EACH (rule, head) {
1752 if (OVS_LIKELY(cls_match_visible_in_version(rule, version))) {
1762 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1763 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1764 * value has the correct value in 'target'.
1766 * This function is equivalent to miniflow_and_mask_matches_flow() but this
1767 * version fills in the mask bits in 'wc'. */
1769 miniflow_and_mask_matches_flow_wc(const struct miniflow *flow,
1770 const struct minimask *mask,
1771 const struct flow *target,
1772 struct flow_wildcards *wc)
1774 const uint64_t *flowp = miniflow_get_values(flow);
1775 const uint64_t *maskp = miniflow_get_values(&mask->masks);
1776 const uint64_t *target_u64 = (const uint64_t *)target;
1777 uint64_t *wc_u64 = (uint64_t *)&wc->masks;
1782 FLOWMAP_FOR_EACH_MAP (map, mask->masks.map) {
1783 MAP_FOR_EACH_INDEX(idx, map) {
1784 uint64_t msk = *maskp++;
1786 diff = (*flowp++ ^ target_u64[idx]) & msk;
1791 /* Fill in the bits that were looked at. */
1794 target_u64 += MAP_T_BITS;
1795 wc_u64 += MAP_T_BITS;
1800 /* Only unwildcard if none of the differing bits is already
1802 if (!(wc_u64[idx] & diff)) {
1803 /* Keep one bit of the difference. The selected bit may be
1804 * different in big-endian v.s. little-endian systems. */
1805 wc_u64[idx] |= rightmost_1bit(diff);
1810 static const struct cls_match *
1811 find_match_wc(const struct cls_subtable *subtable, cls_version_t version,
1812 const struct flow *flow, struct trie_ctx trie_ctx[CLS_MAX_TRIES],
1813 unsigned int n_tries, struct flow_wildcards *wc)
1815 if (OVS_UNLIKELY(!wc)) {
1816 return find_match(subtable, version, flow,
1817 flow_hash_in_minimask(flow, &subtable->mask, 0));
1820 uint32_t basis = 0, hash;
1821 const struct cls_match *rule = NULL;
1822 struct flowmap stages_map = FLOWMAP_EMPTY_INITIALIZER;
1823 unsigned int mask_offset = 0;
1826 /* Try to finish early by checking fields in segments. */
1827 for (i = 0; i < subtable->n_indices; i++) {
1828 const struct cmap_node *inode;
1830 if (check_tries(trie_ctx, n_tries, subtable->trie_plen,
1831 subtable->index_maps[i], flow, wc)) {
1832 /* 'wc' bits for the trie field set, now unwildcard the preceding
1833 * bits used so far. */
1837 /* Accumulate the map used so far. */
1838 stages_map = flowmap_or(stages_map, subtable->index_maps[i]);
1840 hash = flow_hash_in_minimask_range(flow, &subtable->mask,
1841 subtable->index_maps[i],
1842 &mask_offset, &basis);
1844 inode = cmap_find(&subtable->indices[i], hash);
1849 /* If we have narrowed down to a single rule already, check whether
1850 * that rule matches. Either way, we're done.
1852 * (Rare) hash collisions may cause us to miss the opportunity for this
1854 if (!cmap_node_next(inode)) {
1855 const struct cls_match *head;
1857 ASSIGN_CONTAINER(head, inode - i, index_nodes);
1858 if (miniflow_and_mask_matches_flow_wc(&head->flow, &subtable->mask,
1860 /* Return highest priority rule that is visible. */
1861 CLS_MATCH_FOR_EACH (rule, head) {
1862 if (OVS_LIKELY(cls_match_visible_in_version(rule,
1871 /* Trie check for the final range. */
1872 if (check_tries(trie_ctx, n_tries, subtable->trie_plen,
1873 subtable->index_maps[i], flow, wc)) {
1876 hash = flow_hash_in_minimask_range(flow, &subtable->mask,
1877 subtable->index_maps[i],
1878 &mask_offset, &basis);
1879 rule = find_match(subtable, version, flow, hash);
1880 if (!rule && subtable->ports_mask_len) {
1881 /* The final stage had ports, but there was no match. Instead of
1882 * unwildcarding all the ports bits, use the ports trie to figure out a
1883 * smaller set of bits to unwildcard. */
1885 ovs_be32 value, plens, mask;
1887 mask = MINIFLOW_GET_BE32(&subtable->mask.masks, tp_src);
1888 value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
1889 mbits = trie_lookup_value(&subtable->ports_trie, &value, &plens, 32);
1891 ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
1892 mask & be32_prefix_mask(mbits);
1897 /* Must unwildcard all the fields, as they were looked at. */
1898 flow_wildcards_fold_minimask(wc, &subtable->mask);
1902 /* Unwildcard the bits in stages so far, as they were used in determining
1903 * there is no match. */
1904 flow_wildcards_fold_minimask_in_map(wc, &subtable->mask, stages_map);
1908 static struct cls_match *
1909 find_equal(const struct cls_subtable *subtable, const struct miniflow *flow,
1912 struct cls_match *head;
1914 CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1915 if (miniflow_equal(&head->flow, flow)) {
1922 /* A longest-prefix match tree. */
1924 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1925 * Prefixes are in the network byte order, and the offset 0 corresponds to
1926 * the most significant bit of the first byte. The offset can be read as
1927 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1929 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1933 pr += ofs / 32; /* Where to start. */
1934 ofs %= 32; /* How many bits to skip at 'pr'. */
1936 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1937 if (plen > 32 - ofs) { /* Need more than we have already? */
1938 prefix |= ntohl(*++pr) >> (32 - ofs);
1940 /* Return with possible unwanted bits at the end. */
1944 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1945 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1946 * corresponds to the most significant bit of the first byte. The offset can
1947 * be read as "how many bits to skip from the start of the prefix starting at
1950 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1955 if (plen > TRIE_PREFIX_BITS) {
1956 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1958 /* Return with unwanted bits cleared. */
1959 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1962 /* Return the number of equal bits in 'n_bits' of 'prefix's MSBs and a 'value'
1963 * starting at "MSB 0"-based offset 'ofs'. */
1965 prefix_equal_bits(uint32_t prefix, unsigned int n_bits, const ovs_be32 value[],
1968 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, n_bits);
1969 /* Set the bit after the relevant bits to limit the result. */
1970 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - n_bits));
1973 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1974 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1976 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1977 unsigned int ofs, unsigned int plen)
1979 return prefix_equal_bits(node->prefix, MIN(node->n_bits, plen - ofs),
1983 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1984 * be greater than 31. */
1986 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1988 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1991 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1992 * be between 0 and 31, inclusive. */
1994 get_bit_at(const uint32_t prefix, unsigned int ofs)
1996 return (prefix >> (31 - ofs)) & 1u;
1999 /* Create new branch. */
2000 static struct trie_node *
2001 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
2002 unsigned int n_rules)
2004 struct trie_node *node = xmalloc(sizeof *node);
2006 node->prefix = trie_get_prefix(prefix, ofs, plen);
2008 if (plen <= TRIE_PREFIX_BITS) {
2009 node->n_bits = plen;
2010 ovsrcu_set_hidden(&node->edges[0], NULL);
2011 ovsrcu_set_hidden(&node->edges[1], NULL);
2012 node->n_rules = n_rules;
2013 } else { /* Need intermediate nodes. */
2014 struct trie_node *subnode = trie_branch_create(prefix,
2015 ofs + TRIE_PREFIX_BITS,
2016 plen - TRIE_PREFIX_BITS,
2018 int bit = get_bit_at(subnode->prefix, 0);
2019 node->n_bits = TRIE_PREFIX_BITS;
2020 ovsrcu_set_hidden(&node->edges[bit], subnode);
2021 ovsrcu_set_hidden(&node->edges[!bit], NULL);
2028 trie_node_destroy(const struct trie_node *node)
2030 ovsrcu_postpone(free, CONST_CAST(struct trie_node *, node));
2033 /* Copy a trie node for modification and postpone delete the old one. */
2034 static struct trie_node *
2035 trie_node_rcu_realloc(const struct trie_node *node)
2037 struct trie_node *new_node = xmalloc(sizeof *node);
2040 trie_node_destroy(node);
2046 trie_destroy(rcu_trie_ptr *trie)
2048 struct trie_node *node = ovsrcu_get_protected(struct trie_node *, trie);
2051 ovsrcu_set_hidden(trie, NULL);
2052 trie_destroy(&node->edges[0]);
2053 trie_destroy(&node->edges[1]);
2054 trie_node_destroy(node);
2059 trie_is_leaf(const struct trie_node *trie)
2062 return !ovsrcu_get(struct trie_node *, &trie->edges[0])
2063 && !ovsrcu_get(struct trie_node *, &trie->edges[1]);
2067 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
2068 unsigned int n_bits)
2070 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
2073 for (i = 0; i < n_bits / 32; i++) {
2074 mask[i] = OVS_BE32_MAX;
2077 mask[i] |= htonl(~0u << (32 - n_bits % 32));
2082 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
2083 unsigned int n_bits)
2085 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
2087 ovs_be32 zeroes = 0;
2089 for (i = 0; i < n_bits / 32; i++) {
2093 zeroes |= ~mask[i] & htonl(~0u << (32 - n_bits % 32));
2096 return !zeroes; /* All 'n_bits' bits set. */
2099 static rcu_trie_ptr *
2100 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
2103 return node->edges + be_get_bit_at(value, ofs);
2106 static const struct trie_node *
2107 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
2110 return ovsrcu_get(struct trie_node *,
2111 &node->edges[be_get_bit_at(value, ofs)]);
2114 /* Set the bit at ("MSB 0"-based) offset 'ofs'. 'ofs' can be greater than 31.
2117 be_set_bit_at(ovs_be32 value[], unsigned int ofs)
2119 ((uint8_t *)value)[ofs / 8] |= 1u << (7 - ofs % 8);
2122 /* Returns the number of bits in the prefix mask necessary to determine a
2123 * mismatch, in case there are longer prefixes in the tree below the one that
2125 * '*plens' will have a bit set for each prefix length that may have matching
2126 * rules. The caller is responsible for clearing the '*plens' prior to
2130 trie_lookup_value(const rcu_trie_ptr *trie, const ovs_be32 value[],
2131 ovs_be32 plens[], unsigned int n_bits)
2133 const struct trie_node *prev = NULL;
2134 const struct trie_node *node = ovsrcu_get(struct trie_node *, trie);
2135 unsigned int match_len = 0; /* Number of matching bits. */
2137 for (; node; prev = node, node = trie_next_node(node, value, match_len)) {
2138 unsigned int eqbits;
2139 /* Check if this edge can be followed. */
2140 eqbits = prefix_equal_bits(node->prefix, node->n_bits, value,
2142 match_len += eqbits;
2143 if (eqbits < node->n_bits) { /* Mismatch, nothing more to be found. */
2144 /* Bit at offset 'match_len' differed. */
2145 return match_len + 1; /* Includes the first mismatching bit. */
2147 /* Full match, check if rules exist at this prefix length. */
2148 if (node->n_rules > 0) {
2149 be_set_bit_at(plens, match_len - 1);
2151 if (match_len >= n_bits) {
2152 return n_bits; /* Full prefix. */
2155 /* node == NULL. Full match so far, but we tried to follow an
2156 * non-existing branch. Need to exclude the other branch if it exists
2157 * (it does not if we were called on an empty trie or 'prev' is a leaf
2159 return !prev || trie_is_leaf(prev) ? match_len : match_len + 1;
2163 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
2164 union trie_prefix *plens)
2166 const struct mf_field *mf = trie->field;
2168 /* Check that current flow matches the prerequisites for the trie
2169 * field. Some match fields are used for multiple purposes, so we
2170 * must check that the trie is relevant for this flow. */
2171 if (mf_are_prereqs_ok(mf, flow)) {
2172 return trie_lookup_value(&trie->root,
2173 &((ovs_be32 *)flow)[mf->flow_be32ofs],
2174 &plens->be32, mf->n_bits);
2176 memset(plens, 0xff, sizeof *plens); /* All prefixes, no skipping. */
2177 return 0; /* Value not used in this case. */
2180 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
2181 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
2182 * 'miniflow_index' is not NULL. */
2184 minimask_get_prefix_len(const struct minimask *minimask,
2185 const struct mf_field *mf)
2187 unsigned int n_bits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
2188 uint8_t be32_ofs = mf->flow_be32ofs;
2189 uint8_t be32_end = be32_ofs + mf->n_bytes / 4;
2191 for (; be32_ofs < be32_end; ++be32_ofs) {
2192 uint32_t mask = ntohl(minimask_get_be32(minimask, be32_ofs));
2194 /* Validate mask, count the mask length. */
2197 return 0; /* No bits allowed after mask ended. */
2200 if (~mask & (~mask + 1)) {
2201 return 0; /* Mask not contiguous. */
2203 mask_tz = ctz32(mask);
2204 n_bits += 32 - mask_tz;
2212 * This is called only when mask prefix is known to be CIDR and non-zero.
2213 * Relies on the fact that the flow and mask have the same map, and since
2214 * the mask is CIDR, the storage for the flow field exists even if it
2215 * happened to be zeros.
2217 static const ovs_be32 *
2218 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
2220 size_t u64_ofs = mf->flow_be32ofs / 2;
2222 return (OVS_FORCE const ovs_be32 *)miniflow_get__(match->flow, u64_ofs)
2223 + (mf->flow_be32ofs & 1);
2226 /* Insert rule in to the prefix tree.
2227 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2230 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2232 trie_insert_prefix(&trie->root,
2233 minimatch_get_prefix(&rule->match, trie->field), mlen);
2237 trie_insert_prefix(rcu_trie_ptr *edge, const ovs_be32 *prefix, int mlen)
2239 struct trie_node *node;
2242 /* Walk the tree. */
2243 for (; (node = ovsrcu_get_protected(struct trie_node *, edge));
2244 edge = trie_next_edge(node, prefix, ofs)) {
2245 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2247 if (eqbits < node->n_bits) {
2248 /* Mismatch, new node needs to be inserted above. */
2249 int old_branch = get_bit_at(node->prefix, eqbits);
2250 struct trie_node *new_parent;
2252 new_parent = trie_branch_create(prefix, ofs - eqbits, eqbits,
2253 ofs == mlen ? 1 : 0);
2254 /* Copy the node to modify it. */
2255 node = trie_node_rcu_realloc(node);
2256 /* Adjust the new node for its new position in the tree. */
2257 node->prefix <<= eqbits;
2258 node->n_bits -= eqbits;
2259 ovsrcu_set_hidden(&new_parent->edges[old_branch], node);
2261 /* Check if need a new branch for the new rule. */
2263 ovsrcu_set_hidden(&new_parent->edges[!old_branch],
2264 trie_branch_create(prefix, ofs, mlen - ofs,
2267 ovsrcu_set(edge, new_parent); /* Publish changes. */
2270 /* Full match so far. */
2273 /* Full match at the current node, rule needs to be added here. */
2278 /* Must insert a new tree branch for the new rule. */
2279 ovsrcu_set(edge, trie_branch_create(prefix, ofs, mlen - ofs, 1));
2282 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2285 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2287 trie_remove_prefix(&trie->root,
2288 minimatch_get_prefix(&rule->match, trie->field), mlen);
2291 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2294 trie_remove_prefix(rcu_trie_ptr *root, const ovs_be32 *prefix, int mlen)
2296 struct trie_node *node;
2297 rcu_trie_ptr *edges[sizeof(union trie_prefix) * CHAR_BIT];
2298 int depth = 0, ofs = 0;
2300 /* Walk the tree. */
2301 for (edges[0] = root;
2302 (node = ovsrcu_get_protected(struct trie_node *, edges[depth]));
2303 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
2304 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2306 if (eqbits < node->n_bits) {
2307 /* Mismatch, nothing to be removed. This should never happen, as
2308 * only rules in the classifier are ever removed. */
2309 break; /* Log a warning. */
2311 /* Full match so far. */
2315 /* Full prefix match at the current node, remove rule here. */
2316 if (!node->n_rules) {
2317 break; /* Log a warning. */
2321 /* Check if can prune the tree. */
2322 while (!node->n_rules) {
2323 struct trie_node *next,
2324 *edge0 = ovsrcu_get_protected(struct trie_node *,
2326 *edge1 = ovsrcu_get_protected(struct trie_node *,
2329 if (edge0 && edge1) {
2330 break; /* A branching point, cannot prune. */
2333 /* Else have at most one child node, remove this node. */
2334 next = edge0 ? edge0 : edge1;
2337 if (node->n_bits + next->n_bits > TRIE_PREFIX_BITS) {
2338 break; /* Cannot combine. */
2340 next = trie_node_rcu_realloc(next); /* Modify. */
2342 /* Combine node with next. */
2343 next->prefix = node->prefix | next->prefix >> node->n_bits;
2344 next->n_bits += node->n_bits;
2346 /* Update the parent's edge. */
2347 ovsrcu_set(edges[depth], next); /* Publish changes. */
2348 trie_node_destroy(node);
2350 if (next || !depth) {
2351 /* Branch not pruned or at root, nothing more to do. */
2354 node = ovsrcu_get_protected(struct trie_node *,
2360 /* Cannot go deeper. This should never happen, since only rules
2361 * that actually exist in the classifier are ever removed. */
2362 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");
2366 #define CLS_MATCH_POISON (struct cls_match *)(UINTPTR_MAX / 0xf * 0xb)
2369 cls_match_free_cb(struct cls_match *rule)
2371 ovsrcu_set_hidden(&rule->next, CLS_MATCH_POISON);