2 * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 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 /* Ports trie depends on both ports sharing the same ovs_be32. */
35 #define TP_PORTS_OFS32 (offsetof(struct flow, tp_src) / 4)
36 BUILD_ASSERT_DECL(TP_PORTS_OFS32 == offsetof(struct flow, tp_dst) / 4);
37 BUILD_ASSERT_DECL(TP_PORTS_OFS32 % 2 == 0);
38 #define TP_PORTS_OFS64 (TP_PORTS_OFS32 / 2)
40 static struct cls_match *
41 cls_match_alloc(const struct cls_rule *rule)
43 int count = count_1bits(rule->match.flow.map);
45 struct cls_match *cls_match
46 = xmalloc(sizeof *cls_match - sizeof cls_match->flow.inline_values
47 + MINIFLOW_VALUES_SIZE(count));
49 rculist_init(&cls_match->list);
50 *CONST_CAST(const struct cls_rule **, &cls_match->cls_rule) = rule;
51 *CONST_CAST(int *, &cls_match->priority) = rule->priority;
52 miniflow_clone_inline(CONST_CAST(struct miniflow *, &cls_match->flow),
53 &rule->match.flow, count);
58 static struct cls_subtable *find_subtable(const struct classifier *cls,
59 const struct minimask *);
60 static struct cls_subtable *insert_subtable(struct classifier *cls,
61 const struct minimask *);
62 static void destroy_subtable(struct classifier *cls, struct cls_subtable *);
64 static const struct cls_match *find_match_wc(const struct cls_subtable *,
68 struct flow_wildcards *);
69 static struct cls_match *find_equal(const struct cls_subtable *,
70 const struct miniflow *, uint32_t hash);
72 static inline const struct cls_match *
73 next_rule_in_list__(const struct cls_match *rule)
75 const struct cls_match *next = NULL;
76 next = OBJECT_CONTAINING(rculist_next(&rule->list), next, list);
80 static inline const struct cls_match *
81 next_rule_in_list(const struct cls_match *rule)
83 const struct cls_match *next = next_rule_in_list__(rule);
84 return next->priority < rule->priority ? next : NULL;
87 static inline struct cls_match *
88 next_rule_in_list_protected__(struct cls_match *rule)
90 struct cls_match *next = NULL;
91 next = OBJECT_CONTAINING(rculist_next_protected(&rule->list), next, list);
95 static inline struct cls_match *
96 next_rule_in_list_protected(struct cls_match *rule)
98 struct cls_match *next = next_rule_in_list_protected__(rule);
99 return next->priority < rule->priority ? next : NULL;
102 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list. */
103 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD) \
104 for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
105 #define FOR_EACH_RULE_IN_LIST_PROTECTED(RULE, HEAD) \
106 for ((RULE) = (HEAD); (RULE) != NULL; \
107 (RULE) = next_rule_in_list_protected(RULE))
109 static unsigned int minimask_get_prefix_len(const struct minimask *,
110 const struct mf_field *);
111 static void trie_init(struct classifier *cls, int trie_idx,
112 const struct mf_field *);
113 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
114 union mf_value *plens);
115 static unsigned int trie_lookup_value(const rcu_trie_ptr *,
116 const ovs_be32 value[], ovs_be32 plens[],
117 unsigned int value_bits);
118 static void trie_destroy(rcu_trie_ptr *);
119 static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
120 static void trie_insert_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
122 static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
123 static void trie_remove_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
125 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
126 unsigned int n_bits);
127 static bool mask_prefix_bits_set(const struct flow_wildcards *,
128 uint8_t be32ofs, unsigned int n_bits);
133 cls_rule_init__(struct cls_rule *rule, unsigned int priority)
135 rculist_init(&rule->node);
136 rule->priority = priority;
137 rule->cls_match = NULL;
140 /* Initializes 'rule' to match packets specified by 'match' at the given
141 * 'priority'. 'match' must satisfy the invariant described in the comment at
142 * the definition of struct match.
144 * The caller must eventually destroy 'rule' with cls_rule_destroy().
146 * Clients should not use priority INT_MIN. (OpenFlow uses priorities between
147 * 0 and UINT16_MAX, inclusive.) */
149 cls_rule_init(struct cls_rule *rule, const struct match *match, int priority)
151 cls_rule_init__(rule, priority);
152 minimatch_init(&rule->match, match);
155 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
157 cls_rule_init_from_minimatch(struct cls_rule *rule,
158 const struct minimatch *match, int priority)
160 cls_rule_init__(rule, priority);
161 minimatch_clone(&rule->match, match);
164 /* Initializes 'dst' as a copy of 'src'.
166 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
168 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
170 cls_rule_init__(dst, src->priority);
171 minimatch_clone(&dst->match, &src->match);
174 /* Initializes 'dst' with the data in 'src', destroying 'src'.
175 * 'src' must be a cls_rule NOT in a classifier.
177 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
179 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
181 ovs_assert(!src->cls_match); /* Must not be in a classifier. */
182 cls_rule_init__(dst, src->priority);
183 minimatch_move(&dst->match, &src->match);
186 /* Frees memory referenced by 'rule'. Doesn't free 'rule' itself (it's
187 * normally embedded into a larger structure).
189 * ('rule' must not currently be in a classifier.) */
191 cls_rule_destroy(struct cls_rule *rule)
193 ovs_assert(!rule->cls_match); /* Must not be in a classifier. */
195 /* Check that the rule has been properly removed from the classifier and
196 * that the destruction only happens after the RCU grace period, or that
197 * the rule was never inserted to the classifier in the first place. */
198 ovs_assert(rculist_next_protected(&rule->node) == RCULIST_POISON
199 || rculist_is_empty(&rule->node));
201 minimatch_destroy(&rule->match);
204 /* Returns true if 'a' and 'b' match the same packets at the same priority,
205 * false if they differ in some way. */
207 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
209 return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
212 /* Returns a hash value for 'rule', folding in 'basis'. */
214 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
216 return minimatch_hash(&rule->match, hash_int(rule->priority, basis));
219 /* Appends a string describing 'rule' to 's'. */
221 cls_rule_format(const struct cls_rule *rule, struct ds *s)
223 minimatch_format(&rule->match, s, rule->priority);
226 /* Returns true if 'rule' matches every packet, false otherwise. */
228 cls_rule_is_catchall(const struct cls_rule *rule)
230 return minimask_is_catchall(&rule->match.mask);
233 /* Initializes 'cls' as a classifier that initially contains no classification
236 classifier_init(struct classifier *cls, const uint8_t *flow_segments)
239 cmap_init(&cls->subtables_map);
240 pvector_init(&cls->subtables);
241 cmap_init(&cls->partitions);
242 cls->n_flow_segments = 0;
244 while (cls->n_flow_segments < CLS_MAX_INDICES
245 && *flow_segments < FLOW_U64S) {
246 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
250 for (int i = 0; i < CLS_MAX_TRIES; i++) {
251 trie_init(cls, i, NULL);
256 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
257 * caller's responsibility.
258 * May only be called after all the readers have been terminated. */
260 classifier_destroy(struct classifier *cls)
263 struct cls_partition *partition;
264 struct cls_subtable *subtable;
267 for (i = 0; i < cls->n_tries; i++) {
268 trie_destroy(&cls->tries[i].root);
271 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
272 destroy_subtable(cls, subtable);
274 cmap_destroy(&cls->subtables_map);
276 CMAP_FOR_EACH (partition, cmap_node, &cls->partitions) {
277 ovsrcu_postpone(free, partition);
279 cmap_destroy(&cls->partitions);
281 pvector_destroy(&cls->subtables);
285 /* Set the fields for which prefix lookup should be performed. */
287 classifier_set_prefix_fields(struct classifier *cls,
288 const enum mf_field_id *trie_fields,
289 unsigned int n_fields)
291 const struct mf_field * new_fields[CLS_MAX_TRIES];
292 struct mf_bitmap fields = MF_BITMAP_INITIALIZER;
294 bool changed = false;
296 for (i = 0; i < n_fields && n_tries < CLS_MAX_TRIES; i++) {
297 const struct mf_field *field = mf_from_id(trie_fields[i]);
298 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
299 /* Incompatible field. This is the only place where we
300 * enforce these requirements, but the rest of the trie code
301 * depends on the flow_be32ofs to be non-negative and the
302 * field length to be a multiple of 32 bits. */
306 if (bitmap_is_set(fields.bm, trie_fields[i])) {
307 /* Duplicate field, there is no need to build more than
308 * one index for any one field. */
311 bitmap_set1(fields.bm, trie_fields[i]);
313 new_fields[n_tries] = NULL;
314 if (n_tries >= cls->n_tries || field != cls->tries[n_tries].field) {
315 new_fields[n_tries] = field;
321 if (changed || n_tries < cls->n_tries) {
322 struct cls_subtable *subtable;
324 /* Trie configuration needs to change. Disable trie lookups
325 * for the tries that are changing and wait all the current readers
326 * with the old configuration to be done. */
328 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
329 for (i = 0; i < cls->n_tries; i++) {
330 if ((i < n_tries && new_fields[i]) || i >= n_tries) {
331 if (subtable->trie_plen[i]) {
332 subtable->trie_plen[i] = 0;
338 /* Synchronize if any readers were using tries. The readers may
339 * temporarily function without the trie lookup based optimizations. */
341 /* ovsrcu_synchronize() functions as a memory barrier, so it does
342 * not matter that subtable->trie_plen is not atomic. */
343 ovsrcu_synchronize();
346 /* Now set up the tries. */
347 for (i = 0; i < n_tries; i++) {
349 trie_init(cls, i, new_fields[i]);
352 /* Destroy the rest, if any. */
353 for (; i < cls->n_tries; i++) {
354 trie_init(cls, i, NULL);
357 cls->n_tries = n_tries;
361 return false; /* No change. */
365 trie_init(struct classifier *cls, int trie_idx, const struct mf_field *field)
367 struct cls_trie *trie = &cls->tries[trie_idx];
368 struct cls_subtable *subtable;
370 if (trie_idx < cls->n_tries) {
371 trie_destroy(&trie->root);
373 ovsrcu_set_hidden(&trie->root, NULL);
377 /* Add existing rules to the new trie. */
378 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
381 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
383 struct cls_match *head;
385 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
386 trie_insert(trie, head->cls_rule, plen);
389 /* Initialize subtable's prefix length on this field. This will
390 * allow readers to use the trie. */
391 atomic_thread_fence(memory_order_release);
392 subtable->trie_plen[trie_idx] = plen;
396 /* Returns true if 'cls' contains no classification rules, false otherwise.
397 * Checking the cmap requires no locking. */
399 classifier_is_empty(const struct classifier *cls)
401 return cmap_is_empty(&cls->subtables_map);
404 /* Returns the number of rules in 'cls'. */
406 classifier_count(const struct classifier *cls)
408 /* n_rules is an int, so in the presence of concurrent writers this will
409 * return either the old or a new value. */
414 hash_metadata(ovs_be64 metadata)
416 return hash_uint64((OVS_FORCE uint64_t) metadata);
419 static struct cls_partition *
420 find_partition(const struct classifier *cls, ovs_be64 metadata, uint32_t hash)
422 struct cls_partition *partition;
424 CMAP_FOR_EACH_WITH_HASH (partition, cmap_node, hash, &cls->partitions) {
425 if (partition->metadata == metadata) {
433 static struct cls_partition *
434 create_partition(struct classifier *cls, struct cls_subtable *subtable,
437 uint32_t hash = hash_metadata(metadata);
438 struct cls_partition *partition = find_partition(cls, metadata, hash);
440 partition = xmalloc(sizeof *partition);
441 partition->metadata = metadata;
443 tag_tracker_init(&partition->tracker);
444 cmap_insert(&cls->partitions, &partition->cmap_node, hash);
446 tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
450 static inline ovs_be32 minimatch_get_ports(const struct minimatch *match)
452 /* Could optimize to use the same map if needed for fast path. */
453 return MINIFLOW_GET_BE32(&match->flow, tp_src)
454 & MINIFLOW_GET_BE32(&match->mask.masks, tp_src);
458 subtable_replace_head_rule(struct classifier *cls OVS_UNUSED,
459 struct cls_subtable *subtable,
460 struct cls_match *head, struct cls_match *new,
461 uint32_t hash, uint32_t ihash[CLS_MAX_INDICES])
463 /* Rule's data is already in the tries. */
465 new->partition = head->partition; /* Steal partition, if any. */
466 head->partition = NULL;
468 for (int i = 0; i < subtable->n_indices; i++) {
469 cmap_replace(&subtable->indices[i], &head->index_nodes[i],
470 &new->index_nodes[i], ihash[i]);
472 cmap_replace(&subtable->rules, &head->cmap_node, &new->cmap_node, hash);
475 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
476 * must not modify or free it.
478 * If 'cls' already contains an identical rule (including wildcards, values of
479 * fixed fields, and priority), replaces the old rule by 'rule' and returns the
480 * rule that was replaced. The caller takes ownership of the returned rule and
481 * is thus responsible for destroying it with cls_rule_destroy(), after RCU
482 * grace period has passed (see ovsrcu_postpone()).
484 * Returns NULL if 'cls' does not contain a rule with an identical key, after
485 * inserting the new rule. In this case, no rules are displaced by the new
486 * rule, even rules that cannot have any effect because the new rule matches a
487 * superset of their flows and has higher priority.
489 const struct cls_rule *
490 classifier_replace(struct classifier *cls, const struct cls_rule *rule)
492 struct cls_match *new = cls_match_alloc(rule);
493 struct cls_subtable *subtable;
494 uint32_t ihash[CLS_MAX_INDICES];
495 uint8_t prev_be64ofs = 0;
496 struct cls_match *head;
502 CONST_CAST(struct cls_rule *, rule)->cls_match = new;
504 subtable = find_subtable(cls, &rule->match.mask);
506 subtable = insert_subtable(cls, &rule->match.mask);
509 /* Compute hashes in segments. */
511 for (i = 0; i < subtable->n_indices; i++) {
512 ihash[i] = minimatch_hash_range(&rule->match, prev_be64ofs,
513 subtable->index_ofs[i], &basis);
514 prev_be64ofs = subtable->index_ofs[i];
516 hash = minimatch_hash_range(&rule->match, prev_be64ofs, FLOW_U64S, &basis);
518 head = find_equal(subtable, &rule->match.flow, hash);
520 /* Add rule to tries.
522 * Concurrent readers might miss seeing the rule until this update,
523 * which might require being fixed up by revalidation later. */
524 for (i = 0; i < cls->n_tries; i++) {
525 if (subtable->trie_plen[i]) {
526 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
530 /* Add rule to ports trie. */
531 if (subtable->ports_mask_len) {
532 /* We mask the value to be inserted to always have the wildcarded
533 * bits in known (zero) state, so we can include them in comparison
534 * and they will always match (== their original value does not
536 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
538 trie_insert_prefix(&subtable->ports_trie, &masked_ports,
539 subtable->ports_mask_len);
542 /* Add rule to partitions.
544 * Concurrent readers might miss seeing the rule until this update,
545 * which might require being fixed up by revalidation later. */
546 new->partition = NULL;
547 if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
548 ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
550 new->partition = create_partition(cls, subtable, metadata);
553 /* Make rule visible to lookups. */
555 /* Add new node to segment indices.
557 * Readers may find the rule in the indices before the rule is visible
558 * in the subtables 'rules' map. This may result in us losing the
559 * opportunity to quit lookups earlier, resulting in sub-optimal
560 * wildcarding. This will be fixed later by revalidation (always
561 * scheduled after flow table changes). */
562 for (i = 0; i < subtable->n_indices; i++) {
563 cmap_insert(&subtable->indices[i], &new->index_nodes[i], ihash[i]);
565 n_rules = cmap_insert(&subtable->rules, &new->cmap_node, hash);
566 } else { /* Equal rules exist in the classifier already. */
567 struct cls_match *iter;
569 /* Scan the list for the insertion point that will keep the list in
570 * order of decreasing priority. */
571 FOR_EACH_RULE_IN_LIST_PROTECTED (iter, head) {
572 if (rule->priority >= iter->priority) {
577 /* 'iter' now at the insertion point or NULL it at end. */
579 struct cls_rule *old;
581 if (rule->priority == iter->priority) {
582 rculist_replace(&new->list, &iter->list);
583 old = CONST_CAST(struct cls_rule *, iter->cls_rule);
585 rculist_insert(&iter->list, &new->list);
589 /* Replace the existing head in data structures, if rule is the new
592 subtable_replace_head_rule(cls, subtable, head, new, hash,
597 ovsrcu_postpone(free, iter);
598 old->cls_match = NULL;
600 /* No change in subtable's max priority or max count. */
602 /* Make rule visible to iterators. */
603 rculist_replace(CONST_CAST(struct rculist *, &rule->node),
606 /* Return displaced rule. Caller is responsible for keeping it
607 * around until all threads quiesce. */
611 rculist_push_back(&head->list, &new->list);
615 /* Make rule visible to iterators. */
616 rculist_push_back(&subtable->rules_list,
617 CONST_CAST(struct rculist *, &rule->node));
619 /* Rule was added, not replaced. Update 'subtable's 'max_priority' and
620 * 'max_count', if necessary.
622 * The rule was already inserted, but concurrent readers may not see the
623 * rule yet as the subtables vector is not updated yet. This will have to
624 * be fixed by revalidation later. */
626 subtable->max_priority = rule->priority;
627 subtable->max_count = 1;
628 pvector_insert(&cls->subtables, subtable, rule->priority);
629 } else if (rule->priority == subtable->max_priority) {
630 ++subtable->max_count;
631 } else if (rule->priority > subtable->max_priority) {
632 subtable->max_priority = rule->priority;
633 subtable->max_count = 1;
634 pvector_change_priority(&cls->subtables, subtable, rule->priority);
637 /* Nothing was replaced. */
641 pvector_publish(&cls->subtables);
647 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
648 * must not modify or free it.
650 * 'cls' must not contain an identical rule (including wildcards, values of
651 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
654 classifier_insert(struct classifier *cls, const struct cls_rule *rule)
656 const struct cls_rule *displaced_rule = classifier_replace(cls, rule);
657 ovs_assert(!displaced_rule);
660 /* Removes 'rule' from 'cls'. It is the caller's responsibility to destroy
661 * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
662 * resides, etc., as necessary.
664 * Does nothing if 'rule' has been already removed, or was never inserted.
666 * Returns the removed rule, or NULL, if it was already removed.
668 const struct cls_rule *
669 classifier_remove(struct classifier *cls, const struct cls_rule *rule)
671 struct cls_partition *partition;
672 struct cls_match *cls_match;
673 struct cls_subtable *subtable;
674 struct cls_match *prev;
675 struct cls_match *next;
677 uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
678 uint8_t prev_be64ofs = 0;
681 cls_match = rule->cls_match;
685 /* Mark as removed. */
686 CONST_CAST(struct cls_rule *, rule)->cls_match = NULL;
688 /* Remove 'rule' from the subtable's rules list. */
689 rculist_remove(CONST_CAST(struct rculist *, &rule->node));
691 INIT_CONTAINER(prev, rculist_back_protected(&cls_match->list), list);
692 INIT_CONTAINER(next, rculist_next(&cls_match->list), list);
694 /* Remove from the list of equal rules. */
695 rculist_remove(&cls_match->list);
697 /* Check if this is NOT a head rule. */
698 if (prev->priority > rule->priority) {
699 /* Not the highest priority rule, no need to check subtable's
704 subtable = find_subtable(cls, &rule->match.mask);
705 ovs_assert(subtable);
707 for (i = 0; i < subtable->n_indices; i++) {
708 ihash[i] = minimatch_hash_range(&rule->match, prev_be64ofs,
709 subtable->index_ofs[i], &basis);
710 prev_be64ofs = subtable->index_ofs[i];
712 hash = minimatch_hash_range(&rule->match, prev_be64ofs, FLOW_U64S, &basis);
714 /* Head rule. Check if 'next' is an identical, lower-priority rule that
715 * will replace 'rule' in the data structures. */
716 if (next->priority < rule->priority) {
717 subtable_replace_head_rule(cls, subtable, cls_match, next, hash,
722 /* 'rule' is last of the kind in the classifier, must remove from all the
723 * data structures. */
725 if (subtable->ports_mask_len) {
726 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
728 trie_remove_prefix(&subtable->ports_trie,
729 &masked_ports, subtable->ports_mask_len);
731 for (i = 0; i < cls->n_tries; i++) {
732 if (subtable->trie_plen[i]) {
733 trie_remove(&cls->tries[i], rule, subtable->trie_plen[i]);
737 /* Remove rule node from indices. */
738 for (i = 0; i < subtable->n_indices; i++) {
739 cmap_remove(&subtable->indices[i], &cls_match->index_nodes[i],
742 n_rules = cmap_remove(&subtable->rules, &cls_match->cmap_node, hash);
744 partition = cls_match->partition;
746 tag_tracker_subtract(&partition->tracker, &partition->tags,
748 if (!partition->tags) {
749 cmap_remove(&cls->partitions, &partition->cmap_node,
750 hash_metadata(partition->metadata));
751 ovsrcu_postpone(free, partition);
756 destroy_subtable(cls, subtable);
759 if (subtable->max_priority == rule->priority
760 && --subtable->max_count == 0) {
761 /* Find the new 'max_priority' and 'max_count'. */
762 struct cls_match *head;
763 int max_priority = INT_MIN;
765 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
766 if (head->priority > max_priority) {
767 max_priority = head->priority;
768 subtable->max_count = 1;
769 } else if (head->priority == max_priority) {
770 ++subtable->max_count;
773 subtable->max_priority = max_priority;
774 pvector_change_priority(&cls->subtables, subtable, max_priority);
779 pvector_publish(&cls->subtables);
783 ovsrcu_postpone(free, cls_match);
789 /* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
790 * subtables which have a prefix match on the trie field, but whose prefix
791 * length is not indicated in 'match_plens'. For example, a subtable that
792 * has a 8-bit trie field prefix match can be skipped if
793 * !be_get_bit_at(&match_plens, 8 - 1). If skipped, 'maskbits' prefix bits
794 * must be unwildcarded to make datapath flow only match packets it should. */
796 const struct cls_trie *trie;
797 bool lookup_done; /* Status of the lookup. */
798 uint8_t be32ofs; /* U32 offset of the field in question. */
799 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
800 union mf_value match_plens; /* Bitmask of prefix lengths with possible
805 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
808 ctx->be32ofs = trie->field->flow_be32ofs;
809 ctx->lookup_done = false;
812 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
813 * Returns a null pointer if no rules in 'cls' match 'flow'. If multiple rules
814 * of equal priority match 'flow', returns one arbitrarily.
816 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
817 * set of bits that were significant in the lookup. At some point
818 * earlier, 'wc' should have been initialized (e.g., by
819 * flow_wildcards_init_catchall()).
821 * 'flow' is non-const to allow for temporary modifications during the lookup.
822 * Any changes are restored before returning. */
823 const struct cls_rule *
824 classifier_lookup(const struct classifier *cls, struct flow *flow,
825 struct flow_wildcards *wc)
827 const struct cls_partition *partition;
829 int best_priority = INT_MIN;
830 const struct cls_match *best;
831 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
832 struct cls_subtable *subtable;
834 /* Synchronize for cls->n_tries and subtable->trie_plen. They can change
835 * when table configuration changes, which happens typically only on
837 atomic_thread_fence(memory_order_acquire);
839 /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
840 * then 'flow' cannot possibly match in 'subtable':
842 * - If flow->metadata maps to a given 'partition', then we can use
843 * 'tags' for 'partition->tags'.
845 * - If flow->metadata has no partition, then no rule in 'cls' has an
846 * exact-match for flow->metadata. That means that we don't need to
847 * search any subtable that includes flow->metadata in its mask.
849 * In either case, we always need to search any cls_subtables that do not
850 * include flow->metadata in its mask. One way to do that would be to
851 * check the "cls_subtable"s explicitly for that, but that would require an
852 * extra branch per subtable. Instead, we mark such a cls_subtable's
853 * 'tags' as TAG_ALL and make sure that 'tags' is never empty. This means
854 * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
855 * need a special case.
857 partition = (cmap_is_empty(&cls->partitions)
859 : find_partition(cls, flow->metadata,
860 hash_metadata(flow->metadata)));
861 tags = partition ? partition->tags : TAG_ARBITRARY;
863 /* Initialize trie contexts for find_match_wc(). */
864 for (int i = 0; i < cls->n_tries; i++) {
865 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
869 PVECTOR_FOR_EACH_PRIORITY(subtable, best_priority, 2,
870 sizeof(struct cls_subtable), &cls->subtables) {
871 const struct cls_match *rule;
873 if (!tag_intersects(tags, subtable->tag)) {
877 rule = find_match_wc(subtable, flow, trie_ctx, cls->n_tries, wc);
878 if (rule && rule->priority > best_priority) {
879 best_priority = rule->priority;
884 return best ? best->cls_rule : NULL;
887 /* Finds and returns a rule in 'cls' with exactly the same priority and
888 * matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
889 * contain an exact match. */
890 const struct cls_rule *
891 classifier_find_rule_exactly(const struct classifier *cls,
892 const struct cls_rule *target)
894 const struct cls_match *head, *rule;
895 const struct cls_subtable *subtable;
897 subtable = find_subtable(cls, &target->match.mask);
902 head = find_equal(subtable, &target->match.flow,
903 miniflow_hash_in_minimask(&target->match.flow,
904 &target->match.mask, 0));
908 FOR_EACH_RULE_IN_LIST (rule, head) {
909 if (target->priority >= rule->priority) {
910 return target->priority == rule->priority ? rule->cls_rule : NULL;
916 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
917 * same matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
918 * contain an exact match. */
919 const struct cls_rule *
920 classifier_find_match_exactly(const struct classifier *cls,
921 const struct match *target, int priority)
923 const struct cls_rule *retval;
926 cls_rule_init(&cr, target, priority);
927 retval = classifier_find_rule_exactly(cls, &cr);
928 cls_rule_destroy(&cr);
933 /* Checks if 'target' would overlap any other rule in 'cls'. Two rules are
934 * considered to overlap if both rules have the same priority and a packet
937 * A trivial example of overlapping rules is two rules matching disjoint sets
938 * of fields. E.g., if one rule matches only on port number, while another only
939 * on dl_type, any packet from that specific port and with that specific
940 * dl_type could match both, if the rules also have the same priority. */
942 classifier_rule_overlaps(const struct classifier *cls,
943 const struct cls_rule *target)
945 struct cls_subtable *subtable;
947 /* Iterate subtables in the descending max priority order. */
948 PVECTOR_FOR_EACH_PRIORITY (subtable, target->priority - 1, 2,
949 sizeof(struct cls_subtable), &cls->subtables) {
950 uint64_t storage[FLOW_U64S];
951 struct minimask mask;
952 const struct cls_rule *rule;
954 minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
956 RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
957 if (rule->priority == target->priority
958 && miniflow_equal_in_minimask(&target->match.flow,
959 &rule->match.flow, &mask)) {
967 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
968 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
969 * function returns true if, for every field:
971 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
974 * - 'criteria' wildcards the field,
976 * Conversely, 'rule' does not match 'criteria' and this function returns false
977 * if, for at least one field:
979 * - 'criteria' and 'rule' specify different values for the field, or
981 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
983 * Equivalently, the truth table for whether a field matches is:
988 * r +---------+---------+
989 * i wild | yes | yes |
991 * e +---------+---------+
992 * r exact | no |if values|
994 * a +---------+---------+
996 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
997 * commands and by OpenFlow 1.0 aggregate and flow stats.
999 * Ignores rule->priority. */
1001 cls_rule_is_loose_match(const struct cls_rule *rule,
1002 const struct minimatch *criteria)
1004 return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
1005 && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
1012 rule_matches(const struct cls_rule *rule, const struct cls_rule *target)
1015 || miniflow_equal_in_minimask(&rule->match.flow,
1016 &target->match.flow,
1017 &target->match.mask));
1020 static const struct cls_rule *
1021 search_subtable(const struct cls_subtable *subtable,
1022 struct cls_cursor *cursor)
1025 || !minimask_has_extra(&subtable->mask, &cursor->target->match.mask)) {
1026 const struct cls_rule *rule;
1028 RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
1029 if (rule_matches(rule, cursor->target)) {
1037 /* Initializes 'cursor' for iterating through rules in 'cls', and returns the
1038 * first matching cls_rule via '*pnode', or NULL if there are no matches.
1040 * - If 'target' is null, the cursor will visit every rule in 'cls'.
1042 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1043 * such that cls_rule_is_loose_match(rule, target) returns true.
1045 * Ignores target->priority. */
1046 struct cls_cursor cls_cursor_start(const struct classifier *cls,
1047 const struct cls_rule *target)
1049 struct cls_cursor cursor;
1050 struct cls_subtable *subtable;
1053 cursor.target = target && !cls_rule_is_catchall(target) ? target : NULL;
1056 /* Find first rule. */
1057 PVECTOR_CURSOR_FOR_EACH (subtable, &cursor.subtables,
1058 &cursor.cls->subtables) {
1059 const struct cls_rule *rule = search_subtable(subtable, &cursor);
1062 cursor.subtable = subtable;
1071 static const struct cls_rule *
1072 cls_cursor_next(struct cls_cursor *cursor)
1074 const struct cls_rule *rule;
1075 const struct cls_subtable *subtable;
1077 rule = cursor->rule;
1078 subtable = cursor->subtable;
1079 RCULIST_FOR_EACH_CONTINUE (rule, node, &subtable->rules_list) {
1080 if (rule_matches(rule, cursor->target)) {
1085 PVECTOR_CURSOR_FOR_EACH_CONTINUE (subtable, &cursor->subtables) {
1086 rule = search_subtable(subtable, cursor);
1088 cursor->subtable = subtable;
1096 /* Sets 'cursor->rule' to the next matching cls_rule in 'cursor''s iteration,
1097 * or to null if all matching rules have been visited. */
1099 cls_cursor_advance(struct cls_cursor *cursor)
1101 cursor->rule = cls_cursor_next(cursor);
1104 static struct cls_subtable *
1105 find_subtable(const struct classifier *cls, const struct minimask *mask)
1107 struct cls_subtable *subtable;
1109 CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, minimask_hash(mask, 0),
1110 &cls->subtables_map) {
1111 if (minimask_equal(mask, &subtable->mask)) {
1118 /* The new subtable will be visible to the readers only after this. */
1119 static struct cls_subtable *
1120 insert_subtable(struct classifier *cls, const struct minimask *mask)
1122 uint32_t hash = minimask_hash(mask, 0);
1123 struct cls_subtable *subtable;
1125 struct flow_wildcards old, new;
1127 int count = count_1bits(mask->masks.map);
1129 subtable = xzalloc(sizeof *subtable - sizeof mask->masks.inline_values
1130 + MINIFLOW_VALUES_SIZE(count));
1131 cmap_init(&subtable->rules);
1132 miniflow_clone_inline(CONST_CAST(struct miniflow *, &subtable->mask.masks),
1133 &mask->masks, count);
1135 /* Init indices for segmented lookup, if any. */
1136 flow_wildcards_init_catchall(&new);
1139 for (i = 0; i < cls->n_flow_segments; i++) {
1140 flow_wildcards_fold_minimask_range(&new, mask, prev,
1141 cls->flow_segments[i]);
1142 /* Add an index if it adds mask bits. */
1143 if (!flow_wildcards_equal(&new, &old)) {
1144 cmap_init(&subtable->indices[index]);
1145 *CONST_CAST(uint8_t *, &subtable->index_ofs[index])
1146 = cls->flow_segments[i];
1150 prev = cls->flow_segments[i];
1152 /* Check if the rest of the subtable's mask adds any bits,
1153 * and remove the last index if it doesn't. */
1155 flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U64S);
1156 if (flow_wildcards_equal(&new, &old)) {
1158 *CONST_CAST(uint8_t *, &subtable->index_ofs[index]) = 0;
1159 cmap_destroy(&subtable->indices[index]);
1162 *CONST_CAST(uint8_t *, &subtable->n_indices) = index;
1164 *CONST_CAST(tag_type *, &subtable->tag) =
1165 (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1166 ? tag_create_deterministic(hash)
1169 for (i = 0; i < cls->n_tries; i++) {
1170 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1171 cls->tries[i].field);
1175 ovsrcu_set_hidden(&subtable->ports_trie, NULL);
1176 *CONST_CAST(int *, &subtable->ports_mask_len)
1177 = 32 - ctz32(ntohl(MINIFLOW_GET_BE32(&mask->masks, tp_src)));
1179 /* List of rules. */
1180 rculist_init(&subtable->rules_list);
1182 cmap_insert(&cls->subtables_map, &subtable->cmap_node, hash);
1187 /* RCU readers may still access the subtable before it is actually freed. */
1189 destroy_subtable(struct classifier *cls, struct cls_subtable *subtable)
1193 pvector_remove(&cls->subtables, subtable);
1194 cmap_remove(&cls->subtables_map, &subtable->cmap_node,
1195 minimask_hash(&subtable->mask, 0));
1197 ovs_assert(ovsrcu_get_protected(struct trie_node *, &subtable->ports_trie)
1199 ovs_assert(cmap_is_empty(&subtable->rules));
1200 ovs_assert(rculist_is_empty(&subtable->rules_list));
1202 for (i = 0; i < subtable->n_indices; i++) {
1203 cmap_destroy(&subtable->indices[i]);
1205 cmap_destroy(&subtable->rules);
1206 ovsrcu_postpone(free, subtable);
1214 static unsigned int be_get_bit_at(const ovs_be32 value[], unsigned int ofs);
1216 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1217 * lookup results. */
1219 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1220 const unsigned int field_plen[CLS_MAX_TRIES],
1221 const struct range ofs, const struct flow *flow,
1222 struct flow_wildcards *wc)
1226 /* Check if we could avoid fully unwildcarding the next level of
1227 * fields using the prefix tries. The trie checks are done only as
1228 * needed to avoid folding in additional bits to the wildcards mask. */
1229 for (j = 0; j < n_tries; j++) {
1230 /* Is the trie field relevant for this subtable? */
1231 if (field_plen[j]) {
1232 struct trie_ctx *ctx = &trie_ctx[j];
1233 uint8_t be32ofs = ctx->be32ofs;
1234 uint8_t be64ofs = be32ofs / 2;
1236 /* Is the trie field within the current range of fields? */
1237 if (be64ofs >= ofs.start && be64ofs < ofs.end) {
1238 /* On-demand trie lookup. */
1239 if (!ctx->lookup_done) {
1240 memset(&ctx->match_plens, 0, sizeof ctx->match_plens);
1241 ctx->maskbits = trie_lookup(ctx->trie, flow,
1243 ctx->lookup_done = true;
1245 /* Possible to skip the rest of the subtable if subtable's
1246 * prefix on the field is not included in the lookup result. */
1247 if (!be_get_bit_at(&ctx->match_plens.be32, field_plen[j] - 1)) {
1248 /* We want the trie lookup to never result in unwildcarding
1249 * any bits that would not be unwildcarded otherwise.
1250 * Since the trie is shared by the whole classifier, it is
1251 * possible that the 'maskbits' contain bits that are
1252 * irrelevant for the partition relevant for the current
1253 * packet. Hence the checks below. */
1255 /* Check that the trie result will not unwildcard more bits
1256 * than this subtable would otherwise. */
1257 if (ctx->maskbits <= field_plen[j]) {
1258 /* Unwildcard the bits and skip the rest. */
1259 mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1260 /* Note: Prerequisite already unwildcarded, as the only
1261 * prerequisite of the supported trie lookup fields is
1262 * the ethertype, which is always unwildcarded. */
1265 /* Can skip if the field is already unwildcarded. */
1266 if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1276 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1277 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1278 * value has the correct value in 'target'.
1280 * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
1281 * target, mask) but this is faster because of the invariant that
1282 * flow->map and mask->masks.map are the same, and that this version
1283 * takes the 'wc'. */
1285 miniflow_and_mask_matches_flow(const struct miniflow *flow,
1286 const struct minimask *mask,
1287 const struct flow *target)
1289 const uint64_t *flowp = miniflow_get_values(flow);
1290 const uint64_t *maskp = miniflow_get_values(&mask->masks);
1293 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1294 uint64_t diff = (*flowp++ ^ flow_u64_value(target, idx)) & *maskp++;
1304 static inline const struct cls_match *
1305 find_match(const struct cls_subtable *subtable, const struct flow *flow,
1308 const struct cls_match *rule;
1310 CMAP_FOR_EACH_WITH_HASH (rule, cmap_node, hash, &subtable->rules) {
1311 if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
1320 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1321 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1322 * value has the correct value in 'target'.
1324 * This function is equivalent to miniflow_and_mask_matches_flow() but this
1325 * version fills in the mask bits in 'wc'. */
1327 miniflow_and_mask_matches_flow_wc(const struct miniflow *flow,
1328 const struct minimask *mask,
1329 const struct flow *target,
1330 struct flow_wildcards *wc)
1332 const uint64_t *flowp = miniflow_get_values(flow);
1333 const uint64_t *maskp = miniflow_get_values(&mask->masks);
1336 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1337 uint64_t mask = *maskp++;
1338 uint64_t diff = (*flowp++ ^ flow_u64_value(target, idx)) & mask;
1341 /* Only unwildcard if none of the differing bits is already
1343 if (!(flow_u64_value(&wc->masks, idx) & diff)) {
1344 /* Keep one bit of the difference. The selected bit may be
1345 * different in big-endian v.s. little-endian systems. */
1346 *flow_u64_lvalue(&wc->masks, idx) |= rightmost_1bit(diff);
1350 /* Fill in the bits that were looked at. */
1351 *flow_u64_lvalue(&wc->masks, idx) |= mask;
1357 /* Unwildcard the fields looked up so far, if any. */
1359 fill_range_wc(const struct cls_subtable *subtable, struct flow_wildcards *wc,
1363 flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, to);
1367 static const struct cls_match *
1368 find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
1369 struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1370 struct flow_wildcards *wc)
1372 uint32_t basis = 0, hash;
1373 const struct cls_match *rule = NULL;
1377 if (OVS_UNLIKELY(!wc)) {
1378 return find_match(subtable, flow,
1379 flow_hash_in_minimask(flow, &subtable->mask, 0));
1383 /* Try to finish early by checking fields in segments. */
1384 for (i = 0; i < subtable->n_indices; i++) {
1385 const struct cmap_node *inode;
1387 ofs.end = subtable->index_ofs[i];
1389 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1391 /* 'wc' bits for the trie field set, now unwildcard the preceding
1392 * bits used so far. */
1393 fill_range_wc(subtable, wc, ofs.start);
1396 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1398 inode = cmap_find(&subtable->indices[i], hash);
1400 /* No match, can stop immediately, but must fold in the bits
1401 * used in lookup so far. */
1402 fill_range_wc(subtable, wc, ofs.end);
1406 /* If we have narrowed down to a single rule already, check whether
1407 * that rule matches. Either way, we're done.
1409 * (Rare) hash collisions may cause us to miss the opportunity for this
1411 if (!cmap_node_next(inode)) {
1412 ASSIGN_CONTAINER(rule, inode - i, index_nodes);
1413 if (miniflow_and_mask_matches_flow_wc(&rule->flow, &subtable->mask,
1419 ofs.start = ofs.end;
1421 ofs.end = FLOW_U64S;
1422 /* Trie check for the final range. */
1423 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1424 fill_range_wc(subtable, wc, ofs.start);
1427 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1429 rule = find_match(subtable, flow, hash);
1430 if (!rule && subtable->ports_mask_len) {
1431 /* Ports are always part of the final range, if any.
1432 * No match was found for the ports. Use the ports trie to figure out
1433 * which ports bits to unwildcard. */
1435 ovs_be32 value, plens, mask;
1437 mask = MINIFLOW_GET_BE32(&subtable->mask.masks, tp_src);
1438 value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
1439 mbits = trie_lookup_value(&subtable->ports_trie, &value, &plens, 32);
1441 ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
1442 mask & be32_prefix_mask(mbits);
1444 /* Unwildcard all bits in the mask upto the ports, as they were used
1445 * to determine there is no match. */
1446 fill_range_wc(subtable, wc, TP_PORTS_OFS64);
1450 /* Must unwildcard all the fields, as they were looked at. */
1451 flow_wildcards_fold_minimask(wc, &subtable->mask);
1455 static struct cls_match *
1456 find_equal(const struct cls_subtable *subtable, const struct miniflow *flow,
1459 struct cls_match *head;
1461 CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1462 if (miniflow_equal(&head->flow, flow)) {
1469 /* A longest-prefix match tree. */
1471 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1472 * Prefixes are in the network byte order, and the offset 0 corresponds to
1473 * the most significant bit of the first byte. The offset can be read as
1474 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1476 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1480 pr += ofs / 32; /* Where to start. */
1481 ofs %= 32; /* How many bits to skip at 'pr'. */
1483 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1484 if (plen > 32 - ofs) { /* Need more than we have already? */
1485 prefix |= ntohl(*++pr) >> (32 - ofs);
1487 /* Return with possible unwanted bits at the end. */
1491 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1492 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1493 * corresponds to the most significant bit of the first byte. The offset can
1494 * be read as "how many bits to skip from the start of the prefix starting at
1497 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1502 if (plen > TRIE_PREFIX_BITS) {
1503 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1505 /* Return with unwanted bits cleared. */
1506 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1509 /* Return the number of equal bits in 'n_bits' of 'prefix's MSBs and a 'value'
1510 * starting at "MSB 0"-based offset 'ofs'. */
1512 prefix_equal_bits(uint32_t prefix, unsigned int n_bits, const ovs_be32 value[],
1515 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, n_bits);
1516 /* Set the bit after the relevant bits to limit the result. */
1517 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - n_bits));
1520 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1521 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1523 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1524 unsigned int ofs, unsigned int plen)
1526 return prefix_equal_bits(node->prefix, MIN(node->n_bits, plen - ofs),
1530 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1531 * be greater than 31. */
1533 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1535 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1538 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1539 * be between 0 and 31, inclusive. */
1541 get_bit_at(const uint32_t prefix, unsigned int ofs)
1543 return (prefix >> (31 - ofs)) & 1u;
1546 /* Create new branch. */
1547 static struct trie_node *
1548 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1549 unsigned int n_rules)
1551 struct trie_node *node = xmalloc(sizeof *node);
1553 node->prefix = trie_get_prefix(prefix, ofs, plen);
1555 if (plen <= TRIE_PREFIX_BITS) {
1556 node->n_bits = plen;
1557 ovsrcu_set_hidden(&node->edges[0], NULL);
1558 ovsrcu_set_hidden(&node->edges[1], NULL);
1559 node->n_rules = n_rules;
1560 } else { /* Need intermediate nodes. */
1561 struct trie_node *subnode = trie_branch_create(prefix,
1562 ofs + TRIE_PREFIX_BITS,
1563 plen - TRIE_PREFIX_BITS,
1565 int bit = get_bit_at(subnode->prefix, 0);
1566 node->n_bits = TRIE_PREFIX_BITS;
1567 ovsrcu_set_hidden(&node->edges[bit], subnode);
1568 ovsrcu_set_hidden(&node->edges[!bit], NULL);
1575 trie_node_destroy(const struct trie_node *node)
1577 ovsrcu_postpone(free, CONST_CAST(struct trie_node *, node));
1580 /* Copy a trie node for modification and postpone delete the old one. */
1581 static struct trie_node *
1582 trie_node_rcu_realloc(const struct trie_node *node)
1584 struct trie_node *new_node = xmalloc(sizeof *node);
1587 trie_node_destroy(node);
1593 trie_destroy(rcu_trie_ptr *trie)
1595 struct trie_node *node = ovsrcu_get_protected(struct trie_node *, trie);
1598 ovsrcu_set_hidden(trie, NULL);
1599 trie_destroy(&node->edges[0]);
1600 trie_destroy(&node->edges[1]);
1601 trie_node_destroy(node);
1606 trie_is_leaf(const struct trie_node *trie)
1609 return !ovsrcu_get(struct trie_node *, &trie->edges[0])
1610 && !ovsrcu_get(struct trie_node *, &trie->edges[1]);
1614 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1615 unsigned int n_bits)
1617 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1620 for (i = 0; i < n_bits / 32; i++) {
1621 mask[i] = OVS_BE32_MAX;
1624 mask[i] |= htonl(~0u << (32 - n_bits % 32));
1629 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
1630 unsigned int n_bits)
1632 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1634 ovs_be32 zeroes = 0;
1636 for (i = 0; i < n_bits / 32; i++) {
1640 zeroes |= ~mask[i] & htonl(~0u << (32 - n_bits % 32));
1643 return !zeroes; /* All 'n_bits' bits set. */
1646 static rcu_trie_ptr *
1647 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
1650 return node->edges + be_get_bit_at(value, ofs);
1653 static const struct trie_node *
1654 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
1657 return ovsrcu_get(struct trie_node *,
1658 &node->edges[be_get_bit_at(value, ofs)]);
1661 /* Set the bit at ("MSB 0"-based) offset 'ofs'. 'ofs' can be greater than 31.
1664 be_set_bit_at(ovs_be32 value[], unsigned int ofs)
1666 ((uint8_t *)value)[ofs / 8] |= 1u << (7 - ofs % 8);
1669 /* Returns the number of bits in the prefix mask necessary to determine a
1670 * mismatch, in case there are longer prefixes in the tree below the one that
1672 * '*plens' will have a bit set for each prefix length that may have matching
1673 * rules. The caller is responsible for clearing the '*plens' prior to
1677 trie_lookup_value(const rcu_trie_ptr *trie, const ovs_be32 value[],
1678 ovs_be32 plens[], unsigned int n_bits)
1680 const struct trie_node *prev = NULL;
1681 const struct trie_node *node = ovsrcu_get(struct trie_node *, trie);
1682 unsigned int match_len = 0; /* Number of matching bits. */
1684 for (; node; prev = node, node = trie_next_node(node, value, match_len)) {
1685 unsigned int eqbits;
1686 /* Check if this edge can be followed. */
1687 eqbits = prefix_equal_bits(node->prefix, node->n_bits, value,
1689 match_len += eqbits;
1690 if (eqbits < node->n_bits) { /* Mismatch, nothing more to be found. */
1691 /* Bit at offset 'match_len' differed. */
1692 return match_len + 1; /* Includes the first mismatching bit. */
1694 /* Full match, check if rules exist at this prefix length. */
1695 if (node->n_rules > 0) {
1696 be_set_bit_at(plens, match_len - 1);
1698 if (match_len >= n_bits) {
1699 return n_bits; /* Full prefix. */
1702 /* node == NULL. Full match so far, but we tried to follow an
1703 * non-existing branch. Need to exclude the other branch if it exists
1704 * (it does not if we were called on an empty trie or 'prev' is a leaf
1706 return !prev || trie_is_leaf(prev) ? match_len : match_len + 1;
1710 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
1711 union mf_value *plens)
1713 const struct mf_field *mf = trie->field;
1715 /* Check that current flow matches the prerequisites for the trie
1716 * field. Some match fields are used for multiple purposes, so we
1717 * must check that the trie is relevant for this flow. */
1718 if (mf_are_prereqs_ok(mf, flow)) {
1719 return trie_lookup_value(&trie->root,
1720 &((ovs_be32 *)flow)[mf->flow_be32ofs],
1721 &plens->be32, mf->n_bits);
1723 memset(plens, 0xff, sizeof *plens); /* All prefixes, no skipping. */
1724 return 0; /* Value not used in this case. */
1727 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
1728 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
1729 * 'miniflow_index' is not NULL. */
1731 minimask_get_prefix_len(const struct minimask *minimask,
1732 const struct mf_field *mf)
1734 unsigned int n_bits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
1735 uint8_t be32_ofs = mf->flow_be32ofs;
1736 uint8_t be32_end = be32_ofs + mf->n_bytes / 4;
1738 for (; be32_ofs < be32_end; ++be32_ofs) {
1739 uint32_t mask = ntohl(minimask_get_be32(minimask, be32_ofs));
1741 /* Validate mask, count the mask length. */
1744 return 0; /* No bits allowed after mask ended. */
1747 if (~mask & (~mask + 1)) {
1748 return 0; /* Mask not contiguous. */
1750 mask_tz = ctz32(mask);
1751 n_bits += 32 - mask_tz;
1759 * This is called only when mask prefix is known to be CIDR and non-zero.
1760 * Relies on the fact that the flow and mask have the same map, and since
1761 * the mask is CIDR, the storage for the flow field exists even if it
1762 * happened to be zeros.
1764 static const ovs_be32 *
1765 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
1767 return (OVS_FORCE const ovs_be32 *)
1768 (miniflow_get_values(&match->flow)
1769 + count_1bits(match->flow.map &
1770 ((UINT64_C(1) << mf->flow_be32ofs / 2) - 1)))
1771 + (mf->flow_be32ofs & 1);
1774 /* Insert rule in to the prefix tree.
1775 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1778 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1780 trie_insert_prefix(&trie->root,
1781 minimatch_get_prefix(&rule->match, trie->field), mlen);
1785 trie_insert_prefix(rcu_trie_ptr *edge, const ovs_be32 *prefix, int mlen)
1787 struct trie_node *node;
1790 /* Walk the tree. */
1791 for (; (node = ovsrcu_get_protected(struct trie_node *, edge));
1792 edge = trie_next_edge(node, prefix, ofs)) {
1793 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1795 if (eqbits < node->n_bits) {
1796 /* Mismatch, new node needs to be inserted above. */
1797 int old_branch = get_bit_at(node->prefix, eqbits);
1798 struct trie_node *new_parent;
1800 new_parent = trie_branch_create(prefix, ofs - eqbits, eqbits,
1801 ofs == mlen ? 1 : 0);
1802 /* Copy the node to modify it. */
1803 node = trie_node_rcu_realloc(node);
1804 /* Adjust the new node for its new position in the tree. */
1805 node->prefix <<= eqbits;
1806 node->n_bits -= eqbits;
1807 ovsrcu_set_hidden(&new_parent->edges[old_branch], node);
1809 /* Check if need a new branch for the new rule. */
1811 ovsrcu_set_hidden(&new_parent->edges[!old_branch],
1812 trie_branch_create(prefix, ofs, mlen - ofs,
1815 ovsrcu_set(edge, new_parent); /* Publish changes. */
1818 /* Full match so far. */
1821 /* Full match at the current node, rule needs to be added here. */
1826 /* Must insert a new tree branch for the new rule. */
1827 ovsrcu_set(edge, trie_branch_create(prefix, ofs, mlen - ofs, 1));
1830 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1833 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1835 trie_remove_prefix(&trie->root,
1836 minimatch_get_prefix(&rule->match, trie->field), mlen);
1839 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1842 trie_remove_prefix(rcu_trie_ptr *root, const ovs_be32 *prefix, int mlen)
1844 struct trie_node *node;
1845 rcu_trie_ptr *edges[sizeof(union mf_value) * 8];
1846 int depth = 0, ofs = 0;
1848 /* Walk the tree. */
1849 for (edges[0] = root;
1850 (node = ovsrcu_get_protected(struct trie_node *, edges[depth]));
1851 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
1852 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1854 if (eqbits < node->n_bits) {
1855 /* Mismatch, nothing to be removed. This should never happen, as
1856 * only rules in the classifier are ever removed. */
1857 break; /* Log a warning. */
1859 /* Full match so far. */
1863 /* Full prefix match at the current node, remove rule here. */
1864 if (!node->n_rules) {
1865 break; /* Log a warning. */
1869 /* Check if can prune the tree. */
1870 while (!node->n_rules) {
1871 struct trie_node *next,
1872 *edge0 = ovsrcu_get_protected(struct trie_node *,
1874 *edge1 = ovsrcu_get_protected(struct trie_node *,
1877 if (edge0 && edge1) {
1878 break; /* A branching point, cannot prune. */
1881 /* Else have at most one child node, remove this node. */
1882 next = edge0 ? edge0 : edge1;
1885 if (node->n_bits + next->n_bits > TRIE_PREFIX_BITS) {
1886 break; /* Cannot combine. */
1888 next = trie_node_rcu_realloc(next); /* Modify. */
1890 /* Combine node with next. */
1891 next->prefix = node->prefix | next->prefix >> node->n_bits;
1892 next->n_bits += node->n_bits;
1894 /* Update the parent's edge. */
1895 ovsrcu_set(edges[depth], next); /* Publish changes. */
1896 trie_node_destroy(node);
1898 if (next || !depth) {
1899 /* Branch not pruned or at root, nothing more to do. */
1902 node = ovsrcu_get_protected(struct trie_node *,
1908 /* Cannot go deeper. This should never happen, since only rules
1909 * that actually exist in the classifier are ever removed. */
1910 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");