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);
38 static struct cls_match *
39 cls_match_alloc(const struct cls_rule *rule)
41 int count = count_1bits(rule->match.flow.map);
43 struct cls_match *cls_match
44 = xmalloc(sizeof *cls_match - sizeof cls_match->flow.inline_values
45 + MINIFLOW_VALUES_SIZE(count));
47 rculist_init(&cls_match->list);
48 *CONST_CAST(const struct cls_rule **, &cls_match->cls_rule) = rule;
49 *CONST_CAST(int *, &cls_match->priority) = rule->priority;
50 miniflow_clone_inline(CONST_CAST(struct miniflow *, &cls_match->flow),
51 &rule->match.flow, count);
56 static struct cls_subtable *find_subtable(const struct classifier *cls,
57 const struct minimask *);
58 static struct cls_subtable *insert_subtable(struct classifier *cls,
59 const struct minimask *);
60 static void destroy_subtable(struct classifier *cls, struct cls_subtable *);
62 static const struct cls_match *find_match_wc(const struct cls_subtable *,
66 struct flow_wildcards *);
67 static struct cls_match *find_equal(const struct cls_subtable *,
68 const struct miniflow *, uint32_t hash);
70 static inline const struct cls_match *
71 next_rule_in_list__(const struct cls_match *rule)
73 const struct cls_match *next = NULL;
74 next = OBJECT_CONTAINING(rculist_next(&rule->list), next, list);
78 static inline const struct cls_match *
79 next_rule_in_list(const struct cls_match *rule)
81 const struct cls_match *next = next_rule_in_list__(rule);
82 return next->priority < rule->priority ? next : NULL;
85 static inline struct cls_match *
86 next_rule_in_list_protected__(struct cls_match *rule)
88 struct cls_match *next = NULL;
89 next = OBJECT_CONTAINING(rculist_next_protected(&rule->list), next, list);
93 static inline struct cls_match *
94 next_rule_in_list_protected(struct cls_match *rule)
96 struct cls_match *next = next_rule_in_list_protected__(rule);
97 return next->priority < rule->priority ? next : NULL;
100 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list. */
101 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD) \
102 for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
103 #define FOR_EACH_RULE_IN_LIST_PROTECTED(RULE, HEAD) \
104 for ((RULE) = (HEAD); (RULE) != NULL; \
105 (RULE) = next_rule_in_list_protected(RULE))
107 static unsigned int minimask_get_prefix_len(const struct minimask *,
108 const struct mf_field *);
109 static void trie_init(struct classifier *cls, int trie_idx,
110 const struct mf_field *);
111 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
112 union mf_value *plens);
113 static unsigned int trie_lookup_value(const rcu_trie_ptr *,
114 const ovs_be32 value[], ovs_be32 plens[],
115 unsigned int value_bits);
116 static void trie_destroy(rcu_trie_ptr *);
117 static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
118 static void trie_insert_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
120 static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
121 static void trie_remove_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
123 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
124 unsigned int n_bits);
125 static bool mask_prefix_bits_set(const struct flow_wildcards *,
126 uint8_t be32ofs, unsigned int n_bits);
131 cls_rule_init__(struct cls_rule *rule, unsigned int priority)
133 rculist_init(&rule->node);
134 rule->priority = priority;
135 rule->cls_match = NULL;
138 /* Initializes 'rule' to match packets specified by 'match' at the given
139 * 'priority'. 'match' must satisfy the invariant described in the comment at
140 * the definition of struct match.
142 * The caller must eventually destroy 'rule' with cls_rule_destroy().
144 * Clients should not use priority INT_MIN. (OpenFlow uses priorities between
145 * 0 and UINT16_MAX, inclusive.) */
147 cls_rule_init(struct cls_rule *rule, const struct match *match, int priority)
149 cls_rule_init__(rule, priority);
150 minimatch_init(&rule->match, match);
153 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
155 cls_rule_init_from_minimatch(struct cls_rule *rule,
156 const struct minimatch *match, int priority)
158 cls_rule_init__(rule, priority);
159 minimatch_clone(&rule->match, match);
162 /* Initializes 'dst' as a copy of 'src'.
164 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
166 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
168 cls_rule_init__(dst, src->priority);
169 minimatch_clone(&dst->match, &src->match);
172 /* Initializes 'dst' with the data in 'src', destroying 'src'.
173 * 'src' must be a cls_rule NOT in a classifier.
175 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
177 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
179 ovs_assert(!src->cls_match); /* Must not be in a classifier. */
180 cls_rule_init__(dst, src->priority);
181 minimatch_move(&dst->match, &src->match);
184 /* Frees memory referenced by 'rule'. Doesn't free 'rule' itself (it's
185 * normally embedded into a larger structure).
187 * ('rule' must not currently be in a classifier.) */
189 cls_rule_destroy(struct cls_rule *rule)
191 ovs_assert(!rule->cls_match); /* Must not be in a classifier. */
193 /* Check that the rule has been properly removed from the classifier and
194 * that the destruction only happens after the RCU grace period, or that
195 * the rule was never inserted to the classifier in the first place. */
196 ovs_assert(rculist_next_protected(&rule->node) == RCULIST_POISON
197 || rculist_is_empty(&rule->node));
199 minimatch_destroy(&rule->match);
202 /* Returns true if 'a' and 'b' match the same packets at the same priority,
203 * false if they differ in some way. */
205 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
207 return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
210 /* Returns a hash value for 'rule', folding in 'basis'. */
212 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
214 return minimatch_hash(&rule->match, hash_int(rule->priority, basis));
217 /* Appends a string describing 'rule' to 's'. */
219 cls_rule_format(const struct cls_rule *rule, struct ds *s)
221 minimatch_format(&rule->match, s, rule->priority);
224 /* Returns true if 'rule' matches every packet, false otherwise. */
226 cls_rule_is_catchall(const struct cls_rule *rule)
228 return minimask_is_catchall(&rule->match.mask);
231 /* Initializes 'cls' as a classifier that initially contains no classification
234 classifier_init(struct classifier *cls, const uint8_t *flow_segments)
237 cmap_init(&cls->subtables_map);
238 pvector_init(&cls->subtables);
239 cmap_init(&cls->partitions);
240 cls->n_flow_segments = 0;
242 while (cls->n_flow_segments < CLS_MAX_INDICES
243 && *flow_segments < FLOW_U32S) {
244 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
248 for (int i = 0; i < CLS_MAX_TRIES; i++) {
249 trie_init(cls, i, NULL);
254 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
255 * caller's responsibility.
256 * May only be called after all the readers have been terminated. */
258 classifier_destroy(struct classifier *cls)
261 struct cls_partition *partition;
262 struct cls_subtable *subtable;
265 for (i = 0; i < cls->n_tries; i++) {
266 trie_destroy(&cls->tries[i].root);
269 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
270 destroy_subtable(cls, subtable);
272 cmap_destroy(&cls->subtables_map);
274 CMAP_FOR_EACH (partition, cmap_node, &cls->partitions) {
275 ovsrcu_postpone(free, partition);
277 cmap_destroy(&cls->partitions);
279 pvector_destroy(&cls->subtables);
283 /* Set the fields for which prefix lookup should be performed. */
285 classifier_set_prefix_fields(struct classifier *cls,
286 const enum mf_field_id *trie_fields,
287 unsigned int n_fields)
289 const struct mf_field * new_fields[CLS_MAX_TRIES];
290 struct mf_bitmap fields = MF_BITMAP_INITIALIZER;
292 bool changed = false;
294 for (i = 0; i < n_fields && n_tries < CLS_MAX_TRIES; i++) {
295 const struct mf_field *field = mf_from_id(trie_fields[i]);
296 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
297 /* Incompatible field. This is the only place where we
298 * enforce these requirements, but the rest of the trie code
299 * depends on the flow_be32ofs to be non-negative and the
300 * field length to be a multiple of 32 bits. */
304 if (bitmap_is_set(fields.bm, trie_fields[i])) {
305 /* Duplicate field, there is no need to build more than
306 * one index for any one field. */
309 bitmap_set1(fields.bm, trie_fields[i]);
311 new_fields[n_tries] = NULL;
312 if (n_tries >= cls->n_tries || field != cls->tries[n_tries].field) {
313 new_fields[n_tries] = field;
319 if (changed || n_tries < cls->n_tries) {
320 struct cls_subtable *subtable;
322 /* Trie configuration needs to change. Disable trie lookups
323 * for the tries that are changing and wait all the current readers
324 * with the old configuration to be done. */
326 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
327 for (i = 0; i < cls->n_tries; i++) {
328 if ((i < n_tries && new_fields[i]) || i >= n_tries) {
329 if (subtable->trie_plen[i]) {
330 subtable->trie_plen[i] = 0;
336 /* Synchronize if any readers were using tries. The readers may
337 * temporarily function without the trie lookup based optimizations. */
339 /* ovsrcu_synchronize() functions as a memory barrier, so it does
340 * not matter that subtable->trie_plen is not atomic. */
341 ovsrcu_synchronize();
344 /* Now set up the tries. */
345 for (i = 0; i < n_tries; i++) {
347 trie_init(cls, i, new_fields[i]);
350 /* Destroy the rest, if any. */
351 for (; i < cls->n_tries; i++) {
352 trie_init(cls, i, NULL);
355 cls->n_tries = n_tries;
359 return false; /* No change. */
363 trie_init(struct classifier *cls, int trie_idx, const struct mf_field *field)
365 struct cls_trie *trie = &cls->tries[trie_idx];
366 struct cls_subtable *subtable;
368 if (trie_idx < cls->n_tries) {
369 trie_destroy(&trie->root);
371 ovsrcu_set_hidden(&trie->root, NULL);
375 /* Add existing rules to the new trie. */
376 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
379 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
381 struct cls_match *head;
383 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
384 trie_insert(trie, head->cls_rule, plen);
387 /* Initialize subtable's prefix length on this field. This will
388 * allow readers to use the trie. */
389 atomic_thread_fence(memory_order_release);
390 subtable->trie_plen[trie_idx] = plen;
394 /* Returns true if 'cls' contains no classification rules, false otherwise.
395 * Checking the cmap requires no locking. */
397 classifier_is_empty(const struct classifier *cls)
399 return cmap_is_empty(&cls->subtables_map);
402 /* Returns the number of rules in 'cls'. */
404 classifier_count(const struct classifier *cls)
406 /* n_rules is an int, so in the presence of concurrent writers this will
407 * return either the old or a new value. */
412 hash_metadata(ovs_be64 metadata_)
414 uint64_t metadata = (OVS_FORCE uint64_t) metadata_;
415 return hash_uint64(metadata);
418 static struct cls_partition *
419 find_partition(const struct classifier *cls, ovs_be64 metadata, uint32_t hash)
421 struct cls_partition *partition;
423 CMAP_FOR_EACH_WITH_HASH (partition, cmap_node, hash, &cls->partitions) {
424 if (partition->metadata == metadata) {
432 static struct cls_partition *
433 create_partition(struct classifier *cls, struct cls_subtable *subtable,
436 uint32_t hash = hash_metadata(metadata);
437 struct cls_partition *partition = find_partition(cls, metadata, hash);
439 partition = xmalloc(sizeof *partition);
440 partition->metadata = metadata;
442 tag_tracker_init(&partition->tracker);
443 cmap_insert(&cls->partitions, &partition->cmap_node, hash);
445 tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
449 static inline ovs_be32 minimatch_get_ports(const struct minimatch *match)
451 /* Could optimize to use the same map if needed for fast path. */
452 return MINIFLOW_GET_BE32(&match->flow, tp_src)
453 & MINIFLOW_GET_BE32(&match->mask.masks, tp_src);
457 subtable_replace_head_rule(struct classifier *cls OVS_UNUSED,
458 struct cls_subtable *subtable,
459 struct cls_match *head, struct cls_match *new,
460 uint32_t hash, uint32_t ihash[CLS_MAX_INDICES])
462 /* Rule's data is already in the tries. */
464 new->partition = head->partition; /* Steal partition, if any. */
465 head->partition = NULL;
467 for (int i = 0; i < subtable->n_indices; i++) {
468 cmap_replace(&subtable->indices[i], &head->index_nodes[i],
469 &new->index_nodes[i], ihash[i]);
471 cmap_replace(&subtable->rules, &head->cmap_node, &new->cmap_node, hash);
474 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
475 * must not modify or free it.
477 * If 'cls' already contains an identical rule (including wildcards, values of
478 * fixed fields, and priority), replaces the old rule by 'rule' and returns the
479 * rule that was replaced. The caller takes ownership of the returned rule and
480 * is thus responsible for destroying it with cls_rule_destroy(), after RCU
481 * grace period has passed (see ovsrcu_postpone()).
483 * Returns NULL if 'cls' does not contain a rule with an identical key, after
484 * inserting the new rule. In this case, no rules are displaced by the new
485 * rule, even rules that cannot have any effect because the new rule matches a
486 * superset of their flows and has higher priority.
488 const struct cls_rule *
489 classifier_replace(struct classifier *cls, const struct cls_rule *rule)
491 struct cls_match *new = cls_match_alloc(rule);
492 struct cls_subtable *subtable;
493 uint32_t ihash[CLS_MAX_INDICES];
494 uint8_t prev_be32ofs = 0;
495 struct cls_match *head;
501 CONST_CAST(struct cls_rule *, rule)->cls_match = new;
503 subtable = find_subtable(cls, &rule->match.mask);
505 subtable = insert_subtable(cls, &rule->match.mask);
508 /* Compute hashes in segments. */
510 for (i = 0; i < subtable->n_indices; i++) {
511 ihash[i] = minimatch_hash_range(&rule->match, prev_be32ofs,
512 subtable->index_ofs[i], &basis);
513 prev_be32ofs = subtable->index_ofs[i];
515 hash = minimatch_hash_range(&rule->match, prev_be32ofs, FLOW_U32S, &basis);
517 head = find_equal(subtable, &rule->match.flow, hash);
519 /* Add rule to tries.
521 * Concurrent readers might miss seeing the rule until this update,
522 * which might require being fixed up by revalidation later. */
523 for (i = 0; i < cls->n_tries; i++) {
524 if (subtable->trie_plen[i]) {
525 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
529 /* Add rule to ports trie. */
530 if (subtable->ports_mask_len) {
531 /* We mask the value to be inserted to always have the wildcarded
532 * bits in known (zero) state, so we can include them in comparison
533 * and they will always match (== their original value does not
535 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
537 trie_insert_prefix(&subtable->ports_trie, &masked_ports,
538 subtable->ports_mask_len);
541 /* Add rule to partitions.
543 * Concurrent readers might miss seeing the rule until this update,
544 * which might require being fixed up by revalidation later. */
545 new->partition = NULL;
546 if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
547 ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
549 new->partition = create_partition(cls, subtable, metadata);
552 /* Make rule visible to lookups. */
554 /* Add new node to segment indices.
556 * Readers may find the rule in the indices before the rule is visible
557 * in the subtables 'rules' map. This may result in us losing the
558 * opportunity to quit lookups earlier, resulting in sub-optimal
559 * wildcarding. This will be fixed later by revalidation (always
560 * scheduled after flow table changes). */
561 for (i = 0; i < subtable->n_indices; i++) {
562 cmap_insert(&subtable->indices[i], &new->index_nodes[i], ihash[i]);
564 n_rules = cmap_insert(&subtable->rules, &new->cmap_node, hash);
565 } else { /* Equal rules exist in the classifier already. */
566 struct cls_match *iter;
568 /* Scan the list for the insertion point that will keep the list in
569 * order of decreasing priority. */
570 FOR_EACH_RULE_IN_LIST_PROTECTED (iter, head) {
571 if (rule->priority >= iter->priority) {
576 /* 'iter' now at the insertion point or NULL it at end. */
578 struct cls_rule *old;
580 if (rule->priority == iter->priority) {
581 rculist_replace(&new->list, &iter->list);
582 old = CONST_CAST(struct cls_rule *, iter->cls_rule);
584 rculist_insert(&iter->list, &new->list);
588 /* Replace the existing head in data structures, if rule is the new
591 subtable_replace_head_rule(cls, subtable, head, new, hash,
596 ovsrcu_postpone(free, iter);
597 old->cls_match = NULL;
599 /* No change in subtable's max priority or max count. */
601 /* Make rule visible to iterators. */
602 rculist_replace(CONST_CAST(struct rculist *, &rule->node),
605 /* Return displaced rule. Caller is responsible for keeping it
606 * around until all threads quiesce. */
610 rculist_push_back(&head->list, &new->list);
614 /* Make rule visible to iterators. */
615 rculist_push_back(&subtable->rules_list,
616 CONST_CAST(struct rculist *, &rule->node));
618 /* Rule was added, not replaced. Update 'subtable's 'max_priority' and
619 * 'max_count', if necessary.
621 * The rule was already inserted, but concurrent readers may not see the
622 * rule yet as the subtables vector is not updated yet. This will have to
623 * be fixed by revalidation later. */
625 subtable->max_priority = rule->priority;
626 subtable->max_count = 1;
627 pvector_insert(&cls->subtables, subtable, rule->priority);
628 } else if (rule->priority == subtable->max_priority) {
629 ++subtable->max_count;
630 } else if (rule->priority > subtable->max_priority) {
631 subtable->max_priority = rule->priority;
632 subtable->max_count = 1;
633 pvector_change_priority(&cls->subtables, subtable, rule->priority);
636 /* Nothing was replaced. */
640 pvector_publish(&cls->subtables);
646 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
647 * must not modify or free it.
649 * 'cls' must not contain an identical rule (including wildcards, values of
650 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
653 classifier_insert(struct classifier *cls, const struct cls_rule *rule)
655 const struct cls_rule *displaced_rule = classifier_replace(cls, rule);
656 ovs_assert(!displaced_rule);
659 /* Removes 'rule' from 'cls'. It is the caller's responsibility to destroy
660 * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
661 * resides, etc., as necessary.
663 * Does nothing if 'rule' has been already removed, or was never inserted.
665 * Returns the removed rule, or NULL, if it was already removed.
667 const struct cls_rule *
668 classifier_remove(struct classifier *cls, const struct cls_rule *rule)
670 struct cls_partition *partition;
671 struct cls_match *cls_match;
672 struct cls_subtable *subtable;
673 struct cls_match *prev;
674 struct cls_match *next;
676 uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
677 uint8_t prev_be32ofs = 0;
680 cls_match = rule->cls_match;
684 /* Mark as removed. */
685 CONST_CAST(struct cls_rule *, rule)->cls_match = NULL;
687 /* Remove 'rule' from the subtable's rules list. */
688 rculist_remove(CONST_CAST(struct rculist *, &rule->node));
690 INIT_CONTAINER(prev, rculist_back_protected(&cls_match->list), list);
691 INIT_CONTAINER(next, rculist_next(&cls_match->list), list);
693 /* Remove from the list of equal rules. */
694 rculist_remove(&cls_match->list);
696 /* Check if this is NOT a head rule. */
697 if (prev->priority > rule->priority) {
698 /* Not the highest priority rule, no need to check subtable's
703 subtable = find_subtable(cls, &rule->match.mask);
704 ovs_assert(subtable);
706 for (i = 0; i < subtable->n_indices; i++) {
707 ihash[i] = minimatch_hash_range(&rule->match, prev_be32ofs,
708 subtable->index_ofs[i], &basis);
709 prev_be32ofs = subtable->index_ofs[i];
711 hash = minimatch_hash_range(&rule->match, prev_be32ofs, FLOW_U32S, &basis);
713 /* Head rule. Check if 'next' is an identical, lower-priority rule that
714 * will replace 'rule' in the data structures. */
715 if (next->priority < rule->priority) {
716 subtable_replace_head_rule(cls, subtable, cls_match, next, hash,
721 /* 'rule' is last of the kind in the classifier, must remove from all the
722 * data structures. */
724 if (subtable->ports_mask_len) {
725 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
727 trie_remove_prefix(&subtable->ports_trie,
728 &masked_ports, subtable->ports_mask_len);
730 for (i = 0; i < cls->n_tries; i++) {
731 if (subtable->trie_plen[i]) {
732 trie_remove(&cls->tries[i], rule, subtable->trie_plen[i]);
736 /* Remove rule node from indices. */
737 for (i = 0; i < subtable->n_indices; i++) {
738 cmap_remove(&subtable->indices[i], &cls_match->index_nodes[i],
741 n_rules = cmap_remove(&subtable->rules, &cls_match->cmap_node, hash);
743 partition = cls_match->partition;
745 tag_tracker_subtract(&partition->tracker, &partition->tags,
747 if (!partition->tags) {
748 cmap_remove(&cls->partitions, &partition->cmap_node,
749 hash_metadata(partition->metadata));
750 ovsrcu_postpone(free, partition);
755 destroy_subtable(cls, subtable);
758 if (subtable->max_priority == rule->priority
759 && --subtable->max_count == 0) {
760 /* Find the new 'max_priority' and 'max_count'. */
761 struct cls_match *head;
762 int max_priority = INT_MIN;
764 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
765 if (head->priority > max_priority) {
766 max_priority = head->priority;
767 subtable->max_count = 1;
768 } else if (head->priority == max_priority) {
769 ++subtable->max_count;
772 subtable->max_priority = max_priority;
773 pvector_change_priority(&cls->subtables, subtable, max_priority);
778 pvector_publish(&cls->subtables);
782 ovsrcu_postpone(free, cls_match);
788 /* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
789 * subtables which have a prefix match on the trie field, but whose prefix
790 * length is not indicated in 'match_plens'. For example, a subtable that
791 * has a 8-bit trie field prefix match can be skipped if
792 * !be_get_bit_at(&match_plens, 8 - 1). If skipped, 'maskbits' prefix bits
793 * must be unwildcarded to make datapath flow only match packets it should. */
795 const struct cls_trie *trie;
796 bool lookup_done; /* Status of the lookup. */
797 uint8_t be32ofs; /* U32 offset of the field in question. */
798 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
799 union mf_value match_plens; /* Bitmask of prefix lengths with possible
804 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
807 ctx->be32ofs = trie->field->flow_be32ofs;
808 ctx->lookup_done = false;
811 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
812 * Returns a null pointer if no rules in 'cls' match 'flow'. If multiple rules
813 * of equal priority match 'flow', returns one arbitrarily.
815 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
816 * set of bits that were significant in the lookup. At some point
817 * earlier, 'wc' should have been initialized (e.g., by
818 * flow_wildcards_init_catchall()). */
819 const struct cls_rule *
820 classifier_lookup(const struct classifier *cls, const struct flow *flow,
821 struct flow_wildcards *wc)
823 const struct cls_partition *partition;
825 int best_priority = INT_MIN;
826 const struct cls_match *best;
827 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
828 struct cls_subtable *subtable;
830 /* Synchronize for cls->n_tries and subtable->trie_plen. They can change
831 * when table configuration changes, which happens typically only on
833 atomic_thread_fence(memory_order_acquire);
835 /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
836 * then 'flow' cannot possibly match in 'subtable':
838 * - If flow->metadata maps to a given 'partition', then we can use
839 * 'tags' for 'partition->tags'.
841 * - If flow->metadata has no partition, then no rule in 'cls' has an
842 * exact-match for flow->metadata. That means that we don't need to
843 * search any subtable that includes flow->metadata in its mask.
845 * In either case, we always need to search any cls_subtables that do not
846 * include flow->metadata in its mask. One way to do that would be to
847 * check the "cls_subtable"s explicitly for that, but that would require an
848 * extra branch per subtable. Instead, we mark such a cls_subtable's
849 * 'tags' as TAG_ALL and make sure that 'tags' is never empty. This means
850 * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
851 * need a special case.
853 partition = (cmap_is_empty(&cls->partitions)
855 : find_partition(cls, flow->metadata,
856 hash_metadata(flow->metadata)));
857 tags = partition ? partition->tags : TAG_ARBITRARY;
859 /* Initialize trie contexts for find_match_wc(). */
860 for (int i = 0; i < cls->n_tries; i++) {
861 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
865 PVECTOR_FOR_EACH_PRIORITY(subtable, best_priority, 2,
866 sizeof(struct cls_subtable), &cls->subtables) {
867 const struct cls_match *rule;
869 if (!tag_intersects(tags, subtable->tag)) {
873 rule = find_match_wc(subtable, flow, trie_ctx, cls->n_tries, wc);
874 if (rule && rule->priority > best_priority) {
875 best_priority = rule->priority;
880 return best ? best->cls_rule : NULL;
883 /* Finds and returns a rule in 'cls' with exactly the same priority and
884 * matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
885 * contain an exact match. */
886 const struct cls_rule *
887 classifier_find_rule_exactly(const struct classifier *cls,
888 const struct cls_rule *target)
890 const struct cls_match *head, *rule;
891 const struct cls_subtable *subtable;
893 subtable = find_subtable(cls, &target->match.mask);
898 head = find_equal(subtable, &target->match.flow,
899 miniflow_hash_in_minimask(&target->match.flow,
900 &target->match.mask, 0));
904 FOR_EACH_RULE_IN_LIST (rule, head) {
905 if (target->priority >= rule->priority) {
906 return target->priority == rule->priority ? rule->cls_rule : NULL;
912 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
913 * same matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
914 * contain an exact match. */
915 const struct cls_rule *
916 classifier_find_match_exactly(const struct classifier *cls,
917 const struct match *target, int priority)
919 const struct cls_rule *retval;
922 cls_rule_init(&cr, target, priority);
923 retval = classifier_find_rule_exactly(cls, &cr);
924 cls_rule_destroy(&cr);
929 /* Checks if 'target' would overlap any other rule in 'cls'. Two rules are
930 * considered to overlap if both rules have the same priority and a packet
933 * A trivial example of overlapping rules is two rules matching disjoint sets
934 * of fields. E.g., if one rule matches only on port number, while another only
935 * on dl_type, any packet from that specific port and with that specific
936 * dl_type could match both, if the rules also have the same priority. */
938 classifier_rule_overlaps(const struct classifier *cls,
939 const struct cls_rule *target)
941 struct cls_subtable *subtable;
943 /* Iterate subtables in the descending max priority order. */
944 PVECTOR_FOR_EACH_PRIORITY (subtable, target->priority - 1, 2,
945 sizeof(struct cls_subtable), &cls->subtables) {
946 uint32_t storage[FLOW_U32S];
947 struct minimask mask;
948 const struct cls_rule *rule;
950 minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
952 RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
953 if (rule->priority == target->priority
954 && miniflow_equal_in_minimask(&target->match.flow,
955 &rule->match.flow, &mask)) {
963 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
964 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
965 * function returns true if, for every field:
967 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
970 * - 'criteria' wildcards the field,
972 * Conversely, 'rule' does not match 'criteria' and this function returns false
973 * if, for at least one field:
975 * - 'criteria' and 'rule' specify different values for the field, or
977 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
979 * Equivalently, the truth table for whether a field matches is:
984 * r +---------+---------+
985 * i wild | yes | yes |
987 * e +---------+---------+
988 * r exact | no |if values|
990 * a +---------+---------+
992 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
993 * commands and by OpenFlow 1.0 aggregate and flow stats.
995 * Ignores rule->priority. */
997 cls_rule_is_loose_match(const struct cls_rule *rule,
998 const struct minimatch *criteria)
1000 return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
1001 && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
1008 rule_matches(const struct cls_rule *rule, const struct cls_rule *target)
1011 || miniflow_equal_in_minimask(&rule->match.flow,
1012 &target->match.flow,
1013 &target->match.mask));
1016 static const struct cls_rule *
1017 search_subtable(const struct cls_subtable *subtable,
1018 struct cls_cursor *cursor)
1021 || !minimask_has_extra(&subtable->mask, &cursor->target->match.mask)) {
1022 const struct cls_rule *rule;
1024 RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
1025 if (rule_matches(rule, cursor->target)) {
1033 /* Initializes 'cursor' for iterating through rules in 'cls', and returns the
1034 * first matching cls_rule via '*pnode', or NULL if there are no matches.
1036 * - If 'target' is null, the cursor will visit every rule in 'cls'.
1038 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1039 * such that cls_rule_is_loose_match(rule, target) returns true.
1041 * Ignores target->priority. */
1042 struct cls_cursor cls_cursor_start(const struct classifier *cls,
1043 const struct cls_rule *target)
1045 struct cls_cursor cursor;
1046 struct cls_subtable *subtable;
1049 cursor.target = target && !cls_rule_is_catchall(target) ? target : NULL;
1052 /* Find first rule. */
1053 PVECTOR_CURSOR_FOR_EACH (subtable, &cursor.subtables,
1054 &cursor.cls->subtables) {
1055 const struct cls_rule *rule = search_subtable(subtable, &cursor);
1058 cursor.subtable = subtable;
1067 static const struct cls_rule *
1068 cls_cursor_next(struct cls_cursor *cursor)
1070 const struct cls_rule *rule;
1071 const struct cls_subtable *subtable;
1073 rule = cursor->rule;
1074 subtable = cursor->subtable;
1075 RCULIST_FOR_EACH_CONTINUE (rule, node, &subtable->rules_list) {
1076 if (rule_matches(rule, cursor->target)) {
1081 PVECTOR_CURSOR_FOR_EACH_CONTINUE (subtable, &cursor->subtables) {
1082 rule = search_subtable(subtable, cursor);
1084 cursor->subtable = subtable;
1092 /* Sets 'cursor->rule' to the next matching cls_rule in 'cursor''s iteration,
1093 * or to null if all matching rules have been visited. */
1095 cls_cursor_advance(struct cls_cursor *cursor)
1097 cursor->rule = cls_cursor_next(cursor);
1100 static struct cls_subtable *
1101 find_subtable(const struct classifier *cls, const struct minimask *mask)
1103 struct cls_subtable *subtable;
1105 CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, minimask_hash(mask, 0),
1106 &cls->subtables_map) {
1107 if (minimask_equal(mask, &subtable->mask)) {
1114 /* The new subtable will be visible to the readers only after this. */
1115 static struct cls_subtable *
1116 insert_subtable(struct classifier *cls, const struct minimask *mask)
1118 uint32_t hash = minimask_hash(mask, 0);
1119 struct cls_subtable *subtable;
1121 struct flow_wildcards old, new;
1123 int count = count_1bits(mask->masks.map);
1125 subtable = xzalloc(sizeof *subtable - sizeof mask->masks.inline_values
1126 + MINIFLOW_VALUES_SIZE(count));
1127 cmap_init(&subtable->rules);
1128 miniflow_clone_inline(CONST_CAST(struct miniflow *, &subtable->mask.masks),
1129 &mask->masks, count);
1131 /* Init indices for segmented lookup, if any. */
1132 flow_wildcards_init_catchall(&new);
1135 for (i = 0; i < cls->n_flow_segments; i++) {
1136 flow_wildcards_fold_minimask_range(&new, mask, prev,
1137 cls->flow_segments[i]);
1138 /* Add an index if it adds mask bits. */
1139 if (!flow_wildcards_equal(&new, &old)) {
1140 cmap_init(&subtable->indices[index]);
1141 *CONST_CAST(uint8_t *, &subtable->index_ofs[index])
1142 = cls->flow_segments[i];
1146 prev = cls->flow_segments[i];
1148 /* Check if the rest of the subtable's mask adds any bits,
1149 * and remove the last index if it doesn't. */
1151 flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U32S);
1152 if (flow_wildcards_equal(&new, &old)) {
1154 *CONST_CAST(uint8_t *, &subtable->index_ofs[index]) = 0;
1155 cmap_destroy(&subtable->indices[index]);
1158 *CONST_CAST(uint8_t *, &subtable->n_indices) = index;
1160 *CONST_CAST(tag_type *, &subtable->tag) =
1161 (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1162 ? tag_create_deterministic(hash)
1165 for (i = 0; i < cls->n_tries; i++) {
1166 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1167 cls->tries[i].field);
1171 ovsrcu_set_hidden(&subtable->ports_trie, NULL);
1172 *CONST_CAST(int *, &subtable->ports_mask_len)
1173 = 32 - ctz32(ntohl(MINIFLOW_GET_BE32(&mask->masks, tp_src)));
1175 /* List of rules. */
1176 rculist_init(&subtable->rules_list);
1178 cmap_insert(&cls->subtables_map, &subtable->cmap_node, hash);
1183 /* RCU readers may still access the subtable before it is actually freed. */
1185 destroy_subtable(struct classifier *cls, struct cls_subtable *subtable)
1189 pvector_remove(&cls->subtables, subtable);
1190 cmap_remove(&cls->subtables_map, &subtable->cmap_node,
1191 minimask_hash(&subtable->mask, 0));
1193 ovs_assert(ovsrcu_get_protected(struct trie_node *, &subtable->ports_trie)
1195 ovs_assert(cmap_is_empty(&subtable->rules));
1196 ovs_assert(rculist_is_empty(&subtable->rules_list));
1198 for (i = 0; i < subtable->n_indices; i++) {
1199 cmap_destroy(&subtable->indices[i]);
1201 cmap_destroy(&subtable->rules);
1202 ovsrcu_postpone(free, subtable);
1210 static unsigned int be_get_bit_at(const ovs_be32 value[], unsigned int ofs);
1212 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1213 * lookup results. */
1215 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1216 const unsigned int field_plen[CLS_MAX_TRIES],
1217 const struct range ofs, const struct flow *flow,
1218 struct flow_wildcards *wc)
1222 /* Check if we could avoid fully unwildcarding the next level of
1223 * fields using the prefix tries. The trie checks are done only as
1224 * needed to avoid folding in additional bits to the wildcards mask. */
1225 for (j = 0; j < n_tries; j++) {
1226 /* Is the trie field relevant for this subtable? */
1227 if (field_plen[j]) {
1228 struct trie_ctx *ctx = &trie_ctx[j];
1229 uint8_t be32ofs = ctx->be32ofs;
1231 /* Is the trie field within the current range of fields? */
1232 if (be32ofs >= ofs.start && be32ofs < ofs.end) {
1233 /* On-demand trie lookup. */
1234 if (!ctx->lookup_done) {
1235 memset(&ctx->match_plens, 0, sizeof ctx->match_plens);
1236 ctx->maskbits = trie_lookup(ctx->trie, flow,
1238 ctx->lookup_done = true;
1240 /* Possible to skip the rest of the subtable if subtable's
1241 * prefix on the field is not included in the lookup result. */
1242 if (!be_get_bit_at(&ctx->match_plens.be32, field_plen[j] - 1)) {
1243 /* We want the trie lookup to never result in unwildcarding
1244 * any bits that would not be unwildcarded otherwise.
1245 * Since the trie is shared by the whole classifier, it is
1246 * possible that the 'maskbits' contain bits that are
1247 * irrelevant for the partition relevant for the current
1248 * packet. Hence the checks below. */
1250 /* Check that the trie result will not unwildcard more bits
1251 * than this subtable would otherwise. */
1252 if (ctx->maskbits <= field_plen[j]) {
1253 /* Unwildcard the bits and skip the rest. */
1254 mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1255 /* Note: Prerequisite already unwildcarded, as the only
1256 * prerequisite of the supported trie lookup fields is
1257 * the ethertype, which is always unwildcarded. */
1260 /* Can skip if the field is already unwildcarded. */
1261 if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1271 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1272 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1273 * value has the correct value in 'target'.
1275 * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
1276 * target, mask) but this is faster because of the invariant that
1277 * flow->map and mask->masks.map are the same, and that this version
1278 * takes the 'wc'. */
1280 miniflow_and_mask_matches_flow(const struct miniflow *flow,
1281 const struct minimask *mask,
1282 const struct flow *target)
1284 const uint32_t *flowp = miniflow_get_u32_values(flow);
1285 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1288 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1289 uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & *maskp++;
1299 static inline const struct cls_match *
1300 find_match(const struct cls_subtable *subtable, const struct flow *flow,
1303 const struct cls_match *rule;
1305 CMAP_FOR_EACH_WITH_HASH (rule, cmap_node, hash, &subtable->rules) {
1306 if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
1315 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1316 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1317 * value has the correct value in 'target'.
1319 * This function is equivalent to miniflow_and_mask_matches_flow() but this
1320 * version fills in the mask bits in 'wc'. */
1322 miniflow_and_mask_matches_flow_wc(const struct miniflow *flow,
1323 const struct minimask *mask,
1324 const struct flow *target,
1325 struct flow_wildcards *wc)
1327 const uint32_t *flowp = miniflow_get_u32_values(flow);
1328 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1331 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1332 uint32_t mask = *maskp++;
1333 uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & mask;
1336 /* Only unwildcard if none of the differing bits is already
1338 if (!(flow_u32_value(&wc->masks, idx) & diff)) {
1339 /* Keep one bit of the difference. The selected bit may be
1340 * different in big-endian v.s. little-endian systems. */
1341 *flow_u32_lvalue(&wc->masks, idx) |= rightmost_1bit(diff);
1345 /* Fill in the bits that were looked at. */
1346 *flow_u32_lvalue(&wc->masks, idx) |= mask;
1352 /* Unwildcard the fields looked up so far, if any. */
1354 fill_range_wc(const struct cls_subtable *subtable, struct flow_wildcards *wc,
1358 flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, to);
1362 static const struct cls_match *
1363 find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
1364 struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1365 struct flow_wildcards *wc)
1367 uint32_t basis = 0, hash;
1368 const struct cls_match *rule = NULL;
1372 if (OVS_UNLIKELY(!wc)) {
1373 return find_match(subtable, flow,
1374 flow_hash_in_minimask(flow, &subtable->mask, 0));
1378 /* Try to finish early by checking fields in segments. */
1379 for (i = 0; i < subtable->n_indices; i++) {
1380 const struct cmap_node *inode;
1382 ofs.end = subtable->index_ofs[i];
1384 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1386 /* 'wc' bits for the trie field set, now unwildcard the preceding
1387 * bits used so far. */
1388 fill_range_wc(subtable, wc, ofs.start);
1391 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1393 inode = cmap_find(&subtable->indices[i], hash);
1395 /* No match, can stop immediately, but must fold in the bits
1396 * used in lookup so far. */
1397 fill_range_wc(subtable, wc, ofs.end);
1401 /* If we have narrowed down to a single rule already, check whether
1402 * that rule matches. Either way, we're done.
1404 * (Rare) hash collisions may cause us to miss the opportunity for this
1406 if (!cmap_node_next(inode)) {
1407 ASSIGN_CONTAINER(rule, inode - i, index_nodes);
1408 if (miniflow_and_mask_matches_flow_wc(&rule->flow, &subtable->mask,
1414 ofs.start = ofs.end;
1416 ofs.end = FLOW_U32S;
1417 /* Trie check for the final range. */
1418 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1419 fill_range_wc(subtable, wc, ofs.start);
1422 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1424 rule = find_match(subtable, flow, hash);
1425 if (!rule && subtable->ports_mask_len) {
1426 /* Ports are always part of the final range, if any.
1427 * No match was found for the ports. Use the ports trie to figure out
1428 * which ports bits to unwildcard. */
1430 ovs_be32 value, plens, mask;
1432 mask = MINIFLOW_GET_BE32(&subtable->mask.masks, tp_src);
1433 value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
1434 mbits = trie_lookup_value(&subtable->ports_trie, &value, &plens, 32);
1436 ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
1437 mask & be32_prefix_mask(mbits);
1439 /* Unwildcard all bits in the mask upto the ports, as they were used
1440 * to determine there is no match. */
1441 fill_range_wc(subtable, wc, TP_PORTS_OFS32);
1445 /* Must unwildcard all the fields, as they were looked at. */
1446 flow_wildcards_fold_minimask(wc, &subtable->mask);
1450 static struct cls_match *
1451 find_equal(const struct cls_subtable *subtable, const struct miniflow *flow,
1454 struct cls_match *head;
1456 CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1457 if (miniflow_equal(&head->flow, flow)) {
1464 /* A longest-prefix match tree. */
1466 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1467 * Prefixes are in the network byte order, and the offset 0 corresponds to
1468 * the most significant bit of the first byte. The offset can be read as
1469 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1471 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1475 pr += ofs / 32; /* Where to start. */
1476 ofs %= 32; /* How many bits to skip at 'pr'. */
1478 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1479 if (plen > 32 - ofs) { /* Need more than we have already? */
1480 prefix |= ntohl(*++pr) >> (32 - ofs);
1482 /* Return with possible unwanted bits at the end. */
1486 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1487 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1488 * corresponds to the most significant bit of the first byte. The offset can
1489 * be read as "how many bits to skip from the start of the prefix starting at
1492 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1497 if (plen > TRIE_PREFIX_BITS) {
1498 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1500 /* Return with unwanted bits cleared. */
1501 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1504 /* Return the number of equal bits in 'n_bits' of 'prefix's MSBs and a 'value'
1505 * starting at "MSB 0"-based offset 'ofs'. */
1507 prefix_equal_bits(uint32_t prefix, unsigned int n_bits, const ovs_be32 value[],
1510 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, n_bits);
1511 /* Set the bit after the relevant bits to limit the result. */
1512 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - n_bits));
1515 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1516 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1518 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1519 unsigned int ofs, unsigned int plen)
1521 return prefix_equal_bits(node->prefix, MIN(node->n_bits, plen - ofs),
1525 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1526 * be greater than 31. */
1528 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1530 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1533 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1534 * be between 0 and 31, inclusive. */
1536 get_bit_at(const uint32_t prefix, unsigned int ofs)
1538 return (prefix >> (31 - ofs)) & 1u;
1541 /* Create new branch. */
1542 static struct trie_node *
1543 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1544 unsigned int n_rules)
1546 struct trie_node *node = xmalloc(sizeof *node);
1548 node->prefix = trie_get_prefix(prefix, ofs, plen);
1550 if (plen <= TRIE_PREFIX_BITS) {
1551 node->n_bits = plen;
1552 ovsrcu_set_hidden(&node->edges[0], NULL);
1553 ovsrcu_set_hidden(&node->edges[1], NULL);
1554 node->n_rules = n_rules;
1555 } else { /* Need intermediate nodes. */
1556 struct trie_node *subnode = trie_branch_create(prefix,
1557 ofs + TRIE_PREFIX_BITS,
1558 plen - TRIE_PREFIX_BITS,
1560 int bit = get_bit_at(subnode->prefix, 0);
1561 node->n_bits = TRIE_PREFIX_BITS;
1562 ovsrcu_set_hidden(&node->edges[bit], subnode);
1563 ovsrcu_set_hidden(&node->edges[!bit], NULL);
1570 trie_node_destroy(const struct trie_node *node)
1572 ovsrcu_postpone(free, CONST_CAST(struct trie_node *, node));
1575 /* Copy a trie node for modification and postpone delete the old one. */
1576 static struct trie_node *
1577 trie_node_rcu_realloc(const struct trie_node *node)
1579 struct trie_node *new_node = xmalloc(sizeof *node);
1582 trie_node_destroy(node);
1588 trie_destroy(rcu_trie_ptr *trie)
1590 struct trie_node *node = ovsrcu_get_protected(struct trie_node *, trie);
1593 ovsrcu_set_hidden(trie, NULL);
1594 trie_destroy(&node->edges[0]);
1595 trie_destroy(&node->edges[1]);
1596 trie_node_destroy(node);
1601 trie_is_leaf(const struct trie_node *trie)
1604 return !ovsrcu_get(struct trie_node *, &trie->edges[0])
1605 && !ovsrcu_get(struct trie_node *, &trie->edges[1]);
1609 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1610 unsigned int n_bits)
1612 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1615 for (i = 0; i < n_bits / 32; i++) {
1616 mask[i] = OVS_BE32_MAX;
1619 mask[i] |= htonl(~0u << (32 - n_bits % 32));
1624 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
1625 unsigned int n_bits)
1627 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1629 ovs_be32 zeroes = 0;
1631 for (i = 0; i < n_bits / 32; i++) {
1635 zeroes |= ~mask[i] & htonl(~0u << (32 - n_bits % 32));
1638 return !zeroes; /* All 'n_bits' bits set. */
1641 static rcu_trie_ptr *
1642 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
1645 return node->edges + be_get_bit_at(value, ofs);
1648 static const struct trie_node *
1649 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
1652 return ovsrcu_get(struct trie_node *,
1653 &node->edges[be_get_bit_at(value, ofs)]);
1656 /* Set the bit at ("MSB 0"-based) offset 'ofs'. 'ofs' can be greater than 31.
1659 be_set_bit_at(ovs_be32 value[], unsigned int ofs)
1661 ((uint8_t *)value)[ofs / 8] |= 1u << (7 - ofs % 8);
1664 /* Returns the number of bits in the prefix mask necessary to determine a
1665 * mismatch, in case there are longer prefixes in the tree below the one that
1667 * '*plens' will have a bit set for each prefix length that may have matching
1668 * rules. The caller is responsible for clearing the '*plens' prior to
1672 trie_lookup_value(const rcu_trie_ptr *trie, const ovs_be32 value[],
1673 ovs_be32 plens[], unsigned int n_bits)
1675 const struct trie_node *prev = NULL;
1676 const struct trie_node *node = ovsrcu_get(struct trie_node *, trie);
1677 unsigned int match_len = 0; /* Number of matching bits. */
1679 for (; node; prev = node, node = trie_next_node(node, value, match_len)) {
1680 unsigned int eqbits;
1681 /* Check if this edge can be followed. */
1682 eqbits = prefix_equal_bits(node->prefix, node->n_bits, value,
1684 match_len += eqbits;
1685 if (eqbits < node->n_bits) { /* Mismatch, nothing more to be found. */
1686 /* Bit at offset 'match_len' differed. */
1687 return match_len + 1; /* Includes the first mismatching bit. */
1689 /* Full match, check if rules exist at this prefix length. */
1690 if (node->n_rules > 0) {
1691 be_set_bit_at(plens, match_len - 1);
1693 if (match_len >= n_bits) {
1694 return n_bits; /* Full prefix. */
1697 /* node == NULL. Full match so far, but we tried to follow an
1698 * non-existing branch. Need to exclude the other branch if it exists
1699 * (it does not if we were called on an empty trie or 'prev' is a leaf
1701 return !prev || trie_is_leaf(prev) ? match_len : match_len + 1;
1705 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
1706 union mf_value *plens)
1708 const struct mf_field *mf = trie->field;
1710 /* Check that current flow matches the prerequisites for the trie
1711 * field. Some match fields are used for multiple purposes, so we
1712 * must check that the trie is relevant for this flow. */
1713 if (mf_are_prereqs_ok(mf, flow)) {
1714 return trie_lookup_value(&trie->root,
1715 &((ovs_be32 *)flow)[mf->flow_be32ofs],
1716 &plens->be32, mf->n_bits);
1718 memset(plens, 0xff, sizeof *plens); /* All prefixes, no skipping. */
1719 return 0; /* Value not used in this case. */
1722 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
1723 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
1724 * 'miniflow_index' is not NULL. */
1726 minimask_get_prefix_len(const struct minimask *minimask,
1727 const struct mf_field *mf)
1729 unsigned int n_bits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
1730 uint8_t u32_ofs = mf->flow_be32ofs;
1731 uint8_t u32_end = u32_ofs + mf->n_bytes / 4;
1733 for (; u32_ofs < u32_end; ++u32_ofs) {
1735 mask = ntohl((OVS_FORCE ovs_be32)minimask_get(minimask, u32_ofs));
1737 /* Validate mask, count the mask length. */
1740 return 0; /* No bits allowed after mask ended. */
1743 if (~mask & (~mask + 1)) {
1744 return 0; /* Mask not contiguous. */
1746 mask_tz = ctz32(mask);
1747 n_bits += 32 - mask_tz;
1755 * This is called only when mask prefix is known to be CIDR and non-zero.
1756 * Relies on the fact that the flow and mask have the same map, and since
1757 * the mask is CIDR, the storage for the flow field exists even if it
1758 * happened to be zeros.
1760 static const ovs_be32 *
1761 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
1763 return miniflow_get_be32_values(&match->flow) +
1764 count_1bits(match->flow.map & ((UINT64_C(1) << mf->flow_be32ofs) - 1));
1767 /* Insert rule in to the prefix tree.
1768 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1771 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1773 trie_insert_prefix(&trie->root,
1774 minimatch_get_prefix(&rule->match, trie->field), mlen);
1778 trie_insert_prefix(rcu_trie_ptr *edge, const ovs_be32 *prefix, int mlen)
1780 struct trie_node *node;
1783 /* Walk the tree. */
1784 for (; (node = ovsrcu_get_protected(struct trie_node *, edge));
1785 edge = trie_next_edge(node, prefix, ofs)) {
1786 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1788 if (eqbits < node->n_bits) {
1789 /* Mismatch, new node needs to be inserted above. */
1790 int old_branch = get_bit_at(node->prefix, eqbits);
1791 struct trie_node *new_parent;
1793 new_parent = trie_branch_create(prefix, ofs - eqbits, eqbits,
1794 ofs == mlen ? 1 : 0);
1795 /* Copy the node to modify it. */
1796 node = trie_node_rcu_realloc(node);
1797 /* Adjust the new node for its new position in the tree. */
1798 node->prefix <<= eqbits;
1799 node->n_bits -= eqbits;
1800 ovsrcu_set_hidden(&new_parent->edges[old_branch], node);
1802 /* Check if need a new branch for the new rule. */
1804 ovsrcu_set_hidden(&new_parent->edges[!old_branch],
1805 trie_branch_create(prefix, ofs, mlen - ofs,
1808 ovsrcu_set(edge, new_parent); /* Publish changes. */
1811 /* Full match so far. */
1814 /* Full match at the current node, rule needs to be added here. */
1819 /* Must insert a new tree branch for the new rule. */
1820 ovsrcu_set(edge, trie_branch_create(prefix, ofs, mlen - ofs, 1));
1823 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1826 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1828 trie_remove_prefix(&trie->root,
1829 minimatch_get_prefix(&rule->match, trie->field), mlen);
1832 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1835 trie_remove_prefix(rcu_trie_ptr *root, const ovs_be32 *prefix, int mlen)
1837 struct trie_node *node;
1838 rcu_trie_ptr *edges[sizeof(union mf_value) * 8];
1839 int depth = 0, ofs = 0;
1841 /* Walk the tree. */
1842 for (edges[0] = root;
1843 (node = ovsrcu_get_protected(struct trie_node *, edges[depth]));
1844 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
1845 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1847 if (eqbits < node->n_bits) {
1848 /* Mismatch, nothing to be removed. This should never happen, as
1849 * only rules in the classifier are ever removed. */
1850 break; /* Log a warning. */
1852 /* Full match so far. */
1856 /* Full prefix match at the current node, remove rule here. */
1857 if (!node->n_rules) {
1858 break; /* Log a warning. */
1862 /* Check if can prune the tree. */
1863 while (!node->n_rules) {
1864 struct trie_node *next,
1865 *edge0 = ovsrcu_get_protected(struct trie_node *,
1867 *edge1 = ovsrcu_get_protected(struct trie_node *,
1870 if (edge0 && edge1) {
1871 break; /* A branching point, cannot prune. */
1874 /* Else have at most one child node, remove this node. */
1875 next = edge0 ? edge0 : edge1;
1878 if (node->n_bits + next->n_bits > TRIE_PREFIX_BITS) {
1879 break; /* Cannot combine. */
1881 next = trie_node_rcu_realloc(next); /* Modify. */
1883 /* Combine node with next. */
1884 next->prefix = node->prefix | next->prefix >> node->n_bits;
1885 next->n_bits += node->n_bits;
1887 /* Update the parent's edge. */
1888 ovsrcu_set(edges[depth], next); /* Publish changes. */
1889 trie_node_destroy(node);
1891 if (next || !depth) {
1892 /* Branch not pruned or at root, nothing more to do. */
1895 node = ovsrcu_get_protected(struct trie_node *,
1901 /* Cannot go deeper. This should never happen, since only rules
1902 * that actually exist in the classifier are ever removed. */
1903 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");