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 cls->n_flow_segments = 0;
326 while (cls->n_flow_segments < CLS_MAX_INDICES
327 && *flow_segments < FLOW_U64S) {
328 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
332 for (int i = 0; i < CLS_MAX_TRIES; i++) {
333 trie_init(cls, i, NULL);
338 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
339 * caller's responsibility.
340 * May only be called after all the readers have been terminated. */
342 classifier_destroy(struct classifier *cls)
345 struct cls_subtable *subtable;
348 for (i = 0; i < cls->n_tries; i++) {
349 trie_destroy(&cls->tries[i].root);
352 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
353 destroy_subtable(cls, subtable);
355 cmap_destroy(&cls->subtables_map);
357 pvector_destroy(&cls->subtables);
361 /* Set the fields for which prefix lookup should be performed. */
363 classifier_set_prefix_fields(struct classifier *cls,
364 const enum mf_field_id *trie_fields,
365 unsigned int n_fields)
367 const struct mf_field * new_fields[CLS_MAX_TRIES];
368 struct mf_bitmap fields = MF_BITMAP_INITIALIZER;
370 bool changed = false;
372 for (i = 0; i < n_fields && n_tries < CLS_MAX_TRIES; i++) {
373 const struct mf_field *field = mf_from_id(trie_fields[i]);
374 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
375 /* Incompatible field. This is the only place where we
376 * enforce these requirements, but the rest of the trie code
377 * depends on the flow_be32ofs to be non-negative and the
378 * field length to be a multiple of 32 bits. */
382 if (bitmap_is_set(fields.bm, trie_fields[i])) {
383 /* Duplicate field, there is no need to build more than
384 * one index for any one field. */
387 bitmap_set1(fields.bm, trie_fields[i]);
389 new_fields[n_tries] = NULL;
390 if (n_tries >= cls->n_tries || field != cls->tries[n_tries].field) {
391 new_fields[n_tries] = field;
397 if (changed || n_tries < cls->n_tries) {
398 struct cls_subtable *subtable;
400 /* Trie configuration needs to change. Disable trie lookups
401 * for the tries that are changing and wait all the current readers
402 * with the old configuration to be done. */
404 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
405 for (i = 0; i < cls->n_tries; i++) {
406 if ((i < n_tries && new_fields[i]) || i >= n_tries) {
407 if (subtable->trie_plen[i]) {
408 subtable->trie_plen[i] = 0;
414 /* Synchronize if any readers were using tries. The readers may
415 * temporarily function without the trie lookup based optimizations. */
417 /* ovsrcu_synchronize() functions as a memory barrier, so it does
418 * not matter that subtable->trie_plen is not atomic. */
419 ovsrcu_synchronize();
422 /* Now set up the tries. */
423 for (i = 0; i < n_tries; i++) {
425 trie_init(cls, i, new_fields[i]);
428 /* Destroy the rest, if any. */
429 for (; i < cls->n_tries; i++) {
430 trie_init(cls, i, NULL);
433 cls->n_tries = n_tries;
437 return false; /* No change. */
441 trie_init(struct classifier *cls, int trie_idx, const struct mf_field *field)
443 struct cls_trie *trie = &cls->tries[trie_idx];
444 struct cls_subtable *subtable;
446 if (trie_idx < cls->n_tries) {
447 trie_destroy(&trie->root);
449 ovsrcu_set_hidden(&trie->root, NULL);
453 /* Add existing rules to the new trie. */
454 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
457 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
459 struct cls_match *head;
461 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
462 trie_insert(trie, head->cls_rule, plen);
465 /* Initialize subtable's prefix length on this field. This will
466 * allow readers to use the trie. */
467 atomic_thread_fence(memory_order_release);
468 subtable->trie_plen[trie_idx] = plen;
472 /* Returns true if 'cls' contains no classification rules, false otherwise.
473 * Checking the cmap requires no locking. */
475 classifier_is_empty(const struct classifier *cls)
477 return cmap_is_empty(&cls->subtables_map);
480 /* Returns the number of rules in 'cls'. */
482 classifier_count(const struct classifier *cls)
484 /* n_rules is an int, so in the presence of concurrent writers this will
485 * return either the old or a new value. */
489 static inline ovs_be32 minimatch_get_ports(const struct minimatch *match)
491 /* Could optimize to use the same map if needed for fast path. */
492 return MINIFLOW_GET_BE32(match->flow, tp_src)
493 & MINIFLOW_GET_BE32(&match->mask->masks, tp_src);
497 subtable_replace_head_rule(struct classifier *cls OVS_UNUSED,
498 struct cls_subtable *subtable,
499 struct cls_match *head, struct cls_match *new,
500 uint32_t hash, uint32_t ihash[CLS_MAX_INDICES])
502 /* Rule's data is already in the tries. */
504 for (int i = 0; i < subtable->n_indices; i++) {
505 cmap_replace(&subtable->indices[i], &head->index_nodes[i],
506 &new->index_nodes[i], ihash[i]);
508 cmap_replace(&subtable->rules, &head->cmap_node, &new->cmap_node, hash);
511 /* Inserts 'rule' into 'cls' in 'version'. Until 'rule' is removed from 'cls',
512 * the caller must not modify or free it.
514 * If 'cls' already contains an identical rule (including wildcards, values of
515 * fixed fields, and priority) that is visible in 'version', replaces the old
516 * rule by 'rule' and returns the rule that was replaced. The caller takes
517 * ownership of the returned rule and is thus responsible for destroying it
518 * with cls_rule_destroy(), after RCU grace period has passed (see
519 * ovsrcu_postpone()).
521 * Returns NULL if 'cls' does not contain a rule with an identical key, after
522 * inserting the new rule. In this case, no rules are displaced by the new
523 * rule, even rules that cannot have any effect because the new rule matches a
524 * superset of their flows and has higher priority.
526 const struct cls_rule *
527 classifier_replace(struct classifier *cls, const struct cls_rule *rule,
528 cls_version_t version,
529 const struct cls_conjunction *conjs, size_t n_conjs)
531 struct cls_match *new;
532 struct cls_subtable *subtable;
533 uint32_t ihash[CLS_MAX_INDICES];
534 struct cls_match *head;
535 unsigned int mask_offset;
541 /* 'new' is initially invisible to lookups. */
542 new = cls_match_alloc(rule, version, conjs, n_conjs);
544 CONST_CAST(struct cls_rule *, rule)->cls_match = new;
546 subtable = find_subtable(cls, rule->match.mask);
548 subtable = insert_subtable(cls, rule->match.mask);
551 /* Compute hashes in segments. */
554 for (i = 0; i < subtable->n_indices; i++) {
555 ihash[i] = minimatch_hash_range(&rule->match, subtable->index_maps[i],
556 &mask_offset, &basis);
558 hash = minimatch_hash_range(&rule->match, subtable->index_maps[i],
559 &mask_offset, &basis);
561 head = find_equal(subtable, rule->match.flow, hash);
563 /* Add rule to tries.
565 * Concurrent readers might miss seeing the rule until this update,
566 * which might require being fixed up by revalidation later. */
567 for (i = 0; i < cls->n_tries; i++) {
568 if (subtable->trie_plen[i]) {
569 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
573 /* Add rule to ports trie. */
574 if (subtable->ports_mask_len) {
575 /* We mask the value to be inserted to always have the wildcarded
576 * bits in known (zero) state, so we can include them in comparison
577 * and they will always match (== their original value does not
579 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
581 trie_insert_prefix(&subtable->ports_trie, &masked_ports,
582 subtable->ports_mask_len);
585 /* Add new node to segment indices.
587 * Readers may find the rule in the indices before the rule is visible
588 * in the subtables 'rules' map. This may result in us losing the
589 * opportunity to quit lookups earlier, resulting in sub-optimal
590 * wildcarding. This will be fixed later by revalidation (always
591 * scheduled after flow table changes). */
592 for (i = 0; i < subtable->n_indices; i++) {
593 cmap_insert(&subtable->indices[i], &new->index_nodes[i], ihash[i]);
595 n_rules = cmap_insert(&subtable->rules, &new->cmap_node, hash);
596 } else { /* Equal rules exist in the classifier already. */
597 struct cls_match *prev, *iter;
599 /* Scan the list for the insertion point that will keep the list in
600 * order of decreasing priority. Insert after rules marked invisible
601 * in any version of the same priority. */
602 FOR_EACH_RULE_IN_LIST_PROTECTED (iter, prev, head) {
603 if (rule->priority > iter->priority
604 || (rule->priority == iter->priority
605 && !cls_match_is_eventually_invisible(iter))) {
610 /* Replace 'iter' with 'new' or insert 'new' between 'prev' and
613 struct cls_rule *old;
615 if (rule->priority == iter->priority) {
616 cls_match_replace(prev, iter, new);
617 old = CONST_CAST(struct cls_rule *, iter->cls_rule);
619 cls_match_insert(prev, iter, new);
623 /* Replace the existing head in data structures, if rule is the new
626 subtable_replace_head_rule(cls, subtable, head, new, hash,
631 struct cls_conjunction_set *conj_set;
633 conj_set = ovsrcu_get_protected(struct cls_conjunction_set *,
636 ovsrcu_postpone(free, conj_set);
639 ovsrcu_postpone(cls_match_free_cb, iter);
640 old->cls_match = NULL;
642 /* No change in subtable's max priority or max count. */
644 /* Make 'new' visible to lookups in the appropriate version. */
645 cls_match_set_remove_version(new, CLS_NOT_REMOVED_VERSION);
647 /* Make rule visible to iterators (immediately). */
648 rculist_replace(CONST_CAST(struct rculist *, &rule->node),
651 /* Return displaced rule. Caller is responsible for keeping it
652 * around until all threads quiesce. */
656 /* 'new' is new node after 'prev' */
657 cls_match_insert(prev, iter, new);
661 /* Make 'new' visible to lookups in the appropriate version. */
662 cls_match_set_remove_version(new, CLS_NOT_REMOVED_VERSION);
664 /* Make rule visible to iterators (immediately). */
665 rculist_push_back(&subtable->rules_list,
666 CONST_CAST(struct rculist *, &rule->node));
668 /* Rule was added, not replaced. Update 'subtable's 'max_priority' and
669 * 'max_count', if necessary.
671 * The rule was already inserted, but concurrent readers may not see the
672 * rule yet as the subtables vector is not updated yet. This will have to
673 * be fixed by revalidation later. */
675 subtable->max_priority = rule->priority;
676 subtable->max_count = 1;
677 pvector_insert(&cls->subtables, subtable, rule->priority);
678 } else if (rule->priority == subtable->max_priority) {
679 ++subtable->max_count;
680 } else if (rule->priority > subtable->max_priority) {
681 subtable->max_priority = rule->priority;
682 subtable->max_count = 1;
683 pvector_change_priority(&cls->subtables, subtable, rule->priority);
686 /* Nothing was replaced. */
690 pvector_publish(&cls->subtables);
696 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
697 * must not modify or free it.
699 * 'cls' must not contain an identical rule (including wildcards, values of
700 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
703 classifier_insert(struct classifier *cls, const struct cls_rule *rule,
704 cls_version_t version, const struct cls_conjunction conj[],
707 const struct cls_rule *displaced_rule
708 = classifier_replace(cls, rule, version, conj, n_conj);
709 ovs_assert(!displaced_rule);
712 /* Removes 'rule' from 'cls'. It is the caller's responsibility to destroy
713 * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
714 * resides, etc., as necessary.
716 * Does nothing if 'rule' has been already removed, or was never inserted.
718 * Returns the removed rule, or NULL, if it was already removed.
720 const struct cls_rule *
721 classifier_remove(struct classifier *cls, const struct cls_rule *cls_rule)
723 struct cls_match *rule, *prev, *next, *head;
724 struct cls_conjunction_set *conj_set;
725 struct cls_subtable *subtable;
726 uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
727 unsigned int mask_offset;
731 rule = cls_rule->cls_match;
735 /* Mark as removed. */
736 CONST_CAST(struct cls_rule *, cls_rule)->cls_match = NULL;
738 /* Remove 'cls_rule' from the subtable's rules list. */
739 rculist_remove(CONST_CAST(struct rculist *, &cls_rule->node));
741 subtable = find_subtable(cls, cls_rule->match.mask);
742 ovs_assert(subtable);
745 for (i = 0; i < subtable->n_indices; i++) {
746 ihash[i] = minimatch_hash_range(&cls_rule->match,
747 subtable->index_maps[i],
748 &mask_offset, &basis);
750 hash = minimatch_hash_range(&cls_rule->match, subtable->index_maps[i],
751 &mask_offset, &basis);
753 head = find_equal(subtable, cls_rule->match.flow, hash);
755 /* Check if the rule is not the head rule. */
757 struct cls_match *iter;
759 /* Not the head rule, but potentially one with the same priority. */
760 /* Remove from the list of equal rules. */
761 FOR_EACH_RULE_IN_LIST_PROTECTED (iter, prev, head) {
766 ovs_assert(iter == rule);
768 cls_match_remove(prev, rule);
773 /* 'rule' is the head rule. Check if there is another rule to
774 * replace 'rule' in the data structures. */
775 next = cls_match_next_protected(rule);
777 subtable_replace_head_rule(cls, subtable, rule, next, hash, ihash);
781 /* 'rule' is last of the kind in the classifier, must remove from all the
782 * data structures. */
784 if (subtable->ports_mask_len) {
785 ovs_be32 masked_ports = minimatch_get_ports(&cls_rule->match);
787 trie_remove_prefix(&subtable->ports_trie,
788 &masked_ports, subtable->ports_mask_len);
790 for (i = 0; i < cls->n_tries; i++) {
791 if (subtable->trie_plen[i]) {
792 trie_remove(&cls->tries[i], cls_rule, subtable->trie_plen[i]);
796 /* Remove rule node from indices. */
797 for (i = 0; i < subtable->n_indices; i++) {
798 cmap_remove(&subtable->indices[i], &rule->index_nodes[i], ihash[i]);
800 n_rules = cmap_remove(&subtable->rules, &rule->cmap_node, hash);
803 destroy_subtable(cls, subtable);
806 if (subtable->max_priority == rule->priority
807 && --subtable->max_count == 0) {
808 /* Find the new 'max_priority' and 'max_count'. */
809 int max_priority = INT_MIN;
810 struct cls_match *head;
812 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
813 if (head->priority > max_priority) {
814 max_priority = head->priority;
815 subtable->max_count = 1;
816 } else if (head->priority == max_priority) {
817 ++subtable->max_count;
820 subtable->max_priority = max_priority;
821 pvector_change_priority(&cls->subtables, subtable, max_priority);
826 pvector_publish(&cls->subtables);
830 conj_set = ovsrcu_get_protected(struct cls_conjunction_set *,
833 ovsrcu_postpone(free, conj_set);
835 ovsrcu_postpone(cls_match_free_cb, rule);
841 /* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
842 * subtables which have a prefix match on the trie field, but whose prefix
843 * length is not indicated in 'match_plens'. For example, a subtable that
844 * has a 8-bit trie field prefix match can be skipped if
845 * !be_get_bit_at(&match_plens, 8 - 1). If skipped, 'maskbits' prefix bits
846 * must be unwildcarded to make datapath flow only match packets it should. */
848 const struct cls_trie *trie;
849 bool lookup_done; /* Status of the lookup. */
850 uint8_t be32ofs; /* U32 offset of the field in question. */
851 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
852 union trie_prefix match_plens; /* Bitmask of prefix lengths with possible
857 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
860 ctx->be32ofs = trie->field->flow_be32ofs;
861 ctx->lookup_done = false;
864 struct conjunctive_match {
865 struct hmap_node hmap_node;
870 static struct conjunctive_match *
871 find_conjunctive_match__(struct hmap *matches, uint64_t id, uint32_t hash)
873 struct conjunctive_match *m;
875 HMAP_FOR_EACH_IN_BUCKET (m, hmap_node, hash, matches) {
884 find_conjunctive_match(const struct cls_conjunction_set *set,
885 unsigned int max_n_clauses, struct hmap *matches,
886 struct conjunctive_match *cm_stubs, size_t n_cm_stubs,
889 const struct cls_conjunction *c;
891 if (max_n_clauses < set->min_n_clauses) {
895 for (c = set->conj; c < &set->conj[set->n]; c++) {
896 struct conjunctive_match *cm;
899 if (c->n_clauses > max_n_clauses) {
903 hash = hash_int(c->id, 0);
904 cm = find_conjunctive_match__(matches, c->id, hash);
906 size_t n = hmap_count(matches);
908 cm = n < n_cm_stubs ? &cm_stubs[n] : xmalloc(sizeof *cm);
909 hmap_insert(matches, &cm->hmap_node, hash);
911 cm->clauses = UINT64_MAX << (c->n_clauses & 63);
913 cm->clauses |= UINT64_C(1) << c->clause;
914 if (cm->clauses == UINT64_MAX) {
923 free_conjunctive_matches(struct hmap *matches,
924 struct conjunctive_match *cm_stubs, size_t n_cm_stubs)
926 if (hmap_count(matches) > n_cm_stubs) {
927 struct conjunctive_match *cm, *next;
929 HMAP_FOR_EACH_SAFE (cm, next, hmap_node, matches) {
930 if (!(cm >= cm_stubs && cm < &cm_stubs[n_cm_stubs])) {
935 hmap_destroy(matches);
938 /* Like classifier_lookup(), except that support for conjunctive matches can be
939 * configured with 'allow_conjunctive_matches'. That feature is not exposed
940 * externally because turning off conjunctive matches is only useful to avoid
941 * recursion within this function itself.
943 * 'flow' is non-const to allow for temporary modifications during the lookup.
944 * Any changes are restored before returning. */
945 static const struct cls_rule *
946 classifier_lookup__(const struct classifier *cls, cls_version_t version,
947 struct flow *flow, struct flow_wildcards *wc,
948 bool allow_conjunctive_matches)
950 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
951 const struct cls_match *match;
952 /* Highest-priority flow in 'cls' that certainly matches 'flow'. */
953 const struct cls_match *hard = NULL;
954 int hard_pri = INT_MIN; /* hard ? hard->priority : INT_MIN. */
956 /* Highest-priority conjunctive flows in 'cls' matching 'flow'. Since
957 * these are (components of) conjunctive flows, we can only know whether
958 * the full conjunctive flow matches after seeing multiple of them. Thus,
959 * we refer to these as "soft matches". */
960 struct cls_conjunction_set *soft_stub[64];
961 struct cls_conjunction_set **soft = soft_stub;
962 size_t n_soft = 0, allocated_soft = ARRAY_SIZE(soft_stub);
963 int soft_pri = INT_MIN; /* n_soft ? MAX(soft[*]->priority) : INT_MIN. */
965 /* Synchronize for cls->n_tries and subtable->trie_plen. They can change
966 * when table configuration changes, which happens typically only on
968 atomic_thread_fence(memory_order_acquire);
970 /* Initialize trie contexts for find_match_wc(). */
971 for (int i = 0; i < cls->n_tries; i++) {
972 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
976 struct cls_subtable *subtable;
977 PVECTOR_FOR_EACH_PRIORITY (subtable, hard_pri, 2, sizeof *subtable,
979 struct cls_conjunction_set *conj_set;
981 /* Skip subtables with no match, or where the match is lower-priority
982 * than some certain match we've already found. */
983 match = find_match_wc(subtable, version, flow, trie_ctx, cls->n_tries,
985 if (!match || match->priority <= hard_pri) {
989 conj_set = ovsrcu_get(struct cls_conjunction_set *, &match->conj_set);
991 /* 'match' isn't part of a conjunctive match. It's the best
992 * certain match we've got so far, since we know that it's
993 * higher-priority than hard_pri.
995 * (There might be a higher-priority conjunctive match. We can't
998 hard_pri = hard->priority;
999 } else if (allow_conjunctive_matches) {
1000 /* 'match' is part of a conjunctive match. Add it to the list. */
1001 if (OVS_UNLIKELY(n_soft >= allocated_soft)) {
1002 struct cls_conjunction_set **old_soft = soft;
1004 allocated_soft *= 2;
1005 soft = xmalloc(allocated_soft * sizeof *soft);
1006 memcpy(soft, old_soft, n_soft * sizeof *soft);
1007 if (old_soft != soft_stub) {
1011 soft[n_soft++] = conj_set;
1013 /* Keep track of the highest-priority soft match. */
1014 if (soft_pri < match->priority) {
1015 soft_pri = match->priority;
1020 /* In the common case, at this point we have no soft matches and we can
1021 * return immediately. (We do the same thing if we have potential soft
1022 * matches but none of them are higher-priority than our hard match.) */
1023 if (hard_pri >= soft_pri) {
1024 if (soft != soft_stub) {
1027 return hard ? hard->cls_rule : NULL;
1030 /* At this point, we have some soft matches. We might also have a hard
1031 * match; if so, its priority is lower than the highest-priority soft
1036 * Check whether soft matches are real matches. */
1038 /* Delete soft matches that are null. This only happens in second and
1039 * subsequent iterations of the soft match loop, when we drop back from
1040 * a high-priority soft match to a lower-priority one.
1042 * Also, delete soft matches whose priority is less than or equal to
1043 * the hard match's priority. In the first iteration of the soft
1044 * match, these can be in 'soft' because the earlier main loop found
1045 * the soft match before the hard match. In second and later iteration
1046 * of the soft match loop, these can be in 'soft' because we dropped
1047 * back from a high-priority soft match to a lower-priority soft match.
1049 * It is tempting to delete soft matches that cannot be satisfied
1050 * because there are fewer soft matches than required to satisfy any of
1051 * their conjunctions, but we cannot do that because there might be
1052 * lower priority soft or hard matches with otherwise identical
1053 * matches. (We could special case those here, but there's no
1054 * need--we'll do so at the bottom of the soft match loop anyway and
1055 * this duplicates less code.)
1057 * It's also tempting to break out of the soft match loop if 'n_soft ==
1058 * 1' but that would also miss lower-priority hard matches. We could
1059 * special case that also but again there's no need. */
1060 for (int i = 0; i < n_soft; ) {
1061 if (!soft[i] || soft[i]->priority <= hard_pri) {
1062 soft[i] = soft[--n_soft];
1071 /* Find the highest priority among the soft matches. (We know this
1072 * must be higher than the hard match's priority; otherwise we would
1073 * have deleted all of the soft matches in the previous loop.) Count
1074 * the number of soft matches that have that priority. */
1077 for (int i = 0; i < n_soft; i++) {
1078 if (soft[i]->priority > soft_pri) {
1079 soft_pri = soft[i]->priority;
1081 } else if (soft[i]->priority == soft_pri) {
1085 ovs_assert(soft_pri > hard_pri);
1087 /* Look for a real match among the highest-priority soft matches.
1089 * It's unusual to have many conjunctive matches, so we use stubs to
1090 * avoid calling malloc() in the common case. An hmap has a built-in
1091 * stub for up to 2 hmap_nodes; possibly, we would benefit a variant
1092 * with a bigger stub. */
1093 struct conjunctive_match cm_stubs[16];
1094 struct hmap matches;
1096 hmap_init(&matches);
1097 for (int i = 0; i < n_soft; i++) {
1100 if (soft[i]->priority == soft_pri
1101 && find_conjunctive_match(soft[i], n_soft_pri, &matches,
1102 cm_stubs, ARRAY_SIZE(cm_stubs),
1104 uint32_t saved_conj_id = flow->conj_id;
1105 const struct cls_rule *rule;
1108 rule = classifier_lookup__(cls, version, flow, wc, false);
1109 flow->conj_id = saved_conj_id;
1112 free_conjunctive_matches(&matches,
1113 cm_stubs, ARRAY_SIZE(cm_stubs));
1114 if (soft != soft_stub) {
1121 free_conjunctive_matches(&matches, cm_stubs, ARRAY_SIZE(cm_stubs));
1123 /* There's no real match among the highest-priority soft matches.
1124 * However, if any of those soft matches has a lower-priority but
1125 * otherwise identical flow match, then we need to consider those for
1126 * soft or hard matches.
1128 * The next iteration of the soft match loop will delete any null
1129 * pointers we put into 'soft' (and some others too). */
1130 for (int i = 0; i < n_soft; i++) {
1131 if (soft[i]->priority != soft_pri) {
1135 /* Find next-lower-priority flow with identical flow match. */
1136 match = next_visible_rule_in_list(soft[i]->match, version);
1138 soft[i] = ovsrcu_get(struct cls_conjunction_set *,
1141 /* The flow is a hard match; don't treat as a soft
1143 if (match->priority > hard_pri) {
1145 hard_pri = hard->priority;
1149 /* No such lower-priority flow (probably the common case). */
1155 if (soft != soft_stub) {
1158 return hard ? hard->cls_rule : NULL;
1161 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow' and
1162 * that is visible in 'version'. Returns a null pointer if no rules in 'cls'
1163 * match 'flow'. If multiple rules of equal priority match 'flow', returns one
1166 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
1167 * set of bits that were significant in the lookup. At some point
1168 * earlier, 'wc' should have been initialized (e.g., by
1169 * flow_wildcards_init_catchall()).
1171 * 'flow' is non-const to allow for temporary modifications during the lookup.
1172 * Any changes are restored before returning. */
1173 const struct cls_rule *
1174 classifier_lookup(const struct classifier *cls, cls_version_t version,
1175 struct flow *flow, struct flow_wildcards *wc)
1177 return classifier_lookup__(cls, version, flow, wc, true);
1180 /* Finds and returns a rule in 'cls' with exactly the same priority and
1181 * matching criteria as 'target', and that is visible in 'version'.
1182 * Only one such rule may ever exist. Returns a null pointer if 'cls' doesn't
1183 * contain an exact match. */
1184 const struct cls_rule *
1185 classifier_find_rule_exactly(const struct classifier *cls,
1186 const struct cls_rule *target,
1187 cls_version_t version)
1189 const struct cls_match *head, *rule;
1190 const struct cls_subtable *subtable;
1192 subtable = find_subtable(cls, target->match.mask);
1197 head = find_equal(subtable, target->match.flow,
1198 miniflow_hash_in_minimask(target->match.flow,
1199 target->match.mask, 0));
1203 CLS_MATCH_FOR_EACH (rule, head) {
1204 if (rule->priority < target->priority) {
1205 break; /* Not found. */
1207 if (rule->priority == target->priority
1208 && cls_match_visible_in_version(rule, version)) {
1209 return rule->cls_rule;
1215 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
1216 * same matching criteria as 'target', and that is visible in 'version'.
1217 * Returns a null pointer if 'cls' doesn't contain an exact match visible in
1219 const struct cls_rule *
1220 classifier_find_match_exactly(const struct classifier *cls,
1221 const struct match *target, int priority,
1222 cls_version_t version)
1224 const struct cls_rule *retval;
1227 cls_rule_init(&cr, target, priority);
1228 retval = classifier_find_rule_exactly(cls, &cr, version);
1229 cls_rule_destroy(&cr);
1234 /* Checks if 'target' would overlap any other rule in 'cls' in 'version'. Two
1235 * rules are considered to overlap if both rules have the same priority and a
1236 * packet could match both, and if both rules are visible in the same version.
1238 * A trivial example of overlapping rules is two rules matching disjoint sets
1239 * of fields. E.g., if one rule matches only on port number, while another only
1240 * on dl_type, any packet from that specific port and with that specific
1241 * dl_type could match both, if the rules also have the same priority. */
1243 classifier_rule_overlaps(const struct classifier *cls,
1244 const struct cls_rule *target, cls_version_t version)
1246 struct cls_subtable *subtable;
1248 /* Iterate subtables in the descending max priority order. */
1249 PVECTOR_FOR_EACH_PRIORITY (subtable, target->priority - 1, 2,
1250 sizeof(struct cls_subtable), &cls->subtables) {
1252 struct minimask mask;
1253 uint64_t storage[FLOW_U64S];
1255 const struct cls_rule *rule;
1257 minimask_combine(&m.mask, target->match.mask, &subtable->mask,
1260 RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
1261 if (rule->priority == target->priority
1262 && miniflow_equal_in_minimask(target->match.flow,
1263 rule->match.flow, &m.mask)
1264 && cls_match_visible_in_version(rule->cls_match, version)) {
1272 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
1273 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
1274 * function returns true if, for every field:
1276 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
1279 * - 'criteria' wildcards the field,
1281 * Conversely, 'rule' does not match 'criteria' and this function returns false
1282 * if, for at least one field:
1284 * - 'criteria' and 'rule' specify different values for the field, or
1286 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
1288 * Equivalently, the truth table for whether a field matches is:
1293 * r +---------+---------+
1294 * i wild | yes | yes |
1296 * e +---------+---------+
1297 * r exact | no |if values|
1299 * a +---------+---------+
1301 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
1302 * commands and by OpenFlow 1.0 aggregate and flow stats.
1304 * Ignores rule->priority. */
1306 cls_rule_is_loose_match(const struct cls_rule *rule,
1307 const struct minimatch *criteria)
1309 return (!minimask_has_extra(rule->match.mask, criteria->mask)
1310 && miniflow_equal_in_minimask(rule->match.flow, criteria->flow,
1317 rule_matches(const struct cls_rule *rule, const struct cls_rule *target,
1318 cls_version_t version)
1320 /* Rule may only match a target if it is visible in target's version. */
1321 return cls_match_visible_in_version(rule->cls_match, version)
1322 && (!target || miniflow_equal_in_minimask(rule->match.flow,
1324 target->match.mask));
1327 static const struct cls_rule *
1328 search_subtable(const struct cls_subtable *subtable,
1329 struct cls_cursor *cursor)
1332 || !minimask_has_extra(&subtable->mask, cursor->target->match.mask)) {
1333 const struct cls_rule *rule;
1335 RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
1336 if (rule_matches(rule, cursor->target, cursor->version)) {
1344 /* Initializes 'cursor' for iterating through rules in 'cls', and returns the
1347 * - If 'target' is null, or if the 'target' is a catchall target, the
1348 * cursor will visit every rule in 'cls' that is visible in 'version'.
1350 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1351 * such that cls_rule_is_loose_match(rule, target) returns true and that
1352 * the rule is visible in 'version'.
1354 * Ignores target->priority. */
1356 cls_cursor_start(const struct classifier *cls, const struct cls_rule *target,
1357 cls_version_t version)
1359 struct cls_cursor cursor;
1360 struct cls_subtable *subtable;
1363 cursor.target = target && !cls_rule_is_catchall(target) ? target : NULL;
1364 cursor.version = version;
1367 /* Find first rule. */
1368 PVECTOR_CURSOR_FOR_EACH (subtable, &cursor.subtables,
1369 &cursor.cls->subtables) {
1370 const struct cls_rule *rule = search_subtable(subtable, &cursor);
1373 cursor.subtable = subtable;
1382 static const struct cls_rule *
1383 cls_cursor_next(struct cls_cursor *cursor)
1385 const struct cls_rule *rule;
1386 const struct cls_subtable *subtable;
1388 rule = cursor->rule;
1389 subtable = cursor->subtable;
1390 RCULIST_FOR_EACH_CONTINUE (rule, node, &subtable->rules_list) {
1391 if (rule_matches(rule, cursor->target, cursor->version)) {
1396 PVECTOR_CURSOR_FOR_EACH_CONTINUE (subtable, &cursor->subtables) {
1397 rule = search_subtable(subtable, cursor);
1399 cursor->subtable = subtable;
1407 /* Sets 'cursor->rule' to the next matching cls_rule in 'cursor''s iteration,
1408 * or to null if all matching rules have been visited. */
1410 cls_cursor_advance(struct cls_cursor *cursor)
1412 cursor->rule = cls_cursor_next(cursor);
1415 static struct cls_subtable *
1416 find_subtable(const struct classifier *cls, const struct minimask *mask)
1418 struct cls_subtable *subtable;
1420 CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, minimask_hash(mask, 0),
1421 &cls->subtables_map) {
1422 if (minimask_equal(mask, &subtable->mask)) {
1429 /* Initializes 'map' with a subset of 'miniflow''s maps that includes only the
1430 * portions with u64-offset 'i' such that 'start' <= i < 'end'. Does not copy
1431 * any data from 'miniflow' to 'map'. */
1432 static struct flowmap
1433 miniflow_get_map_in_range(const struct miniflow *miniflow, uint8_t start,
1439 map = miniflow->map;
1441 /* Clear the bits before 'start'. */
1442 while (start >= MAP_T_BITS) {
1443 start -= MAP_T_BITS;
1445 map.bits[start / MAP_T_BITS] = 0;
1448 flowmap_clear(&map, ofs, start);
1451 /* Clear the bits starting at 'end'. */
1452 if (end < FLOW_U64S) {
1453 /* flowmap_clear() can handle at most MAP_T_BITS at a time. */
1454 ovs_assert(FLOW_U64S - end <= MAP_T_BITS);
1455 flowmap_clear(&map, end, FLOW_U64S - end);
1460 /* The new subtable will be visible to the readers only after this. */
1461 static struct cls_subtable *
1462 insert_subtable(struct classifier *cls, const struct minimask *mask)
1464 uint32_t hash = minimask_hash(mask, 0);
1465 struct cls_subtable *subtable;
1467 struct flowmap stage_map;
1469 size_t count = miniflow_n_values(&mask->masks);
1471 subtable = xzalloc(sizeof *subtable + MINIFLOW_VALUES_SIZE(count));
1472 cmap_init(&subtable->rules);
1473 miniflow_clone(CONST_CAST(struct miniflow *, &subtable->mask.masks),
1474 &mask->masks, count);
1476 /* Init indices for segmented lookup, if any. */
1478 for (i = 0; i < cls->n_flow_segments; i++) {
1479 stage_map = miniflow_get_map_in_range(&mask->masks, prev,
1480 cls->flow_segments[i]);
1481 /* Add an index if it adds mask bits. */
1482 if (!flowmap_is_empty(stage_map)) {
1483 cmap_init(&subtable->indices[index]);
1484 *CONST_CAST(struct flowmap *, &subtable->index_maps[index])
1488 prev = cls->flow_segments[i];
1490 /* Map for the final stage. */
1491 *CONST_CAST(struct flowmap *, &subtable->index_maps[index])
1492 = miniflow_get_map_in_range(&mask->masks, prev, FLOW_U64S);
1493 /* Check if the final stage adds any bits,
1494 * and remove the last index if it doesn't. */
1496 if (flowmap_equal(subtable->index_maps[index],
1497 subtable->index_maps[index - 1])) {
1499 cmap_destroy(&subtable->indices[index]);
1502 *CONST_CAST(uint8_t *, &subtable->n_indices) = index;
1504 for (i = 0; i < cls->n_tries; i++) {
1505 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1506 cls->tries[i].field);
1510 ovsrcu_set_hidden(&subtable->ports_trie, NULL);
1511 *CONST_CAST(int *, &subtable->ports_mask_len)
1512 = 32 - ctz32(ntohl(MINIFLOW_GET_BE32(&mask->masks, tp_src)));
1514 /* List of rules. */
1515 rculist_init(&subtable->rules_list);
1517 cmap_insert(&cls->subtables_map, &subtable->cmap_node, hash);
1522 /* RCU readers may still access the subtable before it is actually freed. */
1524 destroy_subtable(struct classifier *cls, struct cls_subtable *subtable)
1528 pvector_remove(&cls->subtables, subtable);
1529 cmap_remove(&cls->subtables_map, &subtable->cmap_node,
1530 minimask_hash(&subtable->mask, 0));
1532 ovs_assert(ovsrcu_get_protected(struct trie_node *, &subtable->ports_trie)
1534 ovs_assert(cmap_is_empty(&subtable->rules));
1535 ovs_assert(rculist_is_empty(&subtable->rules_list));
1537 for (i = 0; i < subtable->n_indices; i++) {
1538 cmap_destroy(&subtable->indices[i]);
1540 cmap_destroy(&subtable->rules);
1541 ovsrcu_postpone(free, subtable);
1544 static unsigned int be_get_bit_at(const ovs_be32 value[], unsigned int ofs);
1546 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1547 * lookup results. */
1549 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1550 const unsigned int field_plen[CLS_MAX_TRIES],
1551 const struct flowmap range_map, const struct flow *flow,
1552 struct flow_wildcards *wc)
1556 /* Check if we could avoid fully unwildcarding the next level of
1557 * fields using the prefix tries. The trie checks are done only as
1558 * needed to avoid folding in additional bits to the wildcards mask. */
1559 for (j = 0; j < n_tries; j++) {
1560 /* Is the trie field relevant for this subtable, and
1561 is the trie field within the current range of fields? */
1562 if (field_plen[j] &&
1563 flowmap_is_set(&range_map, trie_ctx[j].be32ofs / 2)) {
1564 struct trie_ctx *ctx = &trie_ctx[j];
1566 /* On-demand trie lookup. */
1567 if (!ctx->lookup_done) {
1568 memset(&ctx->match_plens, 0, sizeof ctx->match_plens);
1569 ctx->maskbits = trie_lookup(ctx->trie, flow, &ctx->match_plens);
1570 ctx->lookup_done = true;
1572 /* Possible to skip the rest of the subtable if subtable's
1573 * prefix on the field is not included in the lookup result. */
1574 if (!be_get_bit_at(&ctx->match_plens.be32, field_plen[j] - 1)) {
1575 /* We want the trie lookup to never result in unwildcarding
1576 * any bits that would not be unwildcarded otherwise.
1577 * Since the trie is shared by the whole classifier, it is
1578 * possible that the 'maskbits' contain bits that are
1579 * irrelevant for the partition relevant for the current
1580 * packet. Hence the checks below. */
1582 /* Check that the trie result will not unwildcard more bits
1583 * than this subtable would otherwise. */
1584 if (ctx->maskbits <= field_plen[j]) {
1585 /* Unwildcard the bits and skip the rest. */
1586 mask_set_prefix_bits(wc, ctx->be32ofs, ctx->maskbits);
1587 /* Note: Prerequisite already unwildcarded, as the only
1588 * prerequisite of the supported trie lookup fields is
1589 * the ethertype, which is always unwildcarded. */
1592 /* Can skip if the field is already unwildcarded. */
1593 if (mask_prefix_bits_set(wc, ctx->be32ofs, ctx->maskbits)) {
1602 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1603 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1604 * value has the correct value in 'target'.
1606 * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
1607 * target, mask) but this is faster because of the invariant that
1608 * flow->map and mask->masks.map are the same, and that this version
1609 * takes the 'wc'. */
1611 miniflow_and_mask_matches_flow(const struct miniflow *flow,
1612 const struct minimask *mask,
1613 const struct flow *target)
1615 const uint64_t *flowp = miniflow_get_values(flow);
1616 const uint64_t *maskp = miniflow_get_values(&mask->masks);
1617 const uint64_t *target_u64 = (const uint64_t *)target;
1620 FLOWMAP_FOR_EACH_MAP (map, mask->masks.map) {
1623 MAP_FOR_EACH_INDEX (idx, map) {
1624 if ((*flowp++ ^ target_u64[idx]) & *maskp++) {
1628 target_u64 += MAP_T_BITS;
1633 static inline const struct cls_match *
1634 find_match(const struct cls_subtable *subtable, cls_version_t version,
1635 const struct flow *flow, uint32_t hash)
1637 const struct cls_match *head, *rule;
1639 CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1640 if (OVS_LIKELY(miniflow_and_mask_matches_flow(&head->flow,
1643 /* Return highest priority rule that is visible. */
1644 CLS_MATCH_FOR_EACH (rule, head) {
1645 if (OVS_LIKELY(cls_match_visible_in_version(rule, version))) {
1655 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1656 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1657 * value has the correct value in 'target'.
1659 * This function is equivalent to miniflow_and_mask_matches_flow() but this
1660 * version fills in the mask bits in 'wc'. */
1662 miniflow_and_mask_matches_flow_wc(const struct miniflow *flow,
1663 const struct minimask *mask,
1664 const struct flow *target,
1665 struct flow_wildcards *wc)
1667 const uint64_t *flowp = miniflow_get_values(flow);
1668 const uint64_t *maskp = miniflow_get_values(&mask->masks);
1669 const uint64_t *target_u64 = (const uint64_t *)target;
1670 uint64_t *wc_u64 = (uint64_t *)&wc->masks;
1675 FLOWMAP_FOR_EACH_MAP (map, mask->masks.map) {
1676 MAP_FOR_EACH_INDEX(idx, map) {
1677 uint64_t msk = *maskp++;
1679 diff = (*flowp++ ^ target_u64[idx]) & msk;
1684 /* Fill in the bits that were looked at. */
1687 target_u64 += MAP_T_BITS;
1688 wc_u64 += MAP_T_BITS;
1693 /* Only unwildcard if none of the differing bits is already
1695 if (!(wc_u64[idx] & diff)) {
1696 /* Keep one bit of the difference. The selected bit may be
1697 * different in big-endian v.s. little-endian systems. */
1698 wc_u64[idx] |= rightmost_1bit(diff);
1703 static const struct cls_match *
1704 find_match_wc(const struct cls_subtable *subtable, cls_version_t version,
1705 const struct flow *flow, struct trie_ctx trie_ctx[CLS_MAX_TRIES],
1706 unsigned int n_tries, struct flow_wildcards *wc)
1708 if (OVS_UNLIKELY(!wc)) {
1709 return find_match(subtable, version, flow,
1710 flow_hash_in_minimask(flow, &subtable->mask, 0));
1713 uint32_t basis = 0, hash;
1714 const struct cls_match *rule = NULL;
1715 struct flowmap stages_map = FLOWMAP_EMPTY_INITIALIZER;
1716 unsigned int mask_offset = 0;
1719 /* Try to finish early by checking fields in segments. */
1720 for (i = 0; i < subtable->n_indices; i++) {
1721 const struct cmap_node *inode;
1723 if (check_tries(trie_ctx, n_tries, subtable->trie_plen,
1724 subtable->index_maps[i], flow, wc)) {
1725 /* 'wc' bits for the trie field set, now unwildcard the preceding
1726 * bits used so far. */
1730 /* Accumulate the map used so far. */
1731 stages_map = flowmap_or(stages_map, subtable->index_maps[i]);
1733 hash = flow_hash_in_minimask_range(flow, &subtable->mask,
1734 subtable->index_maps[i],
1735 &mask_offset, &basis);
1737 inode = cmap_find(&subtable->indices[i], hash);
1742 /* If we have narrowed down to a single rule already, check whether
1743 * that rule matches. Either way, we're done.
1745 * (Rare) hash collisions may cause us to miss the opportunity for this
1747 if (!cmap_node_next(inode)) {
1748 const struct cls_match *head;
1750 ASSIGN_CONTAINER(head, inode - i, index_nodes);
1751 if (miniflow_and_mask_matches_flow_wc(&head->flow, &subtable->mask,
1753 /* Return highest priority rule that is visible. */
1754 CLS_MATCH_FOR_EACH (rule, head) {
1755 if (OVS_LIKELY(cls_match_visible_in_version(rule,
1764 /* Trie check for the final range. */
1765 if (check_tries(trie_ctx, n_tries, subtable->trie_plen,
1766 subtable->index_maps[i], flow, wc)) {
1769 hash = flow_hash_in_minimask_range(flow, &subtable->mask,
1770 subtable->index_maps[i],
1771 &mask_offset, &basis);
1772 rule = find_match(subtable, version, flow, hash);
1773 if (!rule && subtable->ports_mask_len) {
1774 /* The final stage had ports, but there was no match. Instead of
1775 * unwildcarding all the ports bits, use the ports trie to figure out a
1776 * smaller set of bits to unwildcard. */
1778 ovs_be32 value, plens, mask;
1780 mask = MINIFLOW_GET_BE32(&subtable->mask.masks, tp_src);
1781 value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
1782 mbits = trie_lookup_value(&subtable->ports_trie, &value, &plens, 32);
1784 ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
1785 mask & be32_prefix_mask(mbits);
1790 /* Must unwildcard all the fields, as they were looked at. */
1791 flow_wildcards_fold_minimask(wc, &subtable->mask);
1795 /* Unwildcard the bits in stages so far, as they were used in determining
1796 * there is no match. */
1797 flow_wildcards_fold_minimask_in_map(wc, &subtable->mask, stages_map);
1801 static struct cls_match *
1802 find_equal(const struct cls_subtable *subtable, const struct miniflow *flow,
1805 struct cls_match *head;
1807 CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1808 if (miniflow_equal(&head->flow, flow)) {
1815 /* A longest-prefix match tree. */
1817 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1818 * Prefixes are in the network byte order, and the offset 0 corresponds to
1819 * the most significant bit of the first byte. The offset can be read as
1820 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1822 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1826 pr += ofs / 32; /* Where to start. */
1827 ofs %= 32; /* How many bits to skip at 'pr'. */
1829 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1830 if (plen > 32 - ofs) { /* Need more than we have already? */
1831 prefix |= ntohl(*++pr) >> (32 - ofs);
1833 /* Return with possible unwanted bits at the end. */
1837 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1838 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1839 * corresponds to the most significant bit of the first byte. The offset can
1840 * be read as "how many bits to skip from the start of the prefix starting at
1843 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1848 if (plen > TRIE_PREFIX_BITS) {
1849 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1851 /* Return with unwanted bits cleared. */
1852 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1855 /* Return the number of equal bits in 'n_bits' of 'prefix's MSBs and a 'value'
1856 * starting at "MSB 0"-based offset 'ofs'. */
1858 prefix_equal_bits(uint32_t prefix, unsigned int n_bits, const ovs_be32 value[],
1861 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, n_bits);
1862 /* Set the bit after the relevant bits to limit the result. */
1863 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - n_bits));
1866 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1867 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1869 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1870 unsigned int ofs, unsigned int plen)
1872 return prefix_equal_bits(node->prefix, MIN(node->n_bits, plen - ofs),
1876 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1877 * be greater than 31. */
1879 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1881 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1884 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1885 * be between 0 and 31, inclusive. */
1887 get_bit_at(const uint32_t prefix, unsigned int ofs)
1889 return (prefix >> (31 - ofs)) & 1u;
1892 /* Create new branch. */
1893 static struct trie_node *
1894 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1895 unsigned int n_rules)
1897 struct trie_node *node = xmalloc(sizeof *node);
1899 node->prefix = trie_get_prefix(prefix, ofs, plen);
1901 if (plen <= TRIE_PREFIX_BITS) {
1902 node->n_bits = plen;
1903 ovsrcu_set_hidden(&node->edges[0], NULL);
1904 ovsrcu_set_hidden(&node->edges[1], NULL);
1905 node->n_rules = n_rules;
1906 } else { /* Need intermediate nodes. */
1907 struct trie_node *subnode = trie_branch_create(prefix,
1908 ofs + TRIE_PREFIX_BITS,
1909 plen - TRIE_PREFIX_BITS,
1911 int bit = get_bit_at(subnode->prefix, 0);
1912 node->n_bits = TRIE_PREFIX_BITS;
1913 ovsrcu_set_hidden(&node->edges[bit], subnode);
1914 ovsrcu_set_hidden(&node->edges[!bit], NULL);
1921 trie_node_destroy(const struct trie_node *node)
1923 ovsrcu_postpone(free, CONST_CAST(struct trie_node *, node));
1926 /* Copy a trie node for modification and postpone delete the old one. */
1927 static struct trie_node *
1928 trie_node_rcu_realloc(const struct trie_node *node)
1930 struct trie_node *new_node = xmalloc(sizeof *node);
1933 trie_node_destroy(node);
1939 trie_destroy(rcu_trie_ptr *trie)
1941 struct trie_node *node = ovsrcu_get_protected(struct trie_node *, trie);
1944 ovsrcu_set_hidden(trie, NULL);
1945 trie_destroy(&node->edges[0]);
1946 trie_destroy(&node->edges[1]);
1947 trie_node_destroy(node);
1952 trie_is_leaf(const struct trie_node *trie)
1955 return !ovsrcu_get(struct trie_node *, &trie->edges[0])
1956 && !ovsrcu_get(struct trie_node *, &trie->edges[1]);
1960 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1961 unsigned int n_bits)
1963 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1966 for (i = 0; i < n_bits / 32; i++) {
1967 mask[i] = OVS_BE32_MAX;
1970 mask[i] |= htonl(~0u << (32 - n_bits % 32));
1975 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
1976 unsigned int n_bits)
1978 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1980 ovs_be32 zeroes = 0;
1982 for (i = 0; i < n_bits / 32; i++) {
1986 zeroes |= ~mask[i] & htonl(~0u << (32 - n_bits % 32));
1989 return !zeroes; /* All 'n_bits' bits set. */
1992 static rcu_trie_ptr *
1993 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
1996 return node->edges + be_get_bit_at(value, ofs);
1999 static const struct trie_node *
2000 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
2003 return ovsrcu_get(struct trie_node *,
2004 &node->edges[be_get_bit_at(value, ofs)]);
2007 /* Set the bit at ("MSB 0"-based) offset 'ofs'. 'ofs' can be greater than 31.
2010 be_set_bit_at(ovs_be32 value[], unsigned int ofs)
2012 ((uint8_t *)value)[ofs / 8] |= 1u << (7 - ofs % 8);
2015 /* Returns the number of bits in the prefix mask necessary to determine a
2016 * mismatch, in case there are longer prefixes in the tree below the one that
2018 * '*plens' will have a bit set for each prefix length that may have matching
2019 * rules. The caller is responsible for clearing the '*plens' prior to
2023 trie_lookup_value(const rcu_trie_ptr *trie, const ovs_be32 value[],
2024 ovs_be32 plens[], unsigned int n_bits)
2026 const struct trie_node *prev = NULL;
2027 const struct trie_node *node = ovsrcu_get(struct trie_node *, trie);
2028 unsigned int match_len = 0; /* Number of matching bits. */
2030 for (; node; prev = node, node = trie_next_node(node, value, match_len)) {
2031 unsigned int eqbits;
2032 /* Check if this edge can be followed. */
2033 eqbits = prefix_equal_bits(node->prefix, node->n_bits, value,
2035 match_len += eqbits;
2036 if (eqbits < node->n_bits) { /* Mismatch, nothing more to be found. */
2037 /* Bit at offset 'match_len' differed. */
2038 return match_len + 1; /* Includes the first mismatching bit. */
2040 /* Full match, check if rules exist at this prefix length. */
2041 if (node->n_rules > 0) {
2042 be_set_bit_at(plens, match_len - 1);
2044 if (match_len >= n_bits) {
2045 return n_bits; /* Full prefix. */
2048 /* node == NULL. Full match so far, but we tried to follow an
2049 * non-existing branch. Need to exclude the other branch if it exists
2050 * (it does not if we were called on an empty trie or 'prev' is a leaf
2052 return !prev || trie_is_leaf(prev) ? match_len : match_len + 1;
2056 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
2057 union trie_prefix *plens)
2059 const struct mf_field *mf = trie->field;
2061 /* Check that current flow matches the prerequisites for the trie
2062 * field. Some match fields are used for multiple purposes, so we
2063 * must check that the trie is relevant for this flow. */
2064 if (mf_are_prereqs_ok(mf, flow)) {
2065 return trie_lookup_value(&trie->root,
2066 &((ovs_be32 *)flow)[mf->flow_be32ofs],
2067 &plens->be32, mf->n_bits);
2069 memset(plens, 0xff, sizeof *plens); /* All prefixes, no skipping. */
2070 return 0; /* Value not used in this case. */
2073 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
2074 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
2075 * 'miniflow_index' is not NULL. */
2077 minimask_get_prefix_len(const struct minimask *minimask,
2078 const struct mf_field *mf)
2080 unsigned int n_bits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
2081 uint8_t be32_ofs = mf->flow_be32ofs;
2082 uint8_t be32_end = be32_ofs + mf->n_bytes / 4;
2084 for (; be32_ofs < be32_end; ++be32_ofs) {
2085 uint32_t mask = ntohl(minimask_get_be32(minimask, be32_ofs));
2087 /* Validate mask, count the mask length. */
2090 return 0; /* No bits allowed after mask ended. */
2093 if (~mask & (~mask + 1)) {
2094 return 0; /* Mask not contiguous. */
2096 mask_tz = ctz32(mask);
2097 n_bits += 32 - mask_tz;
2105 * This is called only when mask prefix is known to be CIDR and non-zero.
2106 * Relies on the fact that the flow and mask have the same map, and since
2107 * the mask is CIDR, the storage for the flow field exists even if it
2108 * happened to be zeros.
2110 static const ovs_be32 *
2111 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
2113 size_t u64_ofs = mf->flow_be32ofs / 2;
2115 return (OVS_FORCE const ovs_be32 *)miniflow_get__(match->flow, u64_ofs)
2116 + (mf->flow_be32ofs & 1);
2119 /* Insert rule in to the prefix tree.
2120 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2123 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2125 trie_insert_prefix(&trie->root,
2126 minimatch_get_prefix(&rule->match, trie->field), mlen);
2130 trie_insert_prefix(rcu_trie_ptr *edge, const ovs_be32 *prefix, int mlen)
2132 struct trie_node *node;
2135 /* Walk the tree. */
2136 for (; (node = ovsrcu_get_protected(struct trie_node *, edge));
2137 edge = trie_next_edge(node, prefix, ofs)) {
2138 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2140 if (eqbits < node->n_bits) {
2141 /* Mismatch, new node needs to be inserted above. */
2142 int old_branch = get_bit_at(node->prefix, eqbits);
2143 struct trie_node *new_parent;
2145 new_parent = trie_branch_create(prefix, ofs - eqbits, eqbits,
2146 ofs == mlen ? 1 : 0);
2147 /* Copy the node to modify it. */
2148 node = trie_node_rcu_realloc(node);
2149 /* Adjust the new node for its new position in the tree. */
2150 node->prefix <<= eqbits;
2151 node->n_bits -= eqbits;
2152 ovsrcu_set_hidden(&new_parent->edges[old_branch], node);
2154 /* Check if need a new branch for the new rule. */
2156 ovsrcu_set_hidden(&new_parent->edges[!old_branch],
2157 trie_branch_create(prefix, ofs, mlen - ofs,
2160 ovsrcu_set(edge, new_parent); /* Publish changes. */
2163 /* Full match so far. */
2166 /* Full match at the current node, rule needs to be added here. */
2171 /* Must insert a new tree branch for the new rule. */
2172 ovsrcu_set(edge, trie_branch_create(prefix, ofs, mlen - ofs, 1));
2175 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2178 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2180 trie_remove_prefix(&trie->root,
2181 minimatch_get_prefix(&rule->match, trie->field), mlen);
2184 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2187 trie_remove_prefix(rcu_trie_ptr *root, const ovs_be32 *prefix, int mlen)
2189 struct trie_node *node;
2190 rcu_trie_ptr *edges[sizeof(union trie_prefix) * CHAR_BIT];
2191 int depth = 0, ofs = 0;
2193 /* Walk the tree. */
2194 for (edges[0] = root;
2195 (node = ovsrcu_get_protected(struct trie_node *, edges[depth]));
2196 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
2197 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2199 if (eqbits < node->n_bits) {
2200 /* Mismatch, nothing to be removed. This should never happen, as
2201 * only rules in the classifier are ever removed. */
2202 break; /* Log a warning. */
2204 /* Full match so far. */
2208 /* Full prefix match at the current node, remove rule here. */
2209 if (!node->n_rules) {
2210 break; /* Log a warning. */
2214 /* Check if can prune the tree. */
2215 while (!node->n_rules) {
2216 struct trie_node *next,
2217 *edge0 = ovsrcu_get_protected(struct trie_node *,
2219 *edge1 = ovsrcu_get_protected(struct trie_node *,
2222 if (edge0 && edge1) {
2223 break; /* A branching point, cannot prune. */
2226 /* Else have at most one child node, remove this node. */
2227 next = edge0 ? edge0 : edge1;
2230 if (node->n_bits + next->n_bits > TRIE_PREFIX_BITS) {
2231 break; /* Cannot combine. */
2233 next = trie_node_rcu_realloc(next); /* Modify. */
2235 /* Combine node with next. */
2236 next->prefix = node->prefix | next->prefix >> node->n_bits;
2237 next->n_bits += node->n_bits;
2239 /* Update the parent's edge. */
2240 ovsrcu_set(edges[depth], next); /* Publish changes. */
2241 trie_node_destroy(node);
2243 if (next || !depth) {
2244 /* Branch not pruned or at root, nothing more to do. */
2247 node = ovsrcu_get_protected(struct trie_node *,
2253 /* Cannot go deeper. This should never happen, since only rules
2254 * that actually exist in the classifier are ever removed. */
2255 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");
2259 #define CLS_MATCH_POISON (struct cls_match *)(UINTPTR_MAX / 0xf * 0xb)
2262 cls_match_free_cb(struct cls_match *rule)
2264 ovsrcu_set_hidden(&rule->next, CLS_MATCH_POISON);