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()). */
820 const struct cls_rule *
821 classifier_lookup(const struct classifier *cls, const struct flow *flow,
822 struct flow_wildcards *wc)
824 const struct cls_partition *partition;
826 int best_priority = INT_MIN;
827 const struct cls_match *best;
828 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
829 struct cls_subtable *subtable;
831 /* Synchronize for cls->n_tries and subtable->trie_plen. They can change
832 * when table configuration changes, which happens typically only on
834 atomic_thread_fence(memory_order_acquire);
836 /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
837 * then 'flow' cannot possibly match in 'subtable':
839 * - If flow->metadata maps to a given 'partition', then we can use
840 * 'tags' for 'partition->tags'.
842 * - If flow->metadata has no partition, then no rule in 'cls' has an
843 * exact-match for flow->metadata. That means that we don't need to
844 * search any subtable that includes flow->metadata in its mask.
846 * In either case, we always need to search any cls_subtables that do not
847 * include flow->metadata in its mask. One way to do that would be to
848 * check the "cls_subtable"s explicitly for that, but that would require an
849 * extra branch per subtable. Instead, we mark such a cls_subtable's
850 * 'tags' as TAG_ALL and make sure that 'tags' is never empty. This means
851 * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
852 * need a special case.
854 partition = (cmap_is_empty(&cls->partitions)
856 : find_partition(cls, flow->metadata,
857 hash_metadata(flow->metadata)));
858 tags = partition ? partition->tags : TAG_ARBITRARY;
860 /* Initialize trie contexts for find_match_wc(). */
861 for (int i = 0; i < cls->n_tries; i++) {
862 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
866 PVECTOR_FOR_EACH_PRIORITY(subtable, best_priority, 2,
867 sizeof(struct cls_subtable), &cls->subtables) {
868 const struct cls_match *rule;
870 if (!tag_intersects(tags, subtable->tag)) {
874 rule = find_match_wc(subtable, flow, trie_ctx, cls->n_tries, wc);
875 if (rule && rule->priority > best_priority) {
876 best_priority = rule->priority;
881 return best ? best->cls_rule : NULL;
884 /* Finds and returns a rule in 'cls' with exactly the same priority and
885 * matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
886 * contain an exact match. */
887 const struct cls_rule *
888 classifier_find_rule_exactly(const struct classifier *cls,
889 const struct cls_rule *target)
891 const struct cls_match *head, *rule;
892 const struct cls_subtable *subtable;
894 subtable = find_subtable(cls, &target->match.mask);
899 head = find_equal(subtable, &target->match.flow,
900 miniflow_hash_in_minimask(&target->match.flow,
901 &target->match.mask, 0));
905 FOR_EACH_RULE_IN_LIST (rule, head) {
906 if (target->priority >= rule->priority) {
907 return target->priority == rule->priority ? rule->cls_rule : NULL;
913 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
914 * same matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
915 * contain an exact match. */
916 const struct cls_rule *
917 classifier_find_match_exactly(const struct classifier *cls,
918 const struct match *target, int priority)
920 const struct cls_rule *retval;
923 cls_rule_init(&cr, target, priority);
924 retval = classifier_find_rule_exactly(cls, &cr);
925 cls_rule_destroy(&cr);
930 /* Checks if 'target' would overlap any other rule in 'cls'. Two rules are
931 * considered to overlap if both rules have the same priority and a packet
934 * A trivial example of overlapping rules is two rules matching disjoint sets
935 * of fields. E.g., if one rule matches only on port number, while another only
936 * on dl_type, any packet from that specific port and with that specific
937 * dl_type could match both, if the rules also have the same priority. */
939 classifier_rule_overlaps(const struct classifier *cls,
940 const struct cls_rule *target)
942 struct cls_subtable *subtable;
944 /* Iterate subtables in the descending max priority order. */
945 PVECTOR_FOR_EACH_PRIORITY (subtable, target->priority - 1, 2,
946 sizeof(struct cls_subtable), &cls->subtables) {
947 uint64_t storage[FLOW_U64S];
948 struct minimask mask;
949 const struct cls_rule *rule;
951 minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
953 RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
954 if (rule->priority == target->priority
955 && miniflow_equal_in_minimask(&target->match.flow,
956 &rule->match.flow, &mask)) {
964 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
965 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
966 * function returns true if, for every field:
968 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
971 * - 'criteria' wildcards the field,
973 * Conversely, 'rule' does not match 'criteria' and this function returns false
974 * if, for at least one field:
976 * - 'criteria' and 'rule' specify different values for the field, or
978 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
980 * Equivalently, the truth table for whether a field matches is:
985 * r +---------+---------+
986 * i wild | yes | yes |
988 * e +---------+---------+
989 * r exact | no |if values|
991 * a +---------+---------+
993 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
994 * commands and by OpenFlow 1.0 aggregate and flow stats.
996 * Ignores rule->priority. */
998 cls_rule_is_loose_match(const struct cls_rule *rule,
999 const struct minimatch *criteria)
1001 return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
1002 && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
1009 rule_matches(const struct cls_rule *rule, const struct cls_rule *target)
1012 || miniflow_equal_in_minimask(&rule->match.flow,
1013 &target->match.flow,
1014 &target->match.mask));
1017 static const struct cls_rule *
1018 search_subtable(const struct cls_subtable *subtable,
1019 struct cls_cursor *cursor)
1022 || !minimask_has_extra(&subtable->mask, &cursor->target->match.mask)) {
1023 const struct cls_rule *rule;
1025 RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
1026 if (rule_matches(rule, cursor->target)) {
1034 /* Initializes 'cursor' for iterating through rules in 'cls', and returns the
1035 * first matching cls_rule via '*pnode', or NULL if there are no matches.
1037 * - If 'target' is null, the cursor will visit every rule in 'cls'.
1039 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1040 * such that cls_rule_is_loose_match(rule, target) returns true.
1042 * Ignores target->priority. */
1043 struct cls_cursor cls_cursor_start(const struct classifier *cls,
1044 const struct cls_rule *target)
1046 struct cls_cursor cursor;
1047 struct cls_subtable *subtable;
1050 cursor.target = target && !cls_rule_is_catchall(target) ? target : NULL;
1053 /* Find first rule. */
1054 PVECTOR_CURSOR_FOR_EACH (subtable, &cursor.subtables,
1055 &cursor.cls->subtables) {
1056 const struct cls_rule *rule = search_subtable(subtable, &cursor);
1059 cursor.subtable = subtable;
1068 static const struct cls_rule *
1069 cls_cursor_next(struct cls_cursor *cursor)
1071 const struct cls_rule *rule;
1072 const struct cls_subtable *subtable;
1074 rule = cursor->rule;
1075 subtable = cursor->subtable;
1076 RCULIST_FOR_EACH_CONTINUE (rule, node, &subtable->rules_list) {
1077 if (rule_matches(rule, cursor->target)) {
1082 PVECTOR_CURSOR_FOR_EACH_CONTINUE (subtable, &cursor->subtables) {
1083 rule = search_subtable(subtable, cursor);
1085 cursor->subtable = subtable;
1093 /* Sets 'cursor->rule' to the next matching cls_rule in 'cursor''s iteration,
1094 * or to null if all matching rules have been visited. */
1096 cls_cursor_advance(struct cls_cursor *cursor)
1098 cursor->rule = cls_cursor_next(cursor);
1101 static struct cls_subtable *
1102 find_subtable(const struct classifier *cls, const struct minimask *mask)
1104 struct cls_subtable *subtable;
1106 CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, minimask_hash(mask, 0),
1107 &cls->subtables_map) {
1108 if (minimask_equal(mask, &subtable->mask)) {
1115 /* The new subtable will be visible to the readers only after this. */
1116 static struct cls_subtable *
1117 insert_subtable(struct classifier *cls, const struct minimask *mask)
1119 uint32_t hash = minimask_hash(mask, 0);
1120 struct cls_subtable *subtable;
1122 struct flow_wildcards old, new;
1124 int count = count_1bits(mask->masks.map);
1126 subtable = xzalloc(sizeof *subtable - sizeof mask->masks.inline_values
1127 + MINIFLOW_VALUES_SIZE(count));
1128 cmap_init(&subtable->rules);
1129 miniflow_clone_inline(CONST_CAST(struct miniflow *, &subtable->mask.masks),
1130 &mask->masks, count);
1132 /* Init indices for segmented lookup, if any. */
1133 flow_wildcards_init_catchall(&new);
1136 for (i = 0; i < cls->n_flow_segments; i++) {
1137 flow_wildcards_fold_minimask_range(&new, mask, prev,
1138 cls->flow_segments[i]);
1139 /* Add an index if it adds mask bits. */
1140 if (!flow_wildcards_equal(&new, &old)) {
1141 cmap_init(&subtable->indices[index]);
1142 *CONST_CAST(uint8_t *, &subtable->index_ofs[index])
1143 = cls->flow_segments[i];
1147 prev = cls->flow_segments[i];
1149 /* Check if the rest of the subtable's mask adds any bits,
1150 * and remove the last index if it doesn't. */
1152 flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U64S);
1153 if (flow_wildcards_equal(&new, &old)) {
1155 *CONST_CAST(uint8_t *, &subtable->index_ofs[index]) = 0;
1156 cmap_destroy(&subtable->indices[index]);
1159 *CONST_CAST(uint8_t *, &subtable->n_indices) = index;
1161 *CONST_CAST(tag_type *, &subtable->tag) =
1162 (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1163 ? tag_create_deterministic(hash)
1166 for (i = 0; i < cls->n_tries; i++) {
1167 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1168 cls->tries[i].field);
1172 ovsrcu_set_hidden(&subtable->ports_trie, NULL);
1173 *CONST_CAST(int *, &subtable->ports_mask_len)
1174 = 32 - ctz32(ntohl(MINIFLOW_GET_BE32(&mask->masks, tp_src)));
1176 /* List of rules. */
1177 rculist_init(&subtable->rules_list);
1179 cmap_insert(&cls->subtables_map, &subtable->cmap_node, hash);
1184 /* RCU readers may still access the subtable before it is actually freed. */
1186 destroy_subtable(struct classifier *cls, struct cls_subtable *subtable)
1190 pvector_remove(&cls->subtables, subtable);
1191 cmap_remove(&cls->subtables_map, &subtable->cmap_node,
1192 minimask_hash(&subtable->mask, 0));
1194 ovs_assert(ovsrcu_get_protected(struct trie_node *, &subtable->ports_trie)
1196 ovs_assert(cmap_is_empty(&subtable->rules));
1197 ovs_assert(rculist_is_empty(&subtable->rules_list));
1199 for (i = 0; i < subtable->n_indices; i++) {
1200 cmap_destroy(&subtable->indices[i]);
1202 cmap_destroy(&subtable->rules);
1203 ovsrcu_postpone(free, subtable);
1211 static unsigned int be_get_bit_at(const ovs_be32 value[], unsigned int ofs);
1213 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1214 * lookup results. */
1216 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1217 const unsigned int field_plen[CLS_MAX_TRIES],
1218 const struct range ofs, const struct flow *flow,
1219 struct flow_wildcards *wc)
1223 /* Check if we could avoid fully unwildcarding the next level of
1224 * fields using the prefix tries. The trie checks are done only as
1225 * needed to avoid folding in additional bits to the wildcards mask. */
1226 for (j = 0; j < n_tries; j++) {
1227 /* Is the trie field relevant for this subtable? */
1228 if (field_plen[j]) {
1229 struct trie_ctx *ctx = &trie_ctx[j];
1230 uint8_t be32ofs = ctx->be32ofs;
1231 uint8_t be64ofs = be32ofs / 2;
1233 /* Is the trie field within the current range of fields? */
1234 if (be64ofs >= ofs.start && be64ofs < ofs.end) {
1235 /* On-demand trie lookup. */
1236 if (!ctx->lookup_done) {
1237 memset(&ctx->match_plens, 0, sizeof ctx->match_plens);
1238 ctx->maskbits = trie_lookup(ctx->trie, flow,
1240 ctx->lookup_done = true;
1242 /* Possible to skip the rest of the subtable if subtable's
1243 * prefix on the field is not included in the lookup result. */
1244 if (!be_get_bit_at(&ctx->match_plens.be32, field_plen[j] - 1)) {
1245 /* We want the trie lookup to never result in unwildcarding
1246 * any bits that would not be unwildcarded otherwise.
1247 * Since the trie is shared by the whole classifier, it is
1248 * possible that the 'maskbits' contain bits that are
1249 * irrelevant for the partition relevant for the current
1250 * packet. Hence the checks below. */
1252 /* Check that the trie result will not unwildcard more bits
1253 * than this subtable would otherwise. */
1254 if (ctx->maskbits <= field_plen[j]) {
1255 /* Unwildcard the bits and skip the rest. */
1256 mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1257 /* Note: Prerequisite already unwildcarded, as the only
1258 * prerequisite of the supported trie lookup fields is
1259 * the ethertype, which is always unwildcarded. */
1262 /* Can skip if the field is already unwildcarded. */
1263 if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1273 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1274 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1275 * value has the correct value in 'target'.
1277 * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
1278 * target, mask) but this is faster because of the invariant that
1279 * flow->map and mask->masks.map are the same, and that this version
1280 * takes the 'wc'. */
1282 miniflow_and_mask_matches_flow(const struct miniflow *flow,
1283 const struct minimask *mask,
1284 const struct flow *target)
1286 const uint64_t *flowp = miniflow_get_values(flow);
1287 const uint64_t *maskp = miniflow_get_values(&mask->masks);
1290 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1291 uint64_t diff = (*flowp++ ^ flow_u64_value(target, idx)) & *maskp++;
1301 static inline const struct cls_match *
1302 find_match(const struct cls_subtable *subtable, const struct flow *flow,
1305 const struct cls_match *rule;
1307 CMAP_FOR_EACH_WITH_HASH (rule, cmap_node, hash, &subtable->rules) {
1308 if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
1317 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1318 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1319 * value has the correct value in 'target'.
1321 * This function is equivalent to miniflow_and_mask_matches_flow() but this
1322 * version fills in the mask bits in 'wc'. */
1324 miniflow_and_mask_matches_flow_wc(const struct miniflow *flow,
1325 const struct minimask *mask,
1326 const struct flow *target,
1327 struct flow_wildcards *wc)
1329 const uint64_t *flowp = miniflow_get_values(flow);
1330 const uint64_t *maskp = miniflow_get_values(&mask->masks);
1333 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1334 uint64_t mask = *maskp++;
1335 uint64_t diff = (*flowp++ ^ flow_u64_value(target, idx)) & mask;
1338 /* Only unwildcard if none of the differing bits is already
1340 if (!(flow_u64_value(&wc->masks, idx) & diff)) {
1341 /* Keep one bit of the difference. The selected bit may be
1342 * different in big-endian v.s. little-endian systems. */
1343 *flow_u64_lvalue(&wc->masks, idx) |= rightmost_1bit(diff);
1347 /* Fill in the bits that were looked at. */
1348 *flow_u64_lvalue(&wc->masks, idx) |= mask;
1354 /* Unwildcard the fields looked up so far, if any. */
1356 fill_range_wc(const struct cls_subtable *subtable, struct flow_wildcards *wc,
1360 flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, to);
1364 static const struct cls_match *
1365 find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
1366 struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1367 struct flow_wildcards *wc)
1369 uint32_t basis = 0, hash;
1370 const struct cls_match *rule = NULL;
1374 if (OVS_UNLIKELY(!wc)) {
1375 return find_match(subtable, flow,
1376 flow_hash_in_minimask(flow, &subtable->mask, 0));
1380 /* Try to finish early by checking fields in segments. */
1381 for (i = 0; i < subtable->n_indices; i++) {
1382 const struct cmap_node *inode;
1384 ofs.end = subtable->index_ofs[i];
1386 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1388 /* 'wc' bits for the trie field set, now unwildcard the preceding
1389 * bits used so far. */
1390 fill_range_wc(subtable, wc, ofs.start);
1393 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1395 inode = cmap_find(&subtable->indices[i], hash);
1397 /* No match, can stop immediately, but must fold in the bits
1398 * used in lookup so far. */
1399 fill_range_wc(subtable, wc, ofs.end);
1403 /* If we have narrowed down to a single rule already, check whether
1404 * that rule matches. Either way, we're done.
1406 * (Rare) hash collisions may cause us to miss the opportunity for this
1408 if (!cmap_node_next(inode)) {
1409 ASSIGN_CONTAINER(rule, inode - i, index_nodes);
1410 if (miniflow_and_mask_matches_flow_wc(&rule->flow, &subtable->mask,
1416 ofs.start = ofs.end;
1418 ofs.end = FLOW_U64S;
1419 /* Trie check for the final range. */
1420 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1421 fill_range_wc(subtable, wc, ofs.start);
1424 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1426 rule = find_match(subtable, flow, hash);
1427 if (!rule && subtable->ports_mask_len) {
1428 /* Ports are always part of the final range, if any.
1429 * No match was found for the ports. Use the ports trie to figure out
1430 * which ports bits to unwildcard. */
1432 ovs_be32 value, plens, mask;
1434 mask = MINIFLOW_GET_BE32(&subtable->mask.masks, tp_src);
1435 value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
1436 mbits = trie_lookup_value(&subtable->ports_trie, &value, &plens, 32);
1438 ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
1439 mask & be32_prefix_mask(mbits);
1441 /* Unwildcard all bits in the mask upto the ports, as they were used
1442 * to determine there is no match. */
1443 fill_range_wc(subtable, wc, TP_PORTS_OFS64);
1447 /* Must unwildcard all the fields, as they were looked at. */
1448 flow_wildcards_fold_minimask(wc, &subtable->mask);
1452 static struct cls_match *
1453 find_equal(const struct cls_subtable *subtable, const struct miniflow *flow,
1456 struct cls_match *head;
1458 CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1459 if (miniflow_equal(&head->flow, flow)) {
1466 /* A longest-prefix match tree. */
1468 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1469 * Prefixes are in the network byte order, and the offset 0 corresponds to
1470 * the most significant bit of the first byte. The offset can be read as
1471 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1473 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1477 pr += ofs / 32; /* Where to start. */
1478 ofs %= 32; /* How many bits to skip at 'pr'. */
1480 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1481 if (plen > 32 - ofs) { /* Need more than we have already? */
1482 prefix |= ntohl(*++pr) >> (32 - ofs);
1484 /* Return with possible unwanted bits at the end. */
1488 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1489 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1490 * corresponds to the most significant bit of the first byte. The offset can
1491 * be read as "how many bits to skip from the start of the prefix starting at
1494 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1499 if (plen > TRIE_PREFIX_BITS) {
1500 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1502 /* Return with unwanted bits cleared. */
1503 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1506 /* Return the number of equal bits in 'n_bits' of 'prefix's MSBs and a 'value'
1507 * starting at "MSB 0"-based offset 'ofs'. */
1509 prefix_equal_bits(uint32_t prefix, unsigned int n_bits, const ovs_be32 value[],
1512 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, n_bits);
1513 /* Set the bit after the relevant bits to limit the result. */
1514 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - n_bits));
1517 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1518 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1520 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1521 unsigned int ofs, unsigned int plen)
1523 return prefix_equal_bits(node->prefix, MIN(node->n_bits, plen - ofs),
1527 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1528 * be greater than 31. */
1530 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1532 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1535 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1536 * be between 0 and 31, inclusive. */
1538 get_bit_at(const uint32_t prefix, unsigned int ofs)
1540 return (prefix >> (31 - ofs)) & 1u;
1543 /* Create new branch. */
1544 static struct trie_node *
1545 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1546 unsigned int n_rules)
1548 struct trie_node *node = xmalloc(sizeof *node);
1550 node->prefix = trie_get_prefix(prefix, ofs, plen);
1552 if (plen <= TRIE_PREFIX_BITS) {
1553 node->n_bits = plen;
1554 ovsrcu_set_hidden(&node->edges[0], NULL);
1555 ovsrcu_set_hidden(&node->edges[1], NULL);
1556 node->n_rules = n_rules;
1557 } else { /* Need intermediate nodes. */
1558 struct trie_node *subnode = trie_branch_create(prefix,
1559 ofs + TRIE_PREFIX_BITS,
1560 plen - TRIE_PREFIX_BITS,
1562 int bit = get_bit_at(subnode->prefix, 0);
1563 node->n_bits = TRIE_PREFIX_BITS;
1564 ovsrcu_set_hidden(&node->edges[bit], subnode);
1565 ovsrcu_set_hidden(&node->edges[!bit], NULL);
1572 trie_node_destroy(const struct trie_node *node)
1574 ovsrcu_postpone(free, CONST_CAST(struct trie_node *, node));
1577 /* Copy a trie node for modification and postpone delete the old one. */
1578 static struct trie_node *
1579 trie_node_rcu_realloc(const struct trie_node *node)
1581 struct trie_node *new_node = xmalloc(sizeof *node);
1584 trie_node_destroy(node);
1590 trie_destroy(rcu_trie_ptr *trie)
1592 struct trie_node *node = ovsrcu_get_protected(struct trie_node *, trie);
1595 ovsrcu_set_hidden(trie, NULL);
1596 trie_destroy(&node->edges[0]);
1597 trie_destroy(&node->edges[1]);
1598 trie_node_destroy(node);
1603 trie_is_leaf(const struct trie_node *trie)
1606 return !ovsrcu_get(struct trie_node *, &trie->edges[0])
1607 && !ovsrcu_get(struct trie_node *, &trie->edges[1]);
1611 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1612 unsigned int n_bits)
1614 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1617 for (i = 0; i < n_bits / 32; i++) {
1618 mask[i] = OVS_BE32_MAX;
1621 mask[i] |= htonl(~0u << (32 - n_bits % 32));
1626 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
1627 unsigned int n_bits)
1629 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1631 ovs_be32 zeroes = 0;
1633 for (i = 0; i < n_bits / 32; i++) {
1637 zeroes |= ~mask[i] & htonl(~0u << (32 - n_bits % 32));
1640 return !zeroes; /* All 'n_bits' bits set. */
1643 static rcu_trie_ptr *
1644 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
1647 return node->edges + be_get_bit_at(value, ofs);
1650 static const struct trie_node *
1651 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
1654 return ovsrcu_get(struct trie_node *,
1655 &node->edges[be_get_bit_at(value, ofs)]);
1658 /* Set the bit at ("MSB 0"-based) offset 'ofs'. 'ofs' can be greater than 31.
1661 be_set_bit_at(ovs_be32 value[], unsigned int ofs)
1663 ((uint8_t *)value)[ofs / 8] |= 1u << (7 - ofs % 8);
1666 /* Returns the number of bits in the prefix mask necessary to determine a
1667 * mismatch, in case there are longer prefixes in the tree below the one that
1669 * '*plens' will have a bit set for each prefix length that may have matching
1670 * rules. The caller is responsible for clearing the '*plens' prior to
1674 trie_lookup_value(const rcu_trie_ptr *trie, const ovs_be32 value[],
1675 ovs_be32 plens[], unsigned int n_bits)
1677 const struct trie_node *prev = NULL;
1678 const struct trie_node *node = ovsrcu_get(struct trie_node *, trie);
1679 unsigned int match_len = 0; /* Number of matching bits. */
1681 for (; node; prev = node, node = trie_next_node(node, value, match_len)) {
1682 unsigned int eqbits;
1683 /* Check if this edge can be followed. */
1684 eqbits = prefix_equal_bits(node->prefix, node->n_bits, value,
1686 match_len += eqbits;
1687 if (eqbits < node->n_bits) { /* Mismatch, nothing more to be found. */
1688 /* Bit at offset 'match_len' differed. */
1689 return match_len + 1; /* Includes the first mismatching bit. */
1691 /* Full match, check if rules exist at this prefix length. */
1692 if (node->n_rules > 0) {
1693 be_set_bit_at(plens, match_len - 1);
1695 if (match_len >= n_bits) {
1696 return n_bits; /* Full prefix. */
1699 /* node == NULL. Full match so far, but we tried to follow an
1700 * non-existing branch. Need to exclude the other branch if it exists
1701 * (it does not if we were called on an empty trie or 'prev' is a leaf
1703 return !prev || trie_is_leaf(prev) ? match_len : match_len + 1;
1707 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
1708 union mf_value *plens)
1710 const struct mf_field *mf = trie->field;
1712 /* Check that current flow matches the prerequisites for the trie
1713 * field. Some match fields are used for multiple purposes, so we
1714 * must check that the trie is relevant for this flow. */
1715 if (mf_are_prereqs_ok(mf, flow)) {
1716 return trie_lookup_value(&trie->root,
1717 &((ovs_be32 *)flow)[mf->flow_be32ofs],
1718 &plens->be32, mf->n_bits);
1720 memset(plens, 0xff, sizeof *plens); /* All prefixes, no skipping. */
1721 return 0; /* Value not used in this case. */
1724 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
1725 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
1726 * 'miniflow_index' is not NULL. */
1728 minimask_get_prefix_len(const struct minimask *minimask,
1729 const struct mf_field *mf)
1731 unsigned int n_bits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
1732 uint8_t be32_ofs = mf->flow_be32ofs;
1733 uint8_t be32_end = be32_ofs + mf->n_bytes / 4;
1735 for (; be32_ofs < be32_end; ++be32_ofs) {
1736 uint32_t mask = ntohl(minimask_get_be32(minimask, be32_ofs));
1738 /* Validate mask, count the mask length. */
1741 return 0; /* No bits allowed after mask ended. */
1744 if (~mask & (~mask + 1)) {
1745 return 0; /* Mask not contiguous. */
1747 mask_tz = ctz32(mask);
1748 n_bits += 32 - mask_tz;
1756 * This is called only when mask prefix is known to be CIDR and non-zero.
1757 * Relies on the fact that the flow and mask have the same map, and since
1758 * the mask is CIDR, the storage for the flow field exists even if it
1759 * happened to be zeros.
1761 static const ovs_be32 *
1762 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
1764 return (OVS_FORCE const ovs_be32 *)
1765 (miniflow_get_values(&match->flow)
1766 + count_1bits(match->flow.map &
1767 ((UINT64_C(1) << mf->flow_be32ofs / 2) - 1)))
1768 + (mf->flow_be32ofs & 1);
1771 /* Insert rule in to the prefix tree.
1772 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1775 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1777 trie_insert_prefix(&trie->root,
1778 minimatch_get_prefix(&rule->match, trie->field), mlen);
1782 trie_insert_prefix(rcu_trie_ptr *edge, const ovs_be32 *prefix, int mlen)
1784 struct trie_node *node;
1787 /* Walk the tree. */
1788 for (; (node = ovsrcu_get_protected(struct trie_node *, edge));
1789 edge = trie_next_edge(node, prefix, ofs)) {
1790 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1792 if (eqbits < node->n_bits) {
1793 /* Mismatch, new node needs to be inserted above. */
1794 int old_branch = get_bit_at(node->prefix, eqbits);
1795 struct trie_node *new_parent;
1797 new_parent = trie_branch_create(prefix, ofs - eqbits, eqbits,
1798 ofs == mlen ? 1 : 0);
1799 /* Copy the node to modify it. */
1800 node = trie_node_rcu_realloc(node);
1801 /* Adjust the new node for its new position in the tree. */
1802 node->prefix <<= eqbits;
1803 node->n_bits -= eqbits;
1804 ovsrcu_set_hidden(&new_parent->edges[old_branch], node);
1806 /* Check if need a new branch for the new rule. */
1808 ovsrcu_set_hidden(&new_parent->edges[!old_branch],
1809 trie_branch_create(prefix, ofs, mlen - ofs,
1812 ovsrcu_set(edge, new_parent); /* Publish changes. */
1815 /* Full match so far. */
1818 /* Full match at the current node, rule needs to be added here. */
1823 /* Must insert a new tree branch for the new rule. */
1824 ovsrcu_set(edge, trie_branch_create(prefix, ofs, mlen - ofs, 1));
1827 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1830 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1832 trie_remove_prefix(&trie->root,
1833 minimatch_get_prefix(&rule->match, trie->field), mlen);
1836 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1839 trie_remove_prefix(rcu_trie_ptr *root, const ovs_be32 *prefix, int mlen)
1841 struct trie_node *node;
1842 rcu_trie_ptr *edges[sizeof(union mf_value) * 8];
1843 int depth = 0, ofs = 0;
1845 /* Walk the tree. */
1846 for (edges[0] = root;
1847 (node = ovsrcu_get_protected(struct trie_node *, edges[depth]));
1848 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
1849 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1851 if (eqbits < node->n_bits) {
1852 /* Mismatch, nothing to be removed. This should never happen, as
1853 * only rules in the classifier are ever removed. */
1854 break; /* Log a warning. */
1856 /* Full match so far. */
1860 /* Full prefix match at the current node, remove rule here. */
1861 if (!node->n_rules) {
1862 break; /* Log a warning. */
1866 /* Check if can prune the tree. */
1867 while (!node->n_rules) {
1868 struct trie_node *next,
1869 *edge0 = ovsrcu_get_protected(struct trie_node *,
1871 *edge1 = ovsrcu_get_protected(struct trie_node *,
1874 if (edge0 && edge1) {
1875 break; /* A branching point, cannot prune. */
1878 /* Else have at most one child node, remove this node. */
1879 next = edge0 ? edge0 : edge1;
1882 if (node->n_bits + next->n_bits > TRIE_PREFIX_BITS) {
1883 break; /* Cannot combine. */
1885 next = trie_node_rcu_realloc(next); /* Modify. */
1887 /* Combine node with next. */
1888 next->prefix = node->prefix | next->prefix >> node->n_bits;
1889 next->n_bits += node->n_bits;
1891 /* Update the parent's edge. */
1892 ovsrcu_set(edges[depth], next); /* Publish changes. */
1893 trie_node_destroy(node);
1895 if (next || !depth) {
1896 /* Branch not pruned or at root, nothing more to do. */
1899 node = ovsrcu_get_protected(struct trie_node *,
1905 /* Cannot go deeper. This should never happen, since only rules
1906 * that actually exist in the classifier are ever removed. */
1907 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");