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,
91 const struct cls_conjunction conj[], size_t n)
93 int count = count_1bits(rule->match.flow.map);
95 struct cls_match *cls_match
96 = xmalloc(sizeof *cls_match - sizeof cls_match->flow.inline_values
97 + MINIFLOW_VALUES_SIZE(count));
99 ovsrcu_init(&cls_match->next, NULL);
100 *CONST_CAST(const struct cls_rule **, &cls_match->cls_rule) = rule;
101 *CONST_CAST(int *, &cls_match->priority) = rule->priority;
102 *CONST_CAST(cls_version_t *, &cls_match->add_version) = rule->version;
103 atomic_init(&cls_match->remove_version, rule->version); /* Initially
105 miniflow_clone_inline(CONST_CAST(struct miniflow *, &cls_match->flow),
106 &rule->match.flow, count);
107 ovsrcu_set_hidden(&cls_match->conj_set,
108 cls_conjunction_set_alloc(cls_match, conj, n));
113 static struct cls_subtable *find_subtable(const struct classifier *cls,
114 const struct minimask *);
115 static struct cls_subtable *insert_subtable(struct classifier *cls,
116 const struct minimask *);
117 static void destroy_subtable(struct classifier *cls, struct cls_subtable *);
119 static const struct cls_match *find_match_wc(const struct cls_subtable *,
120 cls_version_t version,
123 unsigned int n_tries,
124 struct flow_wildcards *);
125 static struct cls_match *find_equal(const struct cls_subtable *,
126 const struct miniflow *, uint32_t hash);
128 /* Return the next visible (lower-priority) rule in the list. Multiple
129 * identical rules with the same priority may exist transitionally, but when
130 * versioning is used at most one of them is ever visible for lookups on any
131 * given 'version'. */
132 static inline const struct cls_match *
133 next_visible_rule_in_list(const struct cls_match *rule, cls_version_t version)
136 rule = cls_match_next(rule);
137 } while (rule && !cls_match_visible_in_version(rule, version));
142 static unsigned int minimask_get_prefix_len(const struct minimask *,
143 const struct mf_field *);
144 static void trie_init(struct classifier *cls, int trie_idx,
145 const struct mf_field *);
146 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
147 union mf_value *plens);
148 static unsigned int trie_lookup_value(const rcu_trie_ptr *,
149 const ovs_be32 value[], ovs_be32 plens[],
150 unsigned int value_bits);
151 static void trie_destroy(rcu_trie_ptr *);
152 static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
153 static void trie_insert_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
155 static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
156 static void trie_remove_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
158 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
159 unsigned int n_bits);
160 static bool mask_prefix_bits_set(const struct flow_wildcards *,
161 uint8_t be32ofs, unsigned int n_bits);
166 cls_rule_init__(struct cls_rule *rule, unsigned int priority,
167 cls_version_t version)
169 rculist_init(&rule->node);
170 *CONST_CAST(int *, &rule->priority) = priority;
171 *CONST_CAST(cls_version_t *, &rule->version) = version;
172 rule->cls_match = NULL;
175 /* Initializes 'rule' to match packets specified by 'match' at the given
176 * 'priority'. 'match' must satisfy the invariant described in the comment at
177 * the definition of struct match.
179 * The caller must eventually destroy 'rule' with cls_rule_destroy().
181 * Clients should not use priority INT_MIN. (OpenFlow uses priorities between
182 * 0 and UINT16_MAX, inclusive.) */
184 cls_rule_init(struct cls_rule *rule, const struct match *match, int priority,
185 cls_version_t version)
187 cls_rule_init__(rule, priority, version);
188 minimatch_init(CONST_CAST(struct minimatch *, &rule->match), match);
191 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
193 cls_rule_init_from_minimatch(struct cls_rule *rule,
194 const struct minimatch *match, int priority,
195 cls_version_t version)
197 cls_rule_init__(rule, priority, version);
198 minimatch_clone(CONST_CAST(struct minimatch *, &rule->match), match);
201 /* Initializes 'dst' as a copy of 'src', but with 'version'.
203 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
205 cls_rule_clone_in_version(struct cls_rule *dst, const struct cls_rule *src,
206 cls_version_t version)
208 cls_rule_init__(dst, src->priority, version);
209 minimatch_clone(CONST_CAST(struct minimatch *, &dst->match), &src->match);
212 /* Initializes 'dst' as a copy of 'src'.
214 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
216 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
218 cls_rule_clone_in_version(dst, src, src->version);
221 /* Initializes 'dst' with the data in 'src', destroying 'src'.
223 * 'src' must be a cls_rule NOT in a classifier.
225 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
227 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
229 cls_rule_init__(dst, src->priority, src->version);
230 minimatch_move(CONST_CAST(struct minimatch *, &dst->match),
231 CONST_CAST(struct minimatch *, &src->match));
234 /* Frees memory referenced by 'rule'. Doesn't free 'rule' itself (it's
235 * normally embedded into a larger structure).
237 * ('rule' must not currently be in a classifier.) */
239 cls_rule_destroy(struct cls_rule *rule)
240 OVS_NO_THREAD_SAFETY_ANALYSIS
242 ovs_assert(!rule->cls_match); /* Must not be in a classifier. */
244 /* Check that the rule has been properly removed from the classifier. */
245 ovs_assert(rule->node.prev == RCULIST_POISON
246 || rculist_is_empty(&rule->node));
247 rculist_poison__(&rule->node); /* Poisons also the next pointer. */
249 minimatch_destroy(CONST_CAST(struct minimatch *, &rule->match));
253 cls_rule_set_conjunctions(struct cls_rule *cr,
254 const struct cls_conjunction *conj, size_t n)
256 struct cls_match *match = cr->cls_match;
257 struct cls_conjunction_set *old
258 = ovsrcu_get_protected(struct cls_conjunction_set *, &match->conj_set);
259 struct cls_conjunction *old_conj = old ? old->conj : NULL;
260 unsigned int old_n = old ? old->n : 0;
262 if (old_n != n || (n && memcmp(old_conj, conj, n * sizeof *conj))) {
264 ovsrcu_postpone(free, old);
266 ovsrcu_set(&match->conj_set,
267 cls_conjunction_set_alloc(match, conj, n));
272 /* Returns true if 'a' and 'b' match the same packets at the same priority,
273 * false if they differ in some way. */
275 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
277 return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
280 /* Returns a hash value for 'rule', folding in 'basis'. */
282 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
284 return minimatch_hash(&rule->match, hash_int(rule->priority, basis));
287 /* Appends a string describing 'rule' to 's'. */
289 cls_rule_format(const struct cls_rule *rule, struct ds *s)
291 minimatch_format(&rule->match, s, rule->priority);
294 /* Returns true if 'rule' matches every packet, false otherwise. */
296 cls_rule_is_catchall(const struct cls_rule *rule)
298 return minimask_is_catchall(&rule->match.mask);
301 /* Makes rule invisible after 'version'. Once that version is made invisible
302 * (by changing the version parameter used in lookups), the rule should be
303 * actually removed via ovsrcu_postpone().
305 * 'rule_' must be in a classifier. */
307 cls_rule_make_invisible_in_version(const struct cls_rule *rule,
308 cls_version_t remove_version)
310 ovs_assert(remove_version >= rule->cls_match->add_version);
312 cls_match_set_remove_version(rule->cls_match, remove_version);
315 /* This undoes the change made by cls_rule_make_invisible_after_version().
317 * 'rule' must be in a classifier. */
319 cls_rule_restore_visibility(const struct cls_rule *rule)
321 cls_match_set_remove_version(rule->cls_match, CLS_NOT_REMOVED_VERSION);
324 /* Return true if 'rule' is visible in 'version'.
326 * 'rule' must be in a classifier. */
328 cls_rule_visible_in_version(const struct cls_rule *rule, cls_version_t version)
330 return cls_match_visible_in_version(rule->cls_match, version);
333 /* Initializes 'cls' as a classifier that initially contains no classification
336 classifier_init(struct classifier *cls, const uint8_t *flow_segments)
339 cmap_init(&cls->subtables_map);
340 pvector_init(&cls->subtables);
341 cmap_init(&cls->partitions);
342 cls->n_flow_segments = 0;
344 while (cls->n_flow_segments < CLS_MAX_INDICES
345 && *flow_segments < FLOW_U64S) {
346 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
350 for (int i = 0; i < CLS_MAX_TRIES; i++) {
351 trie_init(cls, i, NULL);
356 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
357 * caller's responsibility.
358 * May only be called after all the readers have been terminated. */
360 classifier_destroy(struct classifier *cls)
363 struct cls_partition *partition;
364 struct cls_subtable *subtable;
367 for (i = 0; i < cls->n_tries; i++) {
368 trie_destroy(&cls->tries[i].root);
371 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
372 destroy_subtable(cls, subtable);
374 cmap_destroy(&cls->subtables_map);
376 CMAP_FOR_EACH (partition, cmap_node, &cls->partitions) {
377 ovsrcu_postpone(free, partition);
379 cmap_destroy(&cls->partitions);
381 pvector_destroy(&cls->subtables);
385 /* Set the fields for which prefix lookup should be performed. */
387 classifier_set_prefix_fields(struct classifier *cls,
388 const enum mf_field_id *trie_fields,
389 unsigned int n_fields)
391 const struct mf_field * new_fields[CLS_MAX_TRIES];
392 struct mf_bitmap fields = MF_BITMAP_INITIALIZER;
394 bool changed = false;
396 for (i = 0; i < n_fields && n_tries < CLS_MAX_TRIES; i++) {
397 const struct mf_field *field = mf_from_id(trie_fields[i]);
398 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
399 /* Incompatible field. This is the only place where we
400 * enforce these requirements, but the rest of the trie code
401 * depends on the flow_be32ofs to be non-negative and the
402 * field length to be a multiple of 32 bits. */
406 if (bitmap_is_set(fields.bm, trie_fields[i])) {
407 /* Duplicate field, there is no need to build more than
408 * one index for any one field. */
411 bitmap_set1(fields.bm, trie_fields[i]);
413 new_fields[n_tries] = NULL;
414 if (n_tries >= cls->n_tries || field != cls->tries[n_tries].field) {
415 new_fields[n_tries] = field;
421 if (changed || n_tries < cls->n_tries) {
422 struct cls_subtable *subtable;
424 /* Trie configuration needs to change. Disable trie lookups
425 * for the tries that are changing and wait all the current readers
426 * with the old configuration to be done. */
428 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
429 for (i = 0; i < cls->n_tries; i++) {
430 if ((i < n_tries && new_fields[i]) || i >= n_tries) {
431 if (subtable->trie_plen[i]) {
432 subtable->trie_plen[i] = 0;
438 /* Synchronize if any readers were using tries. The readers may
439 * temporarily function without the trie lookup based optimizations. */
441 /* ovsrcu_synchronize() functions as a memory barrier, so it does
442 * not matter that subtable->trie_plen is not atomic. */
443 ovsrcu_synchronize();
446 /* Now set up the tries. */
447 for (i = 0; i < n_tries; i++) {
449 trie_init(cls, i, new_fields[i]);
452 /* Destroy the rest, if any. */
453 for (; i < cls->n_tries; i++) {
454 trie_init(cls, i, NULL);
457 cls->n_tries = n_tries;
461 return false; /* No change. */
465 trie_init(struct classifier *cls, int trie_idx, const struct mf_field *field)
467 struct cls_trie *trie = &cls->tries[trie_idx];
468 struct cls_subtable *subtable;
470 if (trie_idx < cls->n_tries) {
471 trie_destroy(&trie->root);
473 ovsrcu_set_hidden(&trie->root, NULL);
477 /* Add existing rules to the new trie. */
478 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
481 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
483 struct cls_match *head;
485 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
486 trie_insert(trie, head->cls_rule, plen);
489 /* Initialize subtable's prefix length on this field. This will
490 * allow readers to use the trie. */
491 atomic_thread_fence(memory_order_release);
492 subtable->trie_plen[trie_idx] = plen;
496 /* Returns true if 'cls' contains no classification rules, false otherwise.
497 * Checking the cmap requires no locking. */
499 classifier_is_empty(const struct classifier *cls)
501 return cmap_is_empty(&cls->subtables_map);
504 /* Returns the number of rules in 'cls'. */
506 classifier_count(const struct classifier *cls)
508 /* n_rules is an int, so in the presence of concurrent writers this will
509 * return either the old or a new value. */
514 hash_metadata(ovs_be64 metadata)
516 return hash_uint64((OVS_FORCE uint64_t) metadata);
519 static struct cls_partition *
520 find_partition(const struct classifier *cls, ovs_be64 metadata, uint32_t hash)
522 struct cls_partition *partition;
524 CMAP_FOR_EACH_WITH_HASH (partition, cmap_node, hash, &cls->partitions) {
525 if (partition->metadata == metadata) {
533 static struct cls_partition *
534 create_partition(struct classifier *cls, struct cls_subtable *subtable,
537 uint32_t hash = hash_metadata(metadata);
538 struct cls_partition *partition = find_partition(cls, metadata, hash);
540 partition = xmalloc(sizeof *partition);
541 partition->metadata = metadata;
543 tag_tracker_init(&partition->tracker);
544 cmap_insert(&cls->partitions, &partition->cmap_node, hash);
546 tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
550 static inline ovs_be32 minimatch_get_ports(const struct minimatch *match)
552 /* Could optimize to use the same map if needed for fast path. */
553 return MINIFLOW_GET_BE32(&match->flow, tp_src)
554 & MINIFLOW_GET_BE32(&match->mask.masks, tp_src);
558 subtable_replace_head_rule(struct classifier *cls OVS_UNUSED,
559 struct cls_subtable *subtable,
560 struct cls_match *head, struct cls_match *new,
561 uint32_t hash, uint32_t ihash[CLS_MAX_INDICES])
563 /* Rule's data is already in the tries. */
565 new->partition = head->partition; /* Steal partition, if any. */
566 head->partition = NULL;
568 for (int i = 0; i < subtable->n_indices; i++) {
569 cmap_replace(&subtable->indices[i], &head->index_nodes[i],
570 &new->index_nodes[i], ihash[i]);
572 cmap_replace(&subtable->rules, &head->cmap_node, &new->cmap_node, hash);
575 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
576 * must not modify or free it.
578 * If 'cls' already contains an identical rule (including wildcards, values of
579 * fixed fields, and priority), replaces the old rule by 'rule' and returns the
580 * rule that was replaced. The caller takes ownership of the returned rule and
581 * is thus responsible for destroying it with cls_rule_destroy(), after RCU
582 * grace period has passed (see ovsrcu_postpone()).
584 * Returns NULL if 'cls' does not contain a rule with an identical key, after
585 * inserting the new rule. In this case, no rules are displaced by the new
586 * rule, even rules that cannot have any effect because the new rule matches a
587 * superset of their flows and has higher priority.
589 const struct cls_rule *
590 classifier_replace(struct classifier *cls, const struct cls_rule *rule,
591 const struct cls_conjunction *conjs, size_t n_conjs)
593 struct cls_match *new;
594 struct cls_subtable *subtable;
595 uint32_t ihash[CLS_MAX_INDICES];
596 uint8_t prev_be64ofs = 0;
597 struct cls_match *head;
603 /* 'new' is initially invisible to lookups. */
604 new = cls_match_alloc(rule, conjs, n_conjs);
606 CONST_CAST(struct cls_rule *, rule)->cls_match = new;
608 subtable = find_subtable(cls, &rule->match.mask);
610 subtable = insert_subtable(cls, &rule->match.mask);
613 /* Compute hashes in segments. */
615 for (i = 0; i < subtable->n_indices; i++) {
616 ihash[i] = minimatch_hash_range(&rule->match, prev_be64ofs,
617 subtable->index_ofs[i], &basis);
618 prev_be64ofs = subtable->index_ofs[i];
620 hash = minimatch_hash_range(&rule->match, prev_be64ofs, FLOW_U64S, &basis);
622 head = find_equal(subtable, &rule->match.flow, hash);
624 /* Add rule to tries.
626 * Concurrent readers might miss seeing the rule until this update,
627 * which might require being fixed up by revalidation later. */
628 for (i = 0; i < cls->n_tries; i++) {
629 if (subtable->trie_plen[i]) {
630 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
634 /* Add rule to ports trie. */
635 if (subtable->ports_mask_len) {
636 /* We mask the value to be inserted to always have the wildcarded
637 * bits in known (zero) state, so we can include them in comparison
638 * and they will always match (== their original value does not
640 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
642 trie_insert_prefix(&subtable->ports_trie, &masked_ports,
643 subtable->ports_mask_len);
646 /* Add rule to partitions.
648 * Concurrent readers might miss seeing the rule until this update,
649 * which might require being fixed up by revalidation later. */
650 new->partition = NULL;
651 if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
652 ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
654 new->partition = create_partition(cls, subtable, metadata);
657 /* Add new node to segment indices.
659 * Readers may find the rule in the indices before the rule is visible
660 * in the subtables 'rules' map. This may result in us losing the
661 * opportunity to quit lookups earlier, resulting in sub-optimal
662 * wildcarding. This will be fixed later by revalidation (always
663 * scheduled after flow table changes). */
664 for (i = 0; i < subtable->n_indices; i++) {
665 cmap_insert(&subtable->indices[i], &new->index_nodes[i], ihash[i]);
667 n_rules = cmap_insert(&subtable->rules, &new->cmap_node, hash);
668 } else { /* Equal rules exist in the classifier already. */
669 struct cls_match *prev, *iter;
671 /* Scan the list for the insertion point that will keep the list in
672 * order of decreasing priority. Insert after rules marked invisible
673 * in any version of the same priority. */
674 FOR_EACH_RULE_IN_LIST_PROTECTED (iter, prev, head) {
675 if (rule->priority > iter->priority
676 || (rule->priority == iter->priority
677 && !cls_match_is_eventually_invisible(iter))) {
682 /* Replace 'iter' with 'new' or insert 'new' between 'prev' and
685 struct cls_rule *old;
687 if (rule->priority == iter->priority) {
688 cls_match_replace(prev, iter, new);
689 old = CONST_CAST(struct cls_rule *, iter->cls_rule);
691 cls_match_insert(prev, iter, new);
695 /* Replace the existing head in data structures, if rule is the new
698 subtable_replace_head_rule(cls, subtable, head, new, hash,
703 struct cls_conjunction_set *conj_set;
705 conj_set = ovsrcu_get_protected(struct cls_conjunction_set *,
708 ovsrcu_postpone(free, conj_set);
711 ovsrcu_postpone(cls_match_free_cb, iter);
712 old->cls_match = NULL;
714 /* No change in subtable's max priority or max count. */
716 /* Make 'new' visible to lookups in the appropriate version. */
717 cls_match_set_remove_version(new, CLS_NOT_REMOVED_VERSION);
719 /* Make rule visible to iterators (immediately). */
720 rculist_replace(CONST_CAST(struct rculist *, &rule->node),
723 /* Return displaced rule. Caller is responsible for keeping it
724 * around until all threads quiesce. */
728 /* 'new' is new node after 'prev' */
729 cls_match_insert(prev, iter, new);
733 /* Make 'new' visible to lookups in the appropriate version. */
734 cls_match_set_remove_version(new, CLS_NOT_REMOVED_VERSION);
736 /* Make rule visible to iterators (immediately). */
737 rculist_push_back(&subtable->rules_list,
738 CONST_CAST(struct rculist *, &rule->node));
740 /* Rule was added, not replaced. Update 'subtable's 'max_priority' and
741 * 'max_count', if necessary.
743 * The rule was already inserted, but concurrent readers may not see the
744 * rule yet as the subtables vector is not updated yet. This will have to
745 * be fixed by revalidation later. */
747 subtable->max_priority = rule->priority;
748 subtable->max_count = 1;
749 pvector_insert(&cls->subtables, subtable, rule->priority);
750 } else if (rule->priority == subtable->max_priority) {
751 ++subtable->max_count;
752 } else if (rule->priority > subtable->max_priority) {
753 subtable->max_priority = rule->priority;
754 subtable->max_count = 1;
755 pvector_change_priority(&cls->subtables, subtable, rule->priority);
758 /* Nothing was replaced. */
762 pvector_publish(&cls->subtables);
768 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
769 * must not modify or free it.
771 * 'cls' must not contain an identical rule (including wildcards, values of
772 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
775 classifier_insert(struct classifier *cls, const struct cls_rule *rule,
776 const struct cls_conjunction conj[], size_t n_conj)
778 const struct cls_rule *displaced_rule
779 = classifier_replace(cls, rule, conj, n_conj);
780 ovs_assert(!displaced_rule);
783 /* Removes 'rule' from 'cls'. It is the caller's responsibility to destroy
784 * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
785 * resides, etc., as necessary.
787 * Does nothing if 'rule' has been already removed, or was never inserted.
789 * Returns the removed rule, or NULL, if it was already removed.
791 const struct cls_rule *
792 classifier_remove(struct classifier *cls, const struct cls_rule *cls_rule)
794 struct cls_match *rule, *prev, *next, *head;
795 struct cls_partition *partition;
796 struct cls_conjunction_set *conj_set;
797 struct cls_subtable *subtable;
799 uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
800 uint8_t prev_be64ofs = 0;
803 rule = cls_rule->cls_match;
807 /* Mark as removed. */
808 CONST_CAST(struct cls_rule *, cls_rule)->cls_match = NULL;
810 /* Remove 'cls_rule' from the subtable's rules list. */
811 rculist_remove(CONST_CAST(struct rculist *, &cls_rule->node));
813 subtable = find_subtable(cls, &cls_rule->match.mask);
814 ovs_assert(subtable);
816 for (i = 0; i < subtable->n_indices; i++) {
817 ihash[i] = minimatch_hash_range(&cls_rule->match, prev_be64ofs,
818 subtable->index_ofs[i], &basis);
819 prev_be64ofs = subtable->index_ofs[i];
821 hash = minimatch_hash_range(&cls_rule->match, prev_be64ofs, FLOW_U64S,
824 head = find_equal(subtable, &cls_rule->match.flow, hash);
826 /* Check if the rule is not the head rule. */
828 struct cls_match *iter;
830 /* Not the head rule, but potentially one with the same priority. */
831 /* Remove from the list of equal rules. */
832 FOR_EACH_RULE_IN_LIST_PROTECTED (iter, prev, head) {
837 ovs_assert(iter == rule);
839 cls_match_remove(prev, rule);
844 /* 'rule' is the head rule. Check if there is another rule to
845 * replace 'rule' in the data structures. */
846 next = cls_match_next_protected(rule);
848 subtable_replace_head_rule(cls, subtable, rule, next, hash, ihash);
852 /* 'rule' is last of the kind in the classifier, must remove from all the
853 * data structures. */
855 if (subtable->ports_mask_len) {
856 ovs_be32 masked_ports = minimatch_get_ports(&cls_rule->match);
858 trie_remove_prefix(&subtable->ports_trie,
859 &masked_ports, subtable->ports_mask_len);
861 for (i = 0; i < cls->n_tries; i++) {
862 if (subtable->trie_plen[i]) {
863 trie_remove(&cls->tries[i], cls_rule, subtable->trie_plen[i]);
867 /* Remove rule node from indices. */
868 for (i = 0; i < subtable->n_indices; i++) {
869 cmap_remove(&subtable->indices[i], &rule->index_nodes[i], ihash[i]);
871 n_rules = cmap_remove(&subtable->rules, &rule->cmap_node, hash);
873 partition = rule->partition;
875 tag_tracker_subtract(&partition->tracker, &partition->tags,
877 if (!partition->tags) {
878 cmap_remove(&cls->partitions, &partition->cmap_node,
879 hash_metadata(partition->metadata));
880 ovsrcu_postpone(free, partition);
885 destroy_subtable(cls, subtable);
888 if (subtable->max_priority == rule->priority
889 && --subtable->max_count == 0) {
890 /* Find the new 'max_priority' and 'max_count'. */
891 int max_priority = INT_MIN;
892 struct cls_match *head;
894 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
895 if (head->priority > max_priority) {
896 max_priority = head->priority;
897 subtable->max_count = 1;
898 } else if (head->priority == max_priority) {
899 ++subtable->max_count;
902 subtable->max_priority = max_priority;
903 pvector_change_priority(&cls->subtables, subtable, max_priority);
908 pvector_publish(&cls->subtables);
912 conj_set = ovsrcu_get_protected(struct cls_conjunction_set *,
915 ovsrcu_postpone(free, conj_set);
917 ovsrcu_postpone(cls_match_free_cb, rule);
923 /* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
924 * subtables which have a prefix match on the trie field, but whose prefix
925 * length is not indicated in 'match_plens'. For example, a subtable that
926 * has a 8-bit trie field prefix match can be skipped if
927 * !be_get_bit_at(&match_plens, 8 - 1). If skipped, 'maskbits' prefix bits
928 * must be unwildcarded to make datapath flow only match packets it should. */
930 const struct cls_trie *trie;
931 bool lookup_done; /* Status of the lookup. */
932 uint8_t be32ofs; /* U32 offset of the field in question. */
933 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
934 union mf_value match_plens; /* Bitmask of prefix lengths with possible
939 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
942 ctx->be32ofs = trie->field->flow_be32ofs;
943 ctx->lookup_done = false;
946 struct conjunctive_match {
947 struct hmap_node hmap_node;
952 static struct conjunctive_match *
953 find_conjunctive_match__(struct hmap *matches, uint64_t id, uint32_t hash)
955 struct conjunctive_match *m;
957 HMAP_FOR_EACH_IN_BUCKET (m, hmap_node, hash, matches) {
966 find_conjunctive_match(const struct cls_conjunction_set *set,
967 unsigned int max_n_clauses, struct hmap *matches,
968 struct conjunctive_match *cm_stubs, size_t n_cm_stubs,
971 const struct cls_conjunction *c;
973 if (max_n_clauses < set->min_n_clauses) {
977 for (c = set->conj; c < &set->conj[set->n]; c++) {
978 struct conjunctive_match *cm;
981 if (c->n_clauses > max_n_clauses) {
985 hash = hash_int(c->id, 0);
986 cm = find_conjunctive_match__(matches, c->id, hash);
988 size_t n = hmap_count(matches);
990 cm = n < n_cm_stubs ? &cm_stubs[n] : xmalloc(sizeof *cm);
991 hmap_insert(matches, &cm->hmap_node, hash);
993 cm->clauses = UINT64_MAX << (c->n_clauses & 63);
995 cm->clauses |= UINT64_C(1) << c->clause;
996 if (cm->clauses == UINT64_MAX) {
1005 free_conjunctive_matches(struct hmap *matches,
1006 struct conjunctive_match *cm_stubs, size_t n_cm_stubs)
1008 if (hmap_count(matches) > n_cm_stubs) {
1009 struct conjunctive_match *cm, *next;
1011 HMAP_FOR_EACH_SAFE (cm, next, hmap_node, matches) {
1012 if (!(cm >= cm_stubs && cm < &cm_stubs[n_cm_stubs])) {
1017 hmap_destroy(matches);
1020 /* Like classifier_lookup(), except that support for conjunctive matches can be
1021 * configured with 'allow_conjunctive_matches'. That feature is not exposed
1022 * externally because turning off conjunctive matches is only useful to avoid
1023 * recursion within this function itself.
1025 * 'flow' is non-const to allow for temporary modifications during the lookup.
1026 * Any changes are restored before returning. */
1027 static const struct cls_rule *
1028 classifier_lookup__(const struct classifier *cls, cls_version_t version,
1029 struct flow *flow, struct flow_wildcards *wc,
1030 bool allow_conjunctive_matches)
1032 const struct cls_partition *partition;
1033 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
1034 const struct cls_match *match;
1037 /* Highest-priority flow in 'cls' that certainly matches 'flow'. */
1038 const struct cls_match *hard = NULL;
1039 int hard_pri = INT_MIN; /* hard ? hard->priority : INT_MIN. */
1041 /* Highest-priority conjunctive flows in 'cls' matching 'flow'. Since
1042 * these are (components of) conjunctive flows, we can only know whether
1043 * the full conjunctive flow matches after seeing multiple of them. Thus,
1044 * we refer to these as "soft matches". */
1045 struct cls_conjunction_set *soft_stub[64];
1046 struct cls_conjunction_set **soft = soft_stub;
1047 size_t n_soft = 0, allocated_soft = ARRAY_SIZE(soft_stub);
1048 int soft_pri = INT_MIN; /* n_soft ? MAX(soft[*]->priority) : INT_MIN. */
1050 /* Synchronize for cls->n_tries and subtable->trie_plen. They can change
1051 * when table configuration changes, which happens typically only on
1053 atomic_thread_fence(memory_order_acquire);
1055 /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
1056 * then 'flow' cannot possibly match in 'subtable':
1058 * - If flow->metadata maps to a given 'partition', then we can use
1059 * 'tags' for 'partition->tags'.
1061 * - If flow->metadata has no partition, then no rule in 'cls' has an
1062 * exact-match for flow->metadata. That means that we don't need to
1063 * search any subtable that includes flow->metadata in its mask.
1065 * In either case, we always need to search any cls_subtables that do not
1066 * include flow->metadata in its mask. One way to do that would be to
1067 * check the "cls_subtable"s explicitly for that, but that would require an
1068 * extra branch per subtable. Instead, we mark such a cls_subtable's
1069 * 'tags' as TAG_ALL and make sure that 'tags' is never empty. This means
1070 * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
1071 * need a special case.
1073 partition = (cmap_is_empty(&cls->partitions)
1075 : find_partition(cls, flow->metadata,
1076 hash_metadata(flow->metadata)));
1077 tags = partition ? partition->tags : TAG_ARBITRARY;
1079 /* Initialize trie contexts for find_match_wc(). */
1080 for (int i = 0; i < cls->n_tries; i++) {
1081 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
1085 struct cls_subtable *subtable;
1086 PVECTOR_FOR_EACH_PRIORITY (subtable, hard_pri, 2, sizeof *subtable,
1088 struct cls_conjunction_set *conj_set;
1090 /* Skip subtables not in our partition. */
1091 if (!tag_intersects(tags, subtable->tag)) {
1095 /* Skip subtables with no match, or where the match is lower-priority
1096 * than some certain match we've already found. */
1097 match = find_match_wc(subtable, version, flow, trie_ctx, cls->n_tries,
1099 if (!match || match->priority <= hard_pri) {
1103 conj_set = ovsrcu_get(struct cls_conjunction_set *, &match->conj_set);
1105 /* 'match' isn't part of a conjunctive match. It's the best
1106 * certain match we've got so far, since we know that it's
1107 * higher-priority than hard_pri.
1109 * (There might be a higher-priority conjunctive match. We can't
1112 hard_pri = hard->priority;
1113 } else if (allow_conjunctive_matches) {
1114 /* 'match' is part of a conjunctive match. Add it to the list. */
1115 if (OVS_UNLIKELY(n_soft >= allocated_soft)) {
1116 struct cls_conjunction_set **old_soft = soft;
1118 allocated_soft *= 2;
1119 soft = xmalloc(allocated_soft * sizeof *soft);
1120 memcpy(soft, old_soft, n_soft * sizeof *soft);
1121 if (old_soft != soft_stub) {
1125 soft[n_soft++] = conj_set;
1127 /* Keep track of the highest-priority soft match. */
1128 if (soft_pri < match->priority) {
1129 soft_pri = match->priority;
1134 /* In the common case, at this point we have no soft matches and we can
1135 * return immediately. (We do the same thing if we have potential soft
1136 * matches but none of them are higher-priority than our hard match.) */
1137 if (hard_pri >= soft_pri) {
1138 if (soft != soft_stub) {
1141 return hard ? hard->cls_rule : NULL;
1144 /* At this point, we have some soft matches. We might also have a hard
1145 * match; if so, its priority is lower than the highest-priority soft
1150 * Check whether soft matches are real matches. */
1152 /* Delete soft matches that are null. This only happens in second and
1153 * subsequent iterations of the soft match loop, when we drop back from
1154 * a high-priority soft match to a lower-priority one.
1156 * Also, delete soft matches whose priority is less than or equal to
1157 * the hard match's priority. In the first iteration of the soft
1158 * match, these can be in 'soft' because the earlier main loop found
1159 * the soft match before the hard match. In second and later iteration
1160 * of the soft match loop, these can be in 'soft' because we dropped
1161 * back from a high-priority soft match to a lower-priority soft match.
1163 * It is tempting to delete soft matches that cannot be satisfied
1164 * because there are fewer soft matches than required to satisfy any of
1165 * their conjunctions, but we cannot do that because there might be
1166 * lower priority soft or hard matches with otherwise identical
1167 * matches. (We could special case those here, but there's no
1168 * need--we'll do so at the bottom of the soft match loop anyway and
1169 * this duplicates less code.)
1171 * It's also tempting to break out of the soft match loop if 'n_soft ==
1172 * 1' but that would also miss lower-priority hard matches. We could
1173 * special case that also but again there's no need. */
1174 for (int i = 0; i < n_soft; ) {
1175 if (!soft[i] || soft[i]->priority <= hard_pri) {
1176 soft[i] = soft[--n_soft];
1185 /* Find the highest priority among the soft matches. (We know this
1186 * must be higher than the hard match's priority; otherwise we would
1187 * have deleted all of the soft matches in the previous loop.) Count
1188 * the number of soft matches that have that priority. */
1191 for (int i = 0; i < n_soft; i++) {
1192 if (soft[i]->priority > soft_pri) {
1193 soft_pri = soft[i]->priority;
1195 } else if (soft[i]->priority == soft_pri) {
1199 ovs_assert(soft_pri > hard_pri);
1201 /* Look for a real match among the highest-priority soft matches.
1203 * It's unusual to have many conjunctive matches, so we use stubs to
1204 * avoid calling malloc() in the common case. An hmap has a built-in
1205 * stub for up to 2 hmap_nodes; possibly, we would benefit a variant
1206 * with a bigger stub. */
1207 struct conjunctive_match cm_stubs[16];
1208 struct hmap matches;
1210 hmap_init(&matches);
1211 for (int i = 0; i < n_soft; i++) {
1214 if (soft[i]->priority == soft_pri
1215 && find_conjunctive_match(soft[i], n_soft_pri, &matches,
1216 cm_stubs, ARRAY_SIZE(cm_stubs),
1218 uint32_t saved_conj_id = flow->conj_id;
1219 const struct cls_rule *rule;
1222 rule = classifier_lookup__(cls, version, flow, wc, false);
1223 flow->conj_id = saved_conj_id;
1226 free_conjunctive_matches(&matches,
1227 cm_stubs, ARRAY_SIZE(cm_stubs));
1228 if (soft != soft_stub) {
1235 free_conjunctive_matches(&matches, cm_stubs, ARRAY_SIZE(cm_stubs));
1237 /* There's no real match among the highest-priority soft matches.
1238 * However, if any of those soft matches has a lower-priority but
1239 * otherwise identical flow match, then we need to consider those for
1240 * soft or hard matches.
1242 * The next iteration of the soft match loop will delete any null
1243 * pointers we put into 'soft' (and some others too). */
1244 for (int i = 0; i < n_soft; i++) {
1245 if (soft[i]->priority != soft_pri) {
1249 /* Find next-lower-priority flow with identical flow match. */
1250 match = next_visible_rule_in_list(soft[i]->match, version);
1252 soft[i] = ovsrcu_get(struct cls_conjunction_set *,
1255 /* The flow is a hard match; don't treat as a soft
1257 if (match->priority > hard_pri) {
1259 hard_pri = hard->priority;
1263 /* No such lower-priority flow (probably the common case). */
1269 if (soft != soft_stub) {
1272 return hard ? hard->cls_rule : NULL;
1275 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow' and
1276 * that is visible in 'version'. Returns a null pointer if no rules in 'cls'
1277 * match 'flow'. If multiple rules of equal priority match 'flow', returns one
1280 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
1281 * set of bits that were significant in the lookup. At some point
1282 * earlier, 'wc' should have been initialized (e.g., by
1283 * flow_wildcards_init_catchall()).
1285 * 'flow' is non-const to allow for temporary modifications during the lookup.
1286 * Any changes are restored before returning. */
1287 const struct cls_rule *
1288 classifier_lookup(const struct classifier *cls, cls_version_t version,
1289 struct flow *flow, struct flow_wildcards *wc)
1291 return classifier_lookup__(cls, version, flow, wc, true);
1294 /* Finds and returns a rule in 'cls' with exactly the same priority and
1295 * matching criteria as 'target', and that is visible in 'target->version.
1296 * Only one such rule may ever exist. Returns a null pointer if 'cls' doesn't
1297 * contain an exact match. */
1298 const struct cls_rule *
1299 classifier_find_rule_exactly(const struct classifier *cls,
1300 const struct cls_rule *target)
1302 const struct cls_match *head, *rule;
1303 const struct cls_subtable *subtable;
1305 subtable = find_subtable(cls, &target->match.mask);
1310 head = find_equal(subtable, &target->match.flow,
1311 miniflow_hash_in_minimask(&target->match.flow,
1312 &target->match.mask, 0));
1316 CLS_MATCH_FOR_EACH (rule, head) {
1317 if (rule->priority < target->priority) {
1318 break; /* Not found. */
1320 if (rule->priority == target->priority
1321 && cls_match_visible_in_version(rule, target->version)) {
1322 return rule->cls_rule;
1328 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
1329 * same matching criteria as 'target', and that is visible in 'version'.
1330 * Returns a null pointer if 'cls' doesn't contain an exact match visible in
1332 const struct cls_rule *
1333 classifier_find_match_exactly(const struct classifier *cls,
1334 const struct match *target, int priority,
1335 cls_version_t version)
1337 const struct cls_rule *retval;
1340 cls_rule_init(&cr, target, priority, version);
1341 retval = classifier_find_rule_exactly(cls, &cr);
1342 cls_rule_destroy(&cr);
1347 /* Checks if 'target' would overlap any other rule in 'cls'. Two rules are
1348 * considered to overlap if both rules have the same priority and a packet
1349 * could match both, and if both rules are visible in the same version.
1351 * A trivial example of overlapping rules is two rules matching disjoint sets
1352 * of fields. E.g., if one rule matches only on port number, while another only
1353 * on dl_type, any packet from that specific port and with that specific
1354 * dl_type could match both, if the rules also have the same priority. */
1356 classifier_rule_overlaps(const struct classifier *cls,
1357 const struct cls_rule *target)
1359 struct cls_subtable *subtable;
1361 /* Iterate subtables in the descending max priority order. */
1362 PVECTOR_FOR_EACH_PRIORITY (subtable, target->priority - 1, 2,
1363 sizeof(struct cls_subtable), &cls->subtables) {
1364 uint64_t storage[FLOW_U64S];
1365 struct minimask mask;
1366 const struct cls_rule *rule;
1368 minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
1370 RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
1371 if (rule->priority == target->priority
1372 && miniflow_equal_in_minimask(&target->match.flow,
1373 &rule->match.flow, &mask)
1374 && cls_match_visible_in_version(rule->cls_match,
1383 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
1384 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
1385 * function returns true if, for every field:
1387 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
1390 * - 'criteria' wildcards the field,
1392 * Conversely, 'rule' does not match 'criteria' and this function returns false
1393 * if, for at least one field:
1395 * - 'criteria' and 'rule' specify different values for the field, or
1397 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
1399 * Equivalently, the truth table for whether a field matches is:
1404 * r +---------+---------+
1405 * i wild | yes | yes |
1407 * e +---------+---------+
1408 * r exact | no |if values|
1410 * a +---------+---------+
1412 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
1413 * commands and by OpenFlow 1.0 aggregate and flow stats.
1415 * Ignores rule->priority. */
1417 cls_rule_is_loose_match(const struct cls_rule *rule,
1418 const struct minimatch *criteria)
1420 return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
1421 && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
1427 /* Rule may only match a target if it is visible in target's version. For NULL
1428 * target we only return rules that are not invisible in any version. */
1430 rule_matches(const struct cls_rule *rule, const struct cls_rule *target)
1432 /* Iterators never see duplicate rules with the same priority. */
1434 ? (miniflow_equal_in_minimask(&rule->match.flow, &target->match.flow,
1435 &target->match.mask)
1436 && cls_match_visible_in_version(rule->cls_match, target->version))
1437 : !cls_match_is_eventually_invisible(rule->cls_match);
1440 static const struct cls_rule *
1441 search_subtable(const struct cls_subtable *subtable,
1442 struct cls_cursor *cursor)
1445 || !minimask_has_extra(&subtable->mask, &cursor->target->match.mask)) {
1446 const struct cls_rule *rule;
1448 RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
1449 if (rule_matches(rule, cursor->target)) {
1457 /* Initializes 'cursor' for iterating through rules in 'cls', and returns the
1458 * first matching cls_rule via '*pnode', or NULL if there are no matches.
1460 * - If 'target' is null, or if the 'target' is a catchall target and the
1461 * target's version is CLS_MAX_VERSION, the cursor will visit every rule
1462 * in 'cls' that is not invisible in any version.
1464 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1465 * such that cls_rule_is_loose_match(rule, target) returns true and that
1466 * the rule is visible in 'target->version'.
1468 * Ignores target->priority. */
1470 cls_cursor_start(const struct classifier *cls, const struct cls_rule *target)
1472 struct cls_cursor cursor;
1473 struct cls_subtable *subtable;
1476 cursor.target = target && (!cls_rule_is_catchall(target)
1477 || target->version != CLS_MAX_VERSION)
1481 /* Find first rule. */
1482 PVECTOR_CURSOR_FOR_EACH (subtable, &cursor.subtables,
1483 &cursor.cls->subtables) {
1484 const struct cls_rule *rule = search_subtable(subtable, &cursor);
1487 cursor.subtable = subtable;
1496 static const struct cls_rule *
1497 cls_cursor_next(struct cls_cursor *cursor)
1499 const struct cls_rule *rule;
1500 const struct cls_subtable *subtable;
1502 rule = cursor->rule;
1503 subtable = cursor->subtable;
1504 RCULIST_FOR_EACH_CONTINUE (rule, node, &subtable->rules_list) {
1505 if (rule_matches(rule, cursor->target)) {
1510 PVECTOR_CURSOR_FOR_EACH_CONTINUE (subtable, &cursor->subtables) {
1511 rule = search_subtable(subtable, cursor);
1513 cursor->subtable = subtable;
1521 /* Sets 'cursor->rule' to the next matching cls_rule in 'cursor''s iteration,
1522 * or to null if all matching rules have been visited. */
1524 cls_cursor_advance(struct cls_cursor *cursor)
1526 cursor->rule = cls_cursor_next(cursor);
1529 static struct cls_subtable *
1530 find_subtable(const struct classifier *cls, const struct minimask *mask)
1532 struct cls_subtable *subtable;
1534 CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, minimask_hash(mask, 0),
1535 &cls->subtables_map) {
1536 if (minimask_equal(mask, &subtable->mask)) {
1543 /* The new subtable will be visible to the readers only after this. */
1544 static struct cls_subtable *
1545 insert_subtable(struct classifier *cls, const struct minimask *mask)
1547 uint32_t hash = minimask_hash(mask, 0);
1548 struct cls_subtable *subtable;
1550 struct flow_wildcards old, new;
1552 int count = count_1bits(mask->masks.map);
1554 subtable = xzalloc(sizeof *subtable - sizeof mask->masks.inline_values
1555 + MINIFLOW_VALUES_SIZE(count));
1556 cmap_init(&subtable->rules);
1557 miniflow_clone_inline(CONST_CAST(struct miniflow *, &subtable->mask.masks),
1558 &mask->masks, count);
1560 /* Init indices for segmented lookup, if any. */
1561 flow_wildcards_init_catchall(&new);
1564 for (i = 0; i < cls->n_flow_segments; i++) {
1565 flow_wildcards_fold_minimask_range(&new, mask, prev,
1566 cls->flow_segments[i]);
1567 /* Add an index if it adds mask bits. */
1568 if (!flow_wildcards_equal(&new, &old)) {
1569 cmap_init(&subtable->indices[index]);
1570 *CONST_CAST(uint8_t *, &subtable->index_ofs[index])
1571 = cls->flow_segments[i];
1575 prev = cls->flow_segments[i];
1577 /* Check if the rest of the subtable's mask adds any bits,
1578 * and remove the last index if it doesn't. */
1580 flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U64S);
1581 if (flow_wildcards_equal(&new, &old)) {
1583 *CONST_CAST(uint8_t *, &subtable->index_ofs[index]) = 0;
1584 cmap_destroy(&subtable->indices[index]);
1587 *CONST_CAST(uint8_t *, &subtable->n_indices) = index;
1589 *CONST_CAST(tag_type *, &subtable->tag) =
1590 (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1591 ? tag_create_deterministic(hash)
1594 for (i = 0; i < cls->n_tries; i++) {
1595 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1596 cls->tries[i].field);
1600 ovsrcu_set_hidden(&subtable->ports_trie, NULL);
1601 *CONST_CAST(int *, &subtable->ports_mask_len)
1602 = 32 - ctz32(ntohl(MINIFLOW_GET_BE32(&mask->masks, tp_src)));
1604 /* List of rules. */
1605 rculist_init(&subtable->rules_list);
1607 cmap_insert(&cls->subtables_map, &subtable->cmap_node, hash);
1612 /* RCU readers may still access the subtable before it is actually freed. */
1614 destroy_subtable(struct classifier *cls, struct cls_subtable *subtable)
1618 pvector_remove(&cls->subtables, subtable);
1619 cmap_remove(&cls->subtables_map, &subtable->cmap_node,
1620 minimask_hash(&subtable->mask, 0));
1622 ovs_assert(ovsrcu_get_protected(struct trie_node *, &subtable->ports_trie)
1624 ovs_assert(cmap_is_empty(&subtable->rules));
1625 ovs_assert(rculist_is_empty(&subtable->rules_list));
1627 for (i = 0; i < subtable->n_indices; i++) {
1628 cmap_destroy(&subtable->indices[i]);
1630 cmap_destroy(&subtable->rules);
1631 ovsrcu_postpone(free, subtable);
1639 static unsigned int be_get_bit_at(const ovs_be32 value[], unsigned int ofs);
1641 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1642 * lookup results. */
1644 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1645 const unsigned int field_plen[CLS_MAX_TRIES],
1646 const struct range ofs, const struct flow *flow,
1647 struct flow_wildcards *wc)
1651 /* Check if we could avoid fully unwildcarding the next level of
1652 * fields using the prefix tries. The trie checks are done only as
1653 * needed to avoid folding in additional bits to the wildcards mask. */
1654 for (j = 0; j < n_tries; j++) {
1655 /* Is the trie field relevant for this subtable? */
1656 if (field_plen[j]) {
1657 struct trie_ctx *ctx = &trie_ctx[j];
1658 uint8_t be32ofs = ctx->be32ofs;
1659 uint8_t be64ofs = be32ofs / 2;
1661 /* Is the trie field within the current range of fields? */
1662 if (be64ofs >= ofs.start && be64ofs < ofs.end) {
1663 /* On-demand trie lookup. */
1664 if (!ctx->lookup_done) {
1665 memset(&ctx->match_plens, 0, sizeof ctx->match_plens);
1666 ctx->maskbits = trie_lookup(ctx->trie, flow,
1668 ctx->lookup_done = true;
1670 /* Possible to skip the rest of the subtable if subtable's
1671 * prefix on the field is not included in the lookup result. */
1672 if (!be_get_bit_at(&ctx->match_plens.be32, field_plen[j] - 1)) {
1673 /* We want the trie lookup to never result in unwildcarding
1674 * any bits that would not be unwildcarded otherwise.
1675 * Since the trie is shared by the whole classifier, it is
1676 * possible that the 'maskbits' contain bits that are
1677 * irrelevant for the partition relevant for the current
1678 * packet. Hence the checks below. */
1680 /* Check that the trie result will not unwildcard more bits
1681 * than this subtable would otherwise. */
1682 if (ctx->maskbits <= field_plen[j]) {
1683 /* Unwildcard the bits and skip the rest. */
1684 mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1685 /* Note: Prerequisite already unwildcarded, as the only
1686 * prerequisite of the supported trie lookup fields is
1687 * the ethertype, which is always unwildcarded. */
1690 /* Can skip if the field is already unwildcarded. */
1691 if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1701 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1702 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1703 * value has the correct value in 'target'.
1705 * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
1706 * target, mask) but this is faster because of the invariant that
1707 * flow->map and mask->masks.map are the same, and that this version
1708 * takes the 'wc'. */
1710 miniflow_and_mask_matches_flow(const struct miniflow *flow,
1711 const struct minimask *mask,
1712 const struct flow *target)
1714 const uint64_t *flowp = miniflow_get_values(flow);
1715 const uint64_t *maskp = miniflow_get_values(&mask->masks);
1718 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1719 uint64_t diff = (*flowp++ ^ flow_u64_value(target, idx)) & *maskp++;
1729 static inline const struct cls_match *
1730 find_match(const struct cls_subtable *subtable, cls_version_t version,
1731 const struct flow *flow, uint32_t hash)
1733 const struct cls_match *head, *rule;
1735 CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1736 if (OVS_LIKELY(miniflow_and_mask_matches_flow(&head->flow,
1739 /* Return highest priority rule that is visible. */
1740 CLS_MATCH_FOR_EACH (rule, head) {
1741 if (OVS_LIKELY(cls_match_visible_in_version(rule, version))) {
1751 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1752 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1753 * value has the correct value in 'target'.
1755 * This function is equivalent to miniflow_and_mask_matches_flow() but this
1756 * version fills in the mask bits in 'wc'. */
1758 miniflow_and_mask_matches_flow_wc(const struct miniflow *flow,
1759 const struct minimask *mask,
1760 const struct flow *target,
1761 struct flow_wildcards *wc)
1763 const uint64_t *flowp = miniflow_get_values(flow);
1764 const uint64_t *maskp = miniflow_get_values(&mask->masks);
1767 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1768 uint64_t mask = *maskp++;
1769 uint64_t diff = (*flowp++ ^ flow_u64_value(target, idx)) & mask;
1772 /* Only unwildcard if none of the differing bits is already
1774 if (!(flow_u64_value(&wc->masks, idx) & diff)) {
1775 /* Keep one bit of the difference. The selected bit may be
1776 * different in big-endian v.s. little-endian systems. */
1777 *flow_u64_lvalue(&wc->masks, idx) |= rightmost_1bit(diff);
1781 /* Fill in the bits that were looked at. */
1782 *flow_u64_lvalue(&wc->masks, idx) |= mask;
1788 /* Unwildcard the fields looked up so far, if any. */
1790 fill_range_wc(const struct cls_subtable *subtable, struct flow_wildcards *wc,
1794 flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, to);
1798 static const struct cls_match *
1799 find_match_wc(const struct cls_subtable *subtable, cls_version_t version,
1800 const struct flow *flow, struct trie_ctx trie_ctx[CLS_MAX_TRIES],
1801 unsigned int n_tries, struct flow_wildcards *wc)
1803 uint32_t basis = 0, hash;
1804 const struct cls_match *rule = NULL;
1808 if (OVS_UNLIKELY(!wc)) {
1809 return find_match(subtable, version, flow,
1810 flow_hash_in_minimask(flow, &subtable->mask, 0));
1814 /* Try to finish early by checking fields in segments. */
1815 for (i = 0; i < subtable->n_indices; i++) {
1816 const struct cmap_node *inode;
1818 ofs.end = subtable->index_ofs[i];
1820 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1822 /* 'wc' bits for the trie field set, now unwildcard the preceding
1823 * bits used so far. */
1824 fill_range_wc(subtable, wc, ofs.start);
1827 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1829 inode = cmap_find(&subtable->indices[i], hash);
1831 /* No match, can stop immediately, but must fold in the bits
1832 * used in lookup so far. */
1833 fill_range_wc(subtable, wc, ofs.end);
1837 /* If we have narrowed down to a single rule already, check whether
1838 * that rule matches. Either way, we're done.
1840 * (Rare) hash collisions may cause us to miss the opportunity for this
1842 if (!cmap_node_next(inode)) {
1843 const struct cls_match *head;
1845 ASSIGN_CONTAINER(head, inode - i, index_nodes);
1846 if (miniflow_and_mask_matches_flow_wc(&head->flow, &subtable->mask,
1848 /* Return highest priority rule that is visible. */
1849 CLS_MATCH_FOR_EACH (rule, head) {
1850 if (OVS_LIKELY(cls_match_visible_in_version(rule,
1858 ofs.start = ofs.end;
1860 ofs.end = FLOW_U64S;
1861 /* Trie check for the final range. */
1862 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1863 fill_range_wc(subtable, wc, ofs.start);
1866 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1868 rule = find_match(subtable, version, flow, hash);
1869 if (!rule && subtable->ports_mask_len) {
1870 /* Ports are always part of the final range, if any.
1871 * No match was found for the ports. Use the ports trie to figure out
1872 * which ports bits to unwildcard. */
1874 ovs_be32 value, plens, mask;
1876 mask = MINIFLOW_GET_BE32(&subtable->mask.masks, tp_src);
1877 value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
1878 mbits = trie_lookup_value(&subtable->ports_trie, &value, &plens, 32);
1880 ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
1881 mask & be32_prefix_mask(mbits);
1883 /* Unwildcard all bits in the mask upto the ports, as they were used
1884 * to determine there is no match. */
1885 fill_range_wc(subtable, wc, TP_PORTS_OFS64);
1889 /* Must unwildcard all the fields, as they were looked at. */
1890 flow_wildcards_fold_minimask(wc, &subtable->mask);
1894 static struct cls_match *
1895 find_equal(const struct cls_subtable *subtable, const struct miniflow *flow,
1898 struct cls_match *head;
1900 CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1901 if (miniflow_equal(&head->flow, flow)) {
1908 /* A longest-prefix match tree. */
1910 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1911 * Prefixes are in the network byte order, and the offset 0 corresponds to
1912 * the most significant bit of the first byte. The offset can be read as
1913 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1915 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1919 pr += ofs / 32; /* Where to start. */
1920 ofs %= 32; /* How many bits to skip at 'pr'. */
1922 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1923 if (plen > 32 - ofs) { /* Need more than we have already? */
1924 prefix |= ntohl(*++pr) >> (32 - ofs);
1926 /* Return with possible unwanted bits at the end. */
1930 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1931 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1932 * corresponds to the most significant bit of the first byte. The offset can
1933 * be read as "how many bits to skip from the start of the prefix starting at
1936 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1941 if (plen > TRIE_PREFIX_BITS) {
1942 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1944 /* Return with unwanted bits cleared. */
1945 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1948 /* Return the number of equal bits in 'n_bits' of 'prefix's MSBs and a 'value'
1949 * starting at "MSB 0"-based offset 'ofs'. */
1951 prefix_equal_bits(uint32_t prefix, unsigned int n_bits, const ovs_be32 value[],
1954 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, n_bits);
1955 /* Set the bit after the relevant bits to limit the result. */
1956 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - n_bits));
1959 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1960 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1962 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1963 unsigned int ofs, unsigned int plen)
1965 return prefix_equal_bits(node->prefix, MIN(node->n_bits, plen - ofs),
1969 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1970 * be greater than 31. */
1972 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1974 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1977 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1978 * be between 0 and 31, inclusive. */
1980 get_bit_at(const uint32_t prefix, unsigned int ofs)
1982 return (prefix >> (31 - ofs)) & 1u;
1985 /* Create new branch. */
1986 static struct trie_node *
1987 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1988 unsigned int n_rules)
1990 struct trie_node *node = xmalloc(sizeof *node);
1992 node->prefix = trie_get_prefix(prefix, ofs, plen);
1994 if (plen <= TRIE_PREFIX_BITS) {
1995 node->n_bits = plen;
1996 ovsrcu_set_hidden(&node->edges[0], NULL);
1997 ovsrcu_set_hidden(&node->edges[1], NULL);
1998 node->n_rules = n_rules;
1999 } else { /* Need intermediate nodes. */
2000 struct trie_node *subnode = trie_branch_create(prefix,
2001 ofs + TRIE_PREFIX_BITS,
2002 plen - TRIE_PREFIX_BITS,
2004 int bit = get_bit_at(subnode->prefix, 0);
2005 node->n_bits = TRIE_PREFIX_BITS;
2006 ovsrcu_set_hidden(&node->edges[bit], subnode);
2007 ovsrcu_set_hidden(&node->edges[!bit], NULL);
2014 trie_node_destroy(const struct trie_node *node)
2016 ovsrcu_postpone(free, CONST_CAST(struct trie_node *, node));
2019 /* Copy a trie node for modification and postpone delete the old one. */
2020 static struct trie_node *
2021 trie_node_rcu_realloc(const struct trie_node *node)
2023 struct trie_node *new_node = xmalloc(sizeof *node);
2026 trie_node_destroy(node);
2032 trie_destroy(rcu_trie_ptr *trie)
2034 struct trie_node *node = ovsrcu_get_protected(struct trie_node *, trie);
2037 ovsrcu_set_hidden(trie, NULL);
2038 trie_destroy(&node->edges[0]);
2039 trie_destroy(&node->edges[1]);
2040 trie_node_destroy(node);
2045 trie_is_leaf(const struct trie_node *trie)
2048 return !ovsrcu_get(struct trie_node *, &trie->edges[0])
2049 && !ovsrcu_get(struct trie_node *, &trie->edges[1]);
2053 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
2054 unsigned int n_bits)
2056 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
2059 for (i = 0; i < n_bits / 32; i++) {
2060 mask[i] = OVS_BE32_MAX;
2063 mask[i] |= htonl(~0u << (32 - n_bits % 32));
2068 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
2069 unsigned int n_bits)
2071 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
2073 ovs_be32 zeroes = 0;
2075 for (i = 0; i < n_bits / 32; i++) {
2079 zeroes |= ~mask[i] & htonl(~0u << (32 - n_bits % 32));
2082 return !zeroes; /* All 'n_bits' bits set. */
2085 static rcu_trie_ptr *
2086 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
2089 return node->edges + be_get_bit_at(value, ofs);
2092 static const struct trie_node *
2093 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
2096 return ovsrcu_get(struct trie_node *,
2097 &node->edges[be_get_bit_at(value, ofs)]);
2100 /* Set the bit at ("MSB 0"-based) offset 'ofs'. 'ofs' can be greater than 31.
2103 be_set_bit_at(ovs_be32 value[], unsigned int ofs)
2105 ((uint8_t *)value)[ofs / 8] |= 1u << (7 - ofs % 8);
2108 /* Returns the number of bits in the prefix mask necessary to determine a
2109 * mismatch, in case there are longer prefixes in the tree below the one that
2111 * '*plens' will have a bit set for each prefix length that may have matching
2112 * rules. The caller is responsible for clearing the '*plens' prior to
2116 trie_lookup_value(const rcu_trie_ptr *trie, const ovs_be32 value[],
2117 ovs_be32 plens[], unsigned int n_bits)
2119 const struct trie_node *prev = NULL;
2120 const struct trie_node *node = ovsrcu_get(struct trie_node *, trie);
2121 unsigned int match_len = 0; /* Number of matching bits. */
2123 for (; node; prev = node, node = trie_next_node(node, value, match_len)) {
2124 unsigned int eqbits;
2125 /* Check if this edge can be followed. */
2126 eqbits = prefix_equal_bits(node->prefix, node->n_bits, value,
2128 match_len += eqbits;
2129 if (eqbits < node->n_bits) { /* Mismatch, nothing more to be found. */
2130 /* Bit at offset 'match_len' differed. */
2131 return match_len + 1; /* Includes the first mismatching bit. */
2133 /* Full match, check if rules exist at this prefix length. */
2134 if (node->n_rules > 0) {
2135 be_set_bit_at(plens, match_len - 1);
2137 if (match_len >= n_bits) {
2138 return n_bits; /* Full prefix. */
2141 /* node == NULL. Full match so far, but we tried to follow an
2142 * non-existing branch. Need to exclude the other branch if it exists
2143 * (it does not if we were called on an empty trie or 'prev' is a leaf
2145 return !prev || trie_is_leaf(prev) ? match_len : match_len + 1;
2149 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
2150 union mf_value *plens)
2152 const struct mf_field *mf = trie->field;
2154 /* Check that current flow matches the prerequisites for the trie
2155 * field. Some match fields are used for multiple purposes, so we
2156 * must check that the trie is relevant for this flow. */
2157 if (mf_are_prereqs_ok(mf, flow)) {
2158 return trie_lookup_value(&trie->root,
2159 &((ovs_be32 *)flow)[mf->flow_be32ofs],
2160 &plens->be32, mf->n_bits);
2162 memset(plens, 0xff, sizeof *plens); /* All prefixes, no skipping. */
2163 return 0; /* Value not used in this case. */
2166 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
2167 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
2168 * 'miniflow_index' is not NULL. */
2170 minimask_get_prefix_len(const struct minimask *minimask,
2171 const struct mf_field *mf)
2173 unsigned int n_bits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
2174 uint8_t be32_ofs = mf->flow_be32ofs;
2175 uint8_t be32_end = be32_ofs + mf->n_bytes / 4;
2177 for (; be32_ofs < be32_end; ++be32_ofs) {
2178 uint32_t mask = ntohl(minimask_get_be32(minimask, be32_ofs));
2180 /* Validate mask, count the mask length. */
2183 return 0; /* No bits allowed after mask ended. */
2186 if (~mask & (~mask + 1)) {
2187 return 0; /* Mask not contiguous. */
2189 mask_tz = ctz32(mask);
2190 n_bits += 32 - mask_tz;
2198 * This is called only when mask prefix is known to be CIDR and non-zero.
2199 * Relies on the fact that the flow and mask have the same map, and since
2200 * the mask is CIDR, the storage for the flow field exists even if it
2201 * happened to be zeros.
2203 static const ovs_be32 *
2204 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
2206 return (OVS_FORCE const ovs_be32 *)
2207 (miniflow_get_values(&match->flow)
2208 + count_1bits(match->flow.map &
2209 ((UINT64_C(1) << mf->flow_be32ofs / 2) - 1)))
2210 + (mf->flow_be32ofs & 1);
2213 /* Insert rule in to the prefix tree.
2214 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2217 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2219 trie_insert_prefix(&trie->root,
2220 minimatch_get_prefix(&rule->match, trie->field), mlen);
2224 trie_insert_prefix(rcu_trie_ptr *edge, const ovs_be32 *prefix, int mlen)
2226 struct trie_node *node;
2229 /* Walk the tree. */
2230 for (; (node = ovsrcu_get_protected(struct trie_node *, edge));
2231 edge = trie_next_edge(node, prefix, ofs)) {
2232 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2234 if (eqbits < node->n_bits) {
2235 /* Mismatch, new node needs to be inserted above. */
2236 int old_branch = get_bit_at(node->prefix, eqbits);
2237 struct trie_node *new_parent;
2239 new_parent = trie_branch_create(prefix, ofs - eqbits, eqbits,
2240 ofs == mlen ? 1 : 0);
2241 /* Copy the node to modify it. */
2242 node = trie_node_rcu_realloc(node);
2243 /* Adjust the new node for its new position in the tree. */
2244 node->prefix <<= eqbits;
2245 node->n_bits -= eqbits;
2246 ovsrcu_set_hidden(&new_parent->edges[old_branch], node);
2248 /* Check if need a new branch for the new rule. */
2250 ovsrcu_set_hidden(&new_parent->edges[!old_branch],
2251 trie_branch_create(prefix, ofs, mlen - ofs,
2254 ovsrcu_set(edge, new_parent); /* Publish changes. */
2257 /* Full match so far. */
2260 /* Full match at the current node, rule needs to be added here. */
2265 /* Must insert a new tree branch for the new rule. */
2266 ovsrcu_set(edge, trie_branch_create(prefix, ofs, mlen - ofs, 1));
2269 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2272 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2274 trie_remove_prefix(&trie->root,
2275 minimatch_get_prefix(&rule->match, trie->field), mlen);
2278 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2281 trie_remove_prefix(rcu_trie_ptr *root, const ovs_be32 *prefix, int mlen)
2283 struct trie_node *node;
2284 rcu_trie_ptr *edges[sizeof(union mf_value) * 8];
2285 int depth = 0, ofs = 0;
2287 /* Walk the tree. */
2288 for (edges[0] = root;
2289 (node = ovsrcu_get_protected(struct trie_node *, edges[depth]));
2290 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
2291 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2293 if (eqbits < node->n_bits) {
2294 /* Mismatch, nothing to be removed. This should never happen, as
2295 * only rules in the classifier are ever removed. */
2296 break; /* Log a warning. */
2298 /* Full match so far. */
2302 /* Full prefix match at the current node, remove rule here. */
2303 if (!node->n_rules) {
2304 break; /* Log a warning. */
2308 /* Check if can prune the tree. */
2309 while (!node->n_rules) {
2310 struct trie_node *next,
2311 *edge0 = ovsrcu_get_protected(struct trie_node *,
2313 *edge1 = ovsrcu_get_protected(struct trie_node *,
2316 if (edge0 && edge1) {
2317 break; /* A branching point, cannot prune. */
2320 /* Else have at most one child node, remove this node. */
2321 next = edge0 ? edge0 : edge1;
2324 if (node->n_bits + next->n_bits > TRIE_PREFIX_BITS) {
2325 break; /* Cannot combine. */
2327 next = trie_node_rcu_realloc(next); /* Modify. */
2329 /* Combine node with next. */
2330 next->prefix = node->prefix | next->prefix >> node->n_bits;
2331 next->n_bits += node->n_bits;
2333 /* Update the parent's edge. */
2334 ovsrcu_set(edges[depth], next); /* Publish changes. */
2335 trie_node_destroy(node);
2337 if (next || !depth) {
2338 /* Branch not pruned or at root, nothing more to do. */
2341 node = ovsrcu_get_protected(struct trie_node *,
2347 /* Cannot go deeper. This should never happen, since only rules
2348 * that actually exist in the classifier are ever removed. */
2349 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");
2353 #define CLS_MATCH_POISON (struct cls_match *)(UINTPTR_MAX / 0xf * 0xb)
2356 cls_match_free_cb(struct cls_match *rule)
2358 ovsrcu_set_hidden(&rule->next, CLS_MATCH_POISON);