2 * Copyright (c) 2009, 2010, 2011, 2012, 2013 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"
20 #include <netinet/in.h>
21 #include "byte-order.h"
22 #include "dynamic-string.h"
27 #include "ovs-thread.h"
31 VLOG_DEFINE_THIS_MODULE(classifier);
34 static struct cls_subtable *find_subtable(const struct classifier *,
35 const struct minimask *);
36 static struct cls_subtable *insert_subtable(struct classifier *,
37 const struct minimask *);
39 static void destroy_subtable(struct classifier *, struct cls_subtable *);
41 static void update_subtables_after_insertion(struct classifier *,
42 struct cls_subtable *,
43 unsigned int new_priority);
44 static void update_subtables_after_removal(struct classifier *,
45 struct cls_subtable *,
46 unsigned int del_priority);
48 static struct cls_rule *find_match_wc(const struct cls_subtable *,
49 const struct flow *, struct trie_ctx *,
51 struct flow_wildcards *);
52 static struct cls_rule *find_equal(struct cls_subtable *,
53 const struct miniflow *, uint32_t hash);
54 static struct cls_rule *insert_rule(struct classifier *,
55 struct cls_subtable *, struct cls_rule *);
57 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list. */
58 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD) \
59 for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
60 #define FOR_EACH_RULE_IN_LIST_SAFE(RULE, NEXT, HEAD) \
61 for ((RULE) = (HEAD); \
62 (RULE) != NULL && ((NEXT) = next_rule_in_list(RULE), true); \
65 static struct cls_rule *next_rule_in_list__(struct cls_rule *);
66 static struct cls_rule *next_rule_in_list(struct cls_rule *);
68 static unsigned int minimask_get_prefix_len(const struct minimask *,
69 const struct mf_field *);
70 static void trie_init(struct classifier *, int trie_idx,
71 const struct mf_field *);
72 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
73 unsigned int *checkbits);
75 static void trie_destroy(struct trie_node *);
76 static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
77 static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
78 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
80 static bool mask_prefix_bits_set(const struct flow_wildcards *,
81 uint8_t be32ofs, unsigned int nbits);
83 /* flow/miniflow/minimask/minimatch utilities.
84 * These are only used by the classifier, so place them here to allow
85 * for better optimization. */
87 static inline uint64_t
88 miniflow_get_map_in_range(const struct miniflow *miniflow,
89 uint8_t start, uint8_t end, unsigned int *offset)
91 uint64_t map = miniflow->map;
95 uint64_t msk = (UINT64_C(1) << start) - 1; /* 'start' LSBs set */
96 *offset = count_1bits(map & msk);
99 if (end < FLOW_U32S) {
100 uint64_t msk = (UINT64_C(1) << end) - 1; /* 'end' LSBs set */
106 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
107 * 'mask', given 'basis'.
109 * The hash values returned by this function are the same as those returned by
110 * miniflow_hash_in_minimask(), only the form of the arguments differ. */
111 static inline uint32_t
112 flow_hash_in_minimask(const struct flow *flow, const struct minimask *mask,
115 const uint32_t *flow_u32 = (const uint32_t *)flow;
116 const uint32_t *p = mask->masks.values;
121 for (map = mask->masks.map; map; map = zero_rightmost_1bit(map)) {
122 hash = mhash_add(hash, flow_u32[raw_ctz(map)] & *p++);
125 return mhash_finish(hash, (p - mask->masks.values) * 4);
128 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
129 * 'mask', given 'basis'.
131 * The hash values returned by this function are the same as those returned by
132 * flow_hash_in_minimask(), only the form of the arguments differ. */
133 static inline uint32_t
134 miniflow_hash_in_minimask(const struct miniflow *flow,
135 const struct minimask *mask, uint32_t basis)
137 const uint32_t *p = mask->masks.values;
138 uint32_t hash = basis;
141 MINIFLOW_FOR_EACH_IN_MAP(flow_u32, flow, mask->masks.map) {
142 hash = mhash_add(hash, flow_u32 & *p++);
145 return mhash_finish(hash, (p - mask->masks.values) * 4);
148 /* Returns a hash value for the bits of range [start, end) in 'flow',
149 * where there are 1-bits in 'mask', given 'hash'.
151 * The hash values returned by this function are the same as those returned by
152 * minimatch_hash_range(), only the form of the arguments differ. */
153 static inline uint32_t
154 flow_hash_in_minimask_range(const struct flow *flow,
155 const struct minimask *mask,
156 uint8_t start, uint8_t end, uint32_t *basis)
158 const uint32_t *flow_u32 = (const uint32_t *)flow;
160 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
162 const uint32_t *p = mask->masks.values + offset;
163 uint32_t hash = *basis;
165 for (; map; map = zero_rightmost_1bit(map)) {
166 hash = mhash_add(hash, flow_u32[raw_ctz(map)] & *p++);
169 *basis = hash; /* Allow continuation from the unfinished value. */
170 return mhash_finish(hash, (p - mask->masks.values) * 4);
173 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask. */
175 flow_wildcards_fold_minimask(struct flow_wildcards *wc,
176 const struct minimask *mask)
178 flow_union_with_miniflow(&wc->masks, &mask->masks);
181 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask
182 * in range [start, end). */
184 flow_wildcards_fold_minimask_range(struct flow_wildcards *wc,
185 const struct minimask *mask,
186 uint8_t start, uint8_t end)
188 uint32_t *dst_u32 = (uint32_t *)&wc->masks;
190 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
192 const uint32_t *p = mask->masks.values + offset;
194 for (; map; map = zero_rightmost_1bit(map)) {
195 dst_u32[raw_ctz(map)] |= *p++;
199 /* Returns a hash value for 'flow', given 'basis'. */
200 static inline uint32_t
201 miniflow_hash(const struct miniflow *flow, uint32_t basis)
203 const uint32_t *p = flow->values;
204 uint32_t hash = basis;
205 uint64_t hash_map = 0;
208 for (map = flow->map; map; map = zero_rightmost_1bit(map)) {
210 hash = mhash_add(hash, *p);
211 hash_map |= rightmost_1bit(map);
215 hash = mhash_add(hash, hash_map);
216 hash = mhash_add(hash, hash_map >> 32);
218 return mhash_finish(hash, p - flow->values);
221 /* Returns a hash value for 'mask', given 'basis'. */
222 static inline uint32_t
223 minimask_hash(const struct minimask *mask, uint32_t basis)
225 return miniflow_hash(&mask->masks, basis);
228 /* Returns a hash value for 'match', given 'basis'. */
229 static inline uint32_t
230 minimatch_hash(const struct minimatch *match, uint32_t basis)
232 return miniflow_hash(&match->flow, minimask_hash(&match->mask, basis));
235 /* Returns a hash value for the bits of range [start, end) in 'minimatch',
238 * The hash values returned by this function are the same as those returned by
239 * flow_hash_in_minimask_range(), only the form of the arguments differ. */
240 static inline uint32_t
241 minimatch_hash_range(const struct minimatch *match, uint8_t start, uint8_t end,
245 const uint32_t *p, *q;
246 uint32_t hash = *basis;
249 n = count_1bits(miniflow_get_map_in_range(&match->mask.masks, start, end,
251 q = match->mask.masks.values + offset;
252 p = match->flow.values + offset;
254 for (i = 0; i < n; i++) {
255 hash = mhash_add(hash, p[i] & q[i]);
257 *basis = hash; /* Allow continuation from the unfinished value. */
258 return mhash_finish(hash, (offset + n) * 4);
264 /* Initializes 'rule' to match packets specified by 'match' at the given
265 * 'priority'. 'match' must satisfy the invariant described in the comment at
266 * the definition of struct match.
268 * The caller must eventually destroy 'rule' with cls_rule_destroy().
270 * (OpenFlow uses priorities between 0 and UINT16_MAX, inclusive, but
271 * internally Open vSwitch supports a wider range.) */
273 cls_rule_init(struct cls_rule *rule,
274 const struct match *match, unsigned int priority)
276 minimatch_init(&rule->match, match);
277 rule->priority = priority;
280 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
282 cls_rule_init_from_minimatch(struct cls_rule *rule,
283 const struct minimatch *match,
284 unsigned int priority)
286 minimatch_clone(&rule->match, match);
287 rule->priority = priority;
290 /* Initializes 'dst' as a copy of 'src'.
292 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
294 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
296 minimatch_clone(&dst->match, &src->match);
297 dst->priority = src->priority;
300 /* Initializes 'dst' with the data in 'src', destroying 'src'.
302 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
304 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
306 minimatch_move(&dst->match, &src->match);
307 dst->priority = src->priority;
310 /* Frees memory referenced by 'rule'. Doesn't free 'rule' itself (it's
311 * normally embedded into a larger structure).
313 * ('rule' must not currently be in a classifier.) */
315 cls_rule_destroy(struct cls_rule *rule)
317 minimatch_destroy(&rule->match);
320 /* Returns true if 'a' and 'b' match the same packets at the same priority,
321 * false if they differ in some way. */
323 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
325 return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
328 /* Returns a hash value for 'rule', folding in 'basis'. */
330 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
332 return minimatch_hash(&rule->match, hash_int(rule->priority, basis));
335 /* Appends a string describing 'rule' to 's'. */
337 cls_rule_format(const struct cls_rule *rule, struct ds *s)
339 minimatch_format(&rule->match, s, rule->priority);
342 /* Returns true if 'rule' matches every packet, false otherwise. */
344 cls_rule_is_catchall(const struct cls_rule *rule)
346 return minimask_is_catchall(&rule->match.mask);
349 /* Initializes 'cls' as a classifier that initially contains no classification
352 classifier_init(struct classifier *cls, const uint8_t *flow_segments)
355 hmap_init(&cls->subtables);
356 list_init(&cls->subtables_priority);
357 hmap_init(&cls->partitions);
358 fat_rwlock_init(&cls->rwlock);
359 cls->n_flow_segments = 0;
361 while (cls->n_flow_segments < CLS_MAX_INDICES
362 && *flow_segments < FLOW_U32S) {
363 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
369 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
370 * caller's responsibility. */
372 classifier_destroy(struct classifier *cls)
375 struct cls_subtable *partition, *next_partition;
376 struct cls_subtable *subtable, *next_subtable;
379 for (i = 0; i < cls->n_tries; i++) {
380 trie_destroy(cls->tries[i].root);
383 HMAP_FOR_EACH_SAFE (subtable, next_subtable, hmap_node,
385 destroy_subtable(cls, subtable);
387 hmap_destroy(&cls->subtables);
389 HMAP_FOR_EACH_SAFE (partition, next_partition, hmap_node,
391 hmap_remove(&cls->partitions, &partition->hmap_node);
394 hmap_destroy(&cls->partitions);
395 fat_rwlock_destroy(&cls->rwlock);
399 /* We use uint64_t as a set for the fields below. */
400 BUILD_ASSERT_DECL(MFF_N_IDS <= 64);
402 /* Set the fields for which prefix lookup should be performed. */
404 classifier_set_prefix_fields(struct classifier *cls,
405 const enum mf_field_id *trie_fields,
406 unsigned int n_fields)
411 for (i = 0, trie = 0; i < n_fields && trie < CLS_MAX_TRIES; i++) {
412 const struct mf_field *field = mf_from_id(trie_fields[i]);
413 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
414 /* Incompatible field. This is the only place where we
415 * enforce these requirements, but the rest of the trie code
416 * depends on the flow_be32ofs to be non-negative and the
417 * field length to be a multiple of 32 bits. */
421 if (fields & (UINT64_C(1) << trie_fields[i])) {
422 /* Duplicate field, there is no need to build more than
423 * one index for any one field. */
426 fields |= UINT64_C(1) << trie_fields[i];
428 if (trie >= cls->n_tries || field != cls->tries[trie].field) {
429 trie_init(cls, trie, field);
434 /* Destroy the rest. */
435 for (i = trie; i < cls->n_tries; i++) {
436 trie_init(cls, i, NULL);
442 trie_init(struct classifier *cls, int trie_idx,
443 const struct mf_field *field)
445 struct cls_trie *trie = &cls->tries[trie_idx];
446 struct cls_subtable *subtable;
448 if (trie_idx < cls->n_tries) {
449 trie_destroy(trie->root);
454 /* Add existing rules to the trie. */
455 LIST_FOR_EACH (subtable, list_node, &cls->subtables_priority) {
458 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
459 /* Initialize subtable's prefix length on this field. */
460 subtable->trie_plen[trie_idx] = plen;
463 struct cls_rule *head;
465 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
466 struct cls_rule *rule;
468 FOR_EACH_RULE_IN_LIST (rule, head) {
469 trie_insert(trie, rule, plen);
476 /* Returns true if 'cls' contains no classification rules, false otherwise. */
478 classifier_is_empty(const struct classifier *cls)
480 return cls->n_rules == 0;
483 /* Returns the number of rules in 'cls'. */
485 classifier_count(const struct classifier *cls)
491 hash_metadata(ovs_be64 metadata_)
493 uint64_t metadata = (OVS_FORCE uint64_t) metadata_;
494 return hash_uint64(metadata);
497 static struct cls_partition *
498 find_partition(const struct classifier *cls, ovs_be64 metadata, uint32_t hash)
500 struct cls_partition *partition;
502 HMAP_FOR_EACH_IN_BUCKET (partition, hmap_node, hash, &cls->partitions) {
503 if (partition->metadata == metadata) {
511 static struct cls_partition *
512 create_partition(struct classifier *cls, struct cls_subtable *subtable,
515 uint32_t hash = hash_metadata(metadata);
516 struct cls_partition *partition = find_partition(cls, metadata, hash);
518 partition = xmalloc(sizeof *partition);
519 partition->metadata = metadata;
521 tag_tracker_init(&partition->tracker);
522 hmap_insert(&cls->partitions, &partition->hmap_node, hash);
524 tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
528 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
529 * must not modify or free it.
531 * If 'cls' already contains an identical rule (including wildcards, values of
532 * fixed fields, and priority), replaces the old rule by 'rule' and returns the
533 * rule that was replaced. The caller takes ownership of the returned rule and
534 * is thus responsible for destroying it with cls_rule_destroy(), freeing the
535 * memory block in which it resides, etc., as necessary.
537 * Returns NULL if 'cls' does not contain a rule with an identical key, after
538 * inserting the new rule. In this case, no rules are displaced by the new
539 * rule, even rules that cannot have any effect because the new rule matches a
540 * superset of their flows and has higher priority. */
542 classifier_replace(struct classifier *cls, struct cls_rule *rule)
544 struct cls_rule *old_rule;
545 struct cls_subtable *subtable;
547 subtable = find_subtable(cls, &rule->match.mask);
549 subtable = insert_subtable(cls, &rule->match.mask);
552 old_rule = insert_rule(cls, subtable, rule);
556 if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
557 ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
558 rule->partition = create_partition(cls, subtable, metadata);
560 rule->partition = NULL;
566 for (i = 0; i < cls->n_tries; i++) {
567 if (subtable->trie_plen[i]) {
568 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
572 rule->partition = old_rule->partition;
577 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
578 * must not modify or free it.
580 * 'cls' must not contain an identical rule (including wildcards, values of
581 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
584 classifier_insert(struct classifier *cls, struct cls_rule *rule)
586 struct cls_rule *displaced_rule = classifier_replace(cls, rule);
587 ovs_assert(!displaced_rule);
590 /* Removes 'rule' from 'cls'. It is the caller's responsibility to destroy
591 * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
592 * resides, etc., as necessary. */
594 classifier_remove(struct classifier *cls, struct cls_rule *rule)
596 struct cls_partition *partition;
597 struct cls_rule *head;
598 struct cls_subtable *subtable;
601 subtable = find_subtable(cls, &rule->match.mask);
603 for (i = 0; i < cls->n_tries; i++) {
604 if (subtable->trie_plen[i]) {
605 trie_remove(&cls->tries[i], rule, subtable->trie_plen[i]);
609 /* Remove rule node from indices. */
610 for (i = 0; i < subtable->n_indices; i++) {
611 hindex_remove(&subtable->indices[i], &rule->index_nodes[i]);
614 head = find_equal(subtable, &rule->match.flow, rule->hmap_node.hash);
616 list_remove(&rule->list);
617 } else if (list_is_empty(&rule->list)) {
618 hmap_remove(&subtable->rules, &rule->hmap_node);
620 struct cls_rule *next = CONTAINER_OF(rule->list.next,
621 struct cls_rule, list);
623 list_remove(&rule->list);
624 hmap_replace(&subtable->rules, &rule->hmap_node, &next->hmap_node);
627 partition = rule->partition;
629 tag_tracker_subtract(&partition->tracker, &partition->tags,
631 if (!partition->tags) {
632 hmap_remove(&cls->partitions, &partition->hmap_node);
637 if (--subtable->n_rules == 0) {
638 destroy_subtable(cls, subtable);
640 update_subtables_after_removal(cls, subtable, rule->priority);
646 /* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
647 * subtables which have more than 'match_plen' bits in their corresponding
648 * field at offset 'be32ofs'. If skipped, 'maskbits' prefix bits should be
649 * unwildcarded to quarantee datapath flow matches only packets it should. */
651 const struct cls_trie *trie;
652 bool lookup_done; /* Status of the lookup. */
653 uint8_t be32ofs; /* U32 offset of the field in question. */
654 unsigned int match_plen; /* Longest prefix than could possibly match. */
655 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
659 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
662 ctx->be32ofs = trie->field->flow_be32ofs;
663 ctx->lookup_done = false;
666 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
667 * Returns a null pointer if no rules in 'cls' match 'flow'. If multiple rules
668 * of equal priority match 'flow', returns one arbitrarily.
670 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
671 * set of bits that were significant in the lookup. At some point
672 * earlier, 'wc' should have been initialized (e.g., by
673 * flow_wildcards_init_catchall()). */
675 classifier_lookup(const struct classifier *cls, const struct flow *flow,
676 struct flow_wildcards *wc)
678 const struct cls_partition *partition;
679 struct cls_subtable *subtable;
680 struct cls_rule *best;
682 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
685 /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
686 * then 'flow' cannot possibly match in 'subtable':
688 * - If flow->metadata maps to a given 'partition', then we can use
689 * 'tags' for 'partition->tags'.
691 * - If flow->metadata has no partition, then no rule in 'cls' has an
692 * exact-match for flow->metadata. That means that we don't need to
693 * search any subtable that includes flow->metadata in its mask.
695 * In either case, we always need to search any cls_subtables that do not
696 * include flow->metadata in its mask. One way to do that would be to
697 * check the "cls_subtable"s explicitly for that, but that would require an
698 * extra branch per subtable. Instead, we mark such a cls_subtable's
699 * 'tags' as TAG_ALL and make sure that 'tags' is never empty. This means
700 * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
701 * need a special case.
703 partition = (hmap_is_empty(&cls->partitions)
705 : find_partition(cls, flow->metadata,
706 hash_metadata(flow->metadata)));
707 tags = partition ? partition->tags : TAG_ARBITRARY;
709 /* Initialize trie contexts for match_find_wc(). */
710 for (i = 0; i < cls->n_tries; i++) {
711 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
714 LIST_FOR_EACH (subtable, list_node, &cls->subtables_priority) {
715 struct cls_rule *rule;
717 if (!tag_intersects(tags, subtable->tag)) {
721 rule = find_match_wc(subtable, flow, trie_ctx, cls->n_tries, wc);
724 LIST_FOR_EACH_CONTINUE (subtable, list_node,
725 &cls->subtables_priority) {
726 if (subtable->max_priority <= best->priority) {
727 /* Subtables are in descending priority order,
728 * can not find anything better. */
731 if (!tag_intersects(tags, subtable->tag)) {
735 rule = find_match_wc(subtable, flow, trie_ctx, cls->n_tries,
737 if (rule && rule->priority > best->priority) {
748 /* Returns true if 'target' satisifies 'match', that is, if each bit for which
749 * 'match' specifies a particular value has the correct value in 'target'. */
751 minimatch_matches_miniflow(const struct minimatch *match,
752 const struct miniflow *target)
754 const uint32_t *flowp = (const uint32_t *)match->flow.values;
755 const uint32_t *maskp = (const uint32_t *)match->mask.masks.values;
758 MINIFLOW_FOR_EACH_IN_MAP(target_u32, target, match->mask.masks.map) {
759 if ((*flowp++ ^ target_u32) & *maskp++) {
767 static inline struct cls_rule *
768 find_match_miniflow(const struct cls_subtable *subtable,
769 const struct miniflow *flow,
772 struct cls_rule *rule;
774 HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &subtable->rules) {
775 if (minimatch_matches_miniflow(&rule->match, flow)) {
783 /* Finds and returns the highest-priority rule in 'cls' that matches
784 * 'miniflow'. Returns a null pointer if no rules in 'cls' match 'flow'.
785 * If multiple rules of equal priority match 'flow', returns one arbitrarily.
787 * This function is optimized for the userspace datapath, which only ever has
788 * one priority value for it's flows!
790 struct cls_rule *classifier_lookup_miniflow_first(const struct classifier *cls,
791 const struct miniflow *flow)
793 struct cls_subtable *subtable;
795 LIST_FOR_EACH (subtable, list_node, &cls->subtables_priority) {
796 struct cls_rule *rule;
798 rule = find_match_miniflow(subtable, flow,
799 miniflow_hash_in_minimask(flow,
810 /* Finds and returns a rule in 'cls' with exactly the same priority and
811 * matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
812 * contain an exact match. */
814 classifier_find_rule_exactly(const struct classifier *cls,
815 const struct cls_rule *target)
817 struct cls_rule *head, *rule;
818 struct cls_subtable *subtable;
820 subtable = find_subtable(cls, &target->match.mask);
825 /* Skip if there is no hope. */
826 if (target->priority > subtable->max_priority) {
830 head = find_equal(subtable, &target->match.flow,
831 miniflow_hash_in_minimask(&target->match.flow,
832 &target->match.mask, 0));
833 FOR_EACH_RULE_IN_LIST (rule, head) {
834 if (target->priority >= rule->priority) {
835 return target->priority == rule->priority ? rule : NULL;
841 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
842 * same matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
843 * contain an exact match. */
845 classifier_find_match_exactly(const struct classifier *cls,
846 const struct match *target,
847 unsigned int priority)
849 struct cls_rule *retval;
852 cls_rule_init(&cr, target, priority);
853 retval = classifier_find_rule_exactly(cls, &cr);
854 cls_rule_destroy(&cr);
859 /* Checks if 'target' would overlap any other rule in 'cls'. Two rules are
860 * considered to overlap if both rules have the same priority and a packet
861 * could match both. */
863 classifier_rule_overlaps(const struct classifier *cls,
864 const struct cls_rule *target)
866 struct cls_subtable *subtable;
868 /* Iterate subtables in the descending max priority order. */
869 LIST_FOR_EACH (subtable, list_node, &cls->subtables_priority) {
870 uint32_t storage[FLOW_U32S];
871 struct minimask mask;
872 struct cls_rule *head;
874 if (target->priority > subtable->max_priority) {
875 break; /* Can skip this and the rest of the subtables. */
878 minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
879 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
880 struct cls_rule *rule;
882 FOR_EACH_RULE_IN_LIST (rule, head) {
883 if (rule->priority < target->priority) {
884 break; /* Rules in descending priority order. */
886 if (rule->priority == target->priority
887 && miniflow_equal_in_minimask(&target->match.flow,
888 &rule->match.flow, &mask)) {
898 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
899 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
900 * function returns true if, for every field:
902 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
905 * - 'criteria' wildcards the field,
907 * Conversely, 'rule' does not match 'criteria' and this function returns false
908 * if, for at least one field:
910 * - 'criteria' and 'rule' specify different values for the field, or
912 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
914 * Equivalently, the truth table for whether a field matches is:
919 * r +---------+---------+
920 * i wild | yes | yes |
922 * e +---------+---------+
923 * r exact | no |if values|
925 * a +---------+---------+
927 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
928 * commands and by OpenFlow 1.0 aggregate and flow stats.
930 * Ignores rule->priority. */
932 cls_rule_is_loose_match(const struct cls_rule *rule,
933 const struct minimatch *criteria)
935 return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
936 && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
943 rule_matches(const struct cls_rule *rule, const struct cls_rule *target)
946 || miniflow_equal_in_minimask(&rule->match.flow,
948 &target->match.mask));
951 static struct cls_rule *
952 search_subtable(const struct cls_subtable *subtable,
953 const struct cls_rule *target)
955 if (!target || !minimask_has_extra(&subtable->mask, &target->match.mask)) {
956 struct cls_rule *rule;
958 HMAP_FOR_EACH (rule, hmap_node, &subtable->rules) {
959 if (rule_matches(rule, target)) {
967 /* Initializes 'cursor' for iterating through rules in 'cls':
969 * - If 'target' is null, the cursor will visit every rule in 'cls'.
971 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
972 * such that cls_rule_is_loose_match(rule, target) returns true.
974 * Ignores target->priority. */
976 cls_cursor_init(struct cls_cursor *cursor, const struct classifier *cls,
977 const struct cls_rule *target)
980 cursor->target = target && !cls_rule_is_catchall(target) ? target : NULL;
983 /* Returns the first matching cls_rule in 'cursor''s iteration, or a null
984 * pointer if there are no matches. */
986 cls_cursor_first(struct cls_cursor *cursor)
988 struct cls_subtable *subtable;
990 HMAP_FOR_EACH (subtable, hmap_node, &cursor->cls->subtables) {
991 struct cls_rule *rule = search_subtable(subtable, cursor->target);
993 cursor->subtable = subtable;
1001 /* Returns the next matching cls_rule in 'cursor''s iteration, or a null
1002 * pointer if there are no more matches. */
1004 cls_cursor_next(struct cls_cursor *cursor, const struct cls_rule *rule_)
1006 struct cls_rule *rule = CONST_CAST(struct cls_rule *, rule_);
1007 const struct cls_subtable *subtable;
1008 struct cls_rule *next;
1010 next = next_rule_in_list__(rule);
1011 if (next->priority < rule->priority) {
1015 /* 'next' is the head of the list, that is, the rule that is included in
1016 * the subtable's hmap. (This is important when the classifier contains
1017 * rules that differ only in priority.) */
1019 HMAP_FOR_EACH_CONTINUE (rule, hmap_node, &cursor->subtable->rules) {
1020 if (rule_matches(rule, cursor->target)) {
1025 subtable = cursor->subtable;
1026 HMAP_FOR_EACH_CONTINUE (subtable, hmap_node, &cursor->cls->subtables) {
1027 rule = search_subtable(subtable, cursor->target);
1029 cursor->subtable = subtable;
1037 static struct cls_subtable *
1038 find_subtable(const struct classifier *cls, const struct minimask *mask)
1040 struct cls_subtable *subtable;
1042 HMAP_FOR_EACH_IN_BUCKET (subtable, hmap_node, minimask_hash(mask, 0),
1044 if (minimask_equal(mask, &subtable->mask)) {
1051 static struct cls_subtable *
1052 insert_subtable(struct classifier *cls, const struct minimask *mask)
1054 uint32_t hash = minimask_hash(mask, 0);
1055 struct cls_subtable *subtable;
1057 struct flow_wildcards old, new;
1060 subtable = xzalloc(sizeof *subtable);
1061 hmap_init(&subtable->rules);
1062 minimask_clone(&subtable->mask, mask);
1064 /* Init indices for segmented lookup, if any. */
1065 flow_wildcards_init_catchall(&new);
1068 for (i = 0; i < cls->n_flow_segments; i++) {
1069 flow_wildcards_fold_minimask_range(&new, mask, prev,
1070 cls->flow_segments[i]);
1071 /* Add an index if it adds mask bits. */
1072 if (!flow_wildcards_equal(&new, &old)) {
1073 hindex_init(&subtable->indices[index]);
1074 subtable->index_ofs[index] = cls->flow_segments[i];
1078 prev = cls->flow_segments[i];
1080 /* Check if the rest of the subtable's mask adds any bits,
1081 * and remove the last index if it doesn't. */
1083 flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U32S);
1084 if (flow_wildcards_equal(&new, &old)) {
1086 subtable->index_ofs[index] = 0;
1087 hindex_destroy(&subtable->indices[index]);
1090 subtable->n_indices = index;
1092 hmap_insert(&cls->subtables, &subtable->hmap_node, hash);
1093 list_push_back(&cls->subtables_priority, &subtable->list_node);
1094 subtable->tag = (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1095 ? tag_create_deterministic(hash)
1098 for (i = 0; i < cls->n_tries; i++) {
1099 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1100 cls->tries[i].field);
1107 destroy_subtable(struct classifier *cls, struct cls_subtable *subtable)
1111 for (i = 0; i < subtable->n_indices; i++) {
1112 hindex_destroy(&subtable->indices[i]);
1114 minimask_destroy(&subtable->mask);
1115 hmap_remove(&cls->subtables, &subtable->hmap_node);
1116 hmap_destroy(&subtable->rules);
1117 list_remove(&subtable->list_node);
1121 /* This function performs the following updates for 'subtable' in 'cls'
1122 * following the addition of a new rule with priority 'new_priority' to
1125 * - Update 'subtable->max_priority' and 'subtable->max_count' if necessary.
1127 * - Update 'subtable''s position in 'cls->subtables_priority' if necessary.
1129 * This function should only be called after adding a new rule, not after
1130 * replacing a rule by an identical one or modifying a rule in-place. */
1132 update_subtables_after_insertion(struct classifier *cls,
1133 struct cls_subtable *subtable,
1134 unsigned int new_priority)
1136 if (new_priority == subtable->max_priority) {
1137 ++subtable->max_count;
1138 } else if (new_priority > subtable->max_priority) {
1139 struct cls_subtable *iter;
1141 subtable->max_priority = new_priority;
1142 subtable->max_count = 1;
1144 /* Possibly move 'subtable' earlier in the priority list. If we break
1145 * out of the loop, then 'subtable' should be moved just after that
1146 * 'iter'. If the loop terminates normally, then 'iter' will be the
1147 * list head and we'll move subtable just after that (e.g. to the front
1150 LIST_FOR_EACH_REVERSE_CONTINUE (iter, list_node,
1151 &cls->subtables_priority) {
1152 if (iter->max_priority >= subtable->max_priority) {
1157 /* Move 'subtable' just after 'iter' (unless it's already there). */
1158 if (iter->list_node.next != &subtable->list_node) {
1159 list_splice(iter->list_node.next,
1160 &subtable->list_node, subtable->list_node.next);
1165 /* This function performs the following updates for 'subtable' in 'cls'
1166 * following the deletion of a rule with priority 'del_priority' from
1169 * - Update 'subtable->max_priority' and 'subtable->max_count' if necessary.
1171 * - Update 'subtable''s position in 'cls->subtables_priority' if necessary.
1173 * This function should only be called after removing a rule, not after
1174 * replacing a rule by an identical one or modifying a rule in-place. */
1176 update_subtables_after_removal(struct classifier *cls,
1177 struct cls_subtable *subtable,
1178 unsigned int del_priority)
1180 struct cls_subtable *iter;
1182 if (del_priority == subtable->max_priority && --subtable->max_count == 0) {
1183 struct cls_rule *head;
1185 subtable->max_priority = 0;
1186 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
1187 if (head->priority > subtable->max_priority) {
1188 subtable->max_priority = head->priority;
1189 subtable->max_count = 1;
1190 } else if (head->priority == subtable->max_priority) {
1191 ++subtable->max_count;
1195 /* Possibly move 'subtable' later in the priority list. If we break
1196 * out of the loop, then 'subtable' should be moved just before that
1197 * 'iter'. If the loop terminates normally, then 'iter' will be the
1198 * list head and we'll move subtable just before that (e.g. to the back
1201 LIST_FOR_EACH_CONTINUE (iter, list_node, &cls->subtables_priority) {
1202 if (iter->max_priority <= subtable->max_priority) {
1207 /* Move 'subtable' just before 'iter' (unless it's already there). */
1208 if (iter->list_node.prev != &subtable->list_node) {
1209 list_splice(&iter->list_node,
1210 &subtable->list_node, subtable->list_node.next);
1220 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1221 * lookup results. */
1223 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1224 const unsigned int field_plen[CLS_MAX_TRIES],
1225 const struct range ofs, const struct flow *flow,
1226 struct flow_wildcards *wc)
1230 /* Check if we could avoid fully unwildcarding the next level of
1231 * fields using the prefix tries. The trie checks are done only as
1232 * needed to avoid folding in additional bits to the wildcards mask. */
1233 for (j = 0; j < n_tries; j++) {
1234 /* Is the trie field relevant for this subtable? */
1235 if (field_plen[j]) {
1236 struct trie_ctx *ctx = &trie_ctx[j];
1237 uint8_t be32ofs = ctx->be32ofs;
1239 /* Is the trie field within the current range of fields? */
1240 if (be32ofs >= ofs.start && be32ofs < ofs.end) {
1241 /* On-demand trie lookup. */
1242 if (!ctx->lookup_done) {
1243 ctx->match_plen = trie_lookup(ctx->trie, flow,
1245 ctx->lookup_done = true;
1247 /* Possible to skip the rest of the subtable if subtable's
1248 * prefix on the field is longer than what is known to match
1249 * based on the trie lookup. */
1250 if (field_plen[j] > ctx->match_plen) {
1251 /* RFC: We want the trie lookup to never result in
1252 * unwildcarding any bits that would not be unwildcarded
1253 * otherwise. Since the trie is shared by the whole
1254 * classifier, it is possible that the 'maskbits' contain
1255 * bits that are irrelevant for the partition of the
1256 * classifier relevant for the current flow. */
1258 /* Can skip if the field is already unwildcarded. */
1259 if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1262 /* Check that the trie result will not unwildcard more bits
1263 * than this stage will. */
1264 if (ctx->maskbits <= field_plen[j]) {
1265 /* Unwildcard the bits and skip the rest. */
1266 mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1267 /* Note: Prerequisite already unwildcarded, as the only
1268 * prerequisite of the supported trie lookup fields is
1269 * the ethertype, which is currently always
1281 static inline struct cls_rule *
1282 find_match(const struct cls_subtable *subtable, const struct flow *flow,
1285 struct cls_rule *rule;
1287 HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &subtable->rules) {
1288 if (minimatch_matches_flow(&rule->match, flow)) {
1296 static struct cls_rule *
1297 find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
1298 struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1299 struct flow_wildcards *wc)
1301 uint32_t basis = 0, hash;
1302 struct cls_rule *rule = NULL;
1307 return find_match(subtable, flow,
1308 flow_hash_in_minimask(flow, &subtable->mask, 0));
1312 /* Try to finish early by checking fields in segments. */
1313 for (i = 0; i < subtable->n_indices; i++) {
1314 struct hindex_node *inode;
1315 ofs.end = subtable->index_ofs[i];
1317 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1321 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1323 ofs.start = ofs.end;
1324 inode = hindex_node_with_hash(&subtable->indices[i], hash);
1326 /* No match, can stop immediately, but must fold in the mask
1327 * covered so far. */
1331 /* If we have narrowed down to a single rule already, check whether
1332 * that rule matches. If it does match, then we're done. If it does
1333 * not match, then we know that we will never get a match, but we do
1334 * not yet know how many wildcards we need to fold into 'wc' so we
1335 * continue iterating through indices to find that out. (We won't
1336 * waste time calling minimatch_matches_flow() again because we've set
1339 * This check shows a measurable benefit with non-trivial flow tables.
1341 * (Rare) hash collisions may cause us to miss the opportunity for this
1343 if (!inode->s && !rule) {
1344 ASSIGN_CONTAINER(rule, inode - i, index_nodes);
1345 if (minimatch_matches_flow(&rule->match, flow)) {
1350 ofs.end = FLOW_U32S;
1351 /* Trie check for the final range. */
1352 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1356 /* Multiple potential matches exist, look for one. */
1357 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1359 rule = find_match(subtable, flow, hash);
1361 /* We already narrowed the matching candidates down to just 'rule',
1362 * but it didn't match. */
1366 /* Must unwildcard all the fields, as they were looked at. */
1367 flow_wildcards_fold_minimask(wc, &subtable->mask);
1371 /* Must unwildcard the fields looked up so far, if any. */
1373 flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, ofs.start);
1378 static struct cls_rule *
1379 find_equal(struct cls_subtable *subtable, const struct miniflow *flow,
1382 struct cls_rule *head;
1384 HMAP_FOR_EACH_WITH_HASH (head, hmap_node, hash, &subtable->rules) {
1385 if (miniflow_equal(&head->match.flow, flow)) {
1392 static struct cls_rule *
1393 insert_rule(struct classifier *cls, struct cls_subtable *subtable,
1394 struct cls_rule *new)
1396 struct cls_rule *head;
1397 struct cls_rule *old = NULL;
1399 uint32_t basis = 0, hash;
1400 uint8_t prev_be32ofs = 0;
1402 /* Add new node to segment indices. */
1403 for (i = 0; i < subtable->n_indices; i++) {
1404 hash = minimatch_hash_range(&new->match, prev_be32ofs,
1405 subtable->index_ofs[i], &basis);
1406 hindex_insert(&subtable->indices[i], &new->index_nodes[i], hash);
1407 prev_be32ofs = subtable->index_ofs[i];
1409 hash = minimatch_hash_range(&new->match, prev_be32ofs, FLOW_U32S, &basis);
1410 head = find_equal(subtable, &new->match.flow, hash);
1412 hmap_insert(&subtable->rules, &new->hmap_node, hash);
1413 list_init(&new->list);
1416 /* Scan the list for the insertion point that will keep the list in
1417 * order of decreasing priority. */
1418 struct cls_rule *rule;
1420 new->hmap_node.hash = hash; /* Otherwise done by hmap_insert. */
1422 FOR_EACH_RULE_IN_LIST (rule, head) {
1423 if (new->priority >= rule->priority) {
1425 /* 'new' is the new highest-priority flow in the list. */
1426 hmap_replace(&subtable->rules,
1427 &rule->hmap_node, &new->hmap_node);
1430 if (new->priority == rule->priority) {
1431 list_replace(&new->list, &rule->list);
1435 list_insert(&rule->list, &new->list);
1441 /* Insert 'new' at the end of the list. */
1442 list_push_back(&head->list, &new->list);
1447 update_subtables_after_insertion(cls, subtable, new->priority);
1449 /* Remove old node from indices. */
1450 for (i = 0; i < subtable->n_indices; i++) {
1451 hindex_remove(&subtable->indices[i], &old->index_nodes[i]);
1457 static struct cls_rule *
1458 next_rule_in_list__(struct cls_rule *rule)
1460 struct cls_rule *next = OBJECT_CONTAINING(rule->list.next, next, list);
1464 static struct cls_rule *
1465 next_rule_in_list(struct cls_rule *rule)
1467 struct cls_rule *next = next_rule_in_list__(rule);
1468 return next->priority < rule->priority ? next : NULL;
1471 /* A longest-prefix match tree. */
1473 uint32_t prefix; /* Prefix bits for this node, MSB first. */
1474 uint8_t nbits; /* Never zero, except for the root node. */
1475 unsigned int n_rules; /* Number of rules that have this prefix. */
1476 struct trie_node *edges[2]; /* Both NULL if leaf. */
1479 /* Max bits per node. Must fit in struct trie_node's 'prefix'.
1480 * Also tested with 16, 8, and 5 to stress the implementation. */
1481 #define TRIE_PREFIX_BITS 32
1483 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1484 * Prefixes are in the network byte order, and the offset 0 corresponds to
1485 * the most significant bit of the first byte. The offset can be read as
1486 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1488 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1492 pr += ofs / 32; /* Where to start. */
1493 ofs %= 32; /* How many bits to skip at 'pr'. */
1495 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1496 if (plen > 32 - ofs) { /* Need more than we have already? */
1497 prefix |= ntohl(*++pr) >> (32 - ofs);
1499 /* Return with possible unwanted bits at the end. */
1503 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1504 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1505 * corresponds to the most significant bit of the first byte. The offset can
1506 * be read as "how many bits to skip from the start of the prefix starting at
1509 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1514 if (plen > TRIE_PREFIX_BITS) {
1515 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1517 /* Return with unwanted bits cleared. */
1518 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1521 /* Return the number of equal bits in 'nbits' of 'prefix's MSBs and a 'value'
1522 * starting at "MSB 0"-based offset 'ofs'. */
1524 prefix_equal_bits(uint32_t prefix, unsigned int nbits, const ovs_be32 value[],
1527 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, nbits);
1528 /* Set the bit after the relevant bits to limit the result. */
1529 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - nbits));
1532 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1533 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1535 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1536 unsigned int ofs, unsigned int plen)
1538 return prefix_equal_bits(node->prefix, MIN(node->nbits, plen - ofs),
1542 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1543 * be greater than 31. */
1545 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1547 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1550 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1551 * be between 0 and 31, inclusive. */
1553 get_bit_at(const uint32_t prefix, unsigned int ofs)
1555 return (prefix >> (31 - ofs)) & 1u;
1558 /* Create new branch. */
1559 static struct trie_node *
1560 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1561 unsigned int n_rules)
1563 struct trie_node *node = xmalloc(sizeof *node);
1565 node->prefix = trie_get_prefix(prefix, ofs, plen);
1567 if (plen <= TRIE_PREFIX_BITS) {
1569 node->edges[0] = NULL;
1570 node->edges[1] = NULL;
1571 node->n_rules = n_rules;
1572 } else { /* Need intermediate nodes. */
1573 struct trie_node *subnode = trie_branch_create(prefix,
1574 ofs + TRIE_PREFIX_BITS,
1575 plen - TRIE_PREFIX_BITS,
1577 int bit = get_bit_at(subnode->prefix, 0);
1578 node->nbits = TRIE_PREFIX_BITS;
1579 node->edges[bit] = subnode;
1580 node->edges[!bit] = NULL;
1587 trie_node_destroy(struct trie_node *node)
1593 trie_destroy(struct trie_node *node)
1596 trie_destroy(node->edges[0]);
1597 trie_destroy(node->edges[1]);
1603 trie_is_leaf(const struct trie_node *trie)
1605 return !trie->edges[0] && !trie->edges[1]; /* No children. */
1609 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1612 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1615 for (i = 0; i < nbits / 32; i++) {
1616 mask[i] = OVS_BE32_MAX;
1619 mask[i] |= htonl(~0u << (32 - nbits % 32));
1624 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
1627 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1629 ovs_be32 zeroes = 0;
1631 for (i = 0; i < nbits / 32; i++) {
1635 zeroes |= ~mask[i] & htonl(~0u << (32 - nbits % 32));
1638 return !zeroes; /* All 'nbits' bits set. */
1641 static struct trie_node **
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 node->edges[be_get_bit_at(value, ofs)];
1655 /* Return the prefix mask length necessary to find the longest-prefix match for
1656 * the '*value' in the prefix tree 'node'.
1657 * '*checkbits' is set to the number of bits in the prefix mask necessary to
1658 * determine a mismatch, in case there are longer prefixes in the tree below
1659 * the one that matched.
1662 trie_lookup_value(const struct trie_node *node, const ovs_be32 value[],
1663 unsigned int *checkbits)
1665 unsigned int plen = 0, match_len = 0;
1666 const struct trie_node *prev = NULL;
1668 for (; node; prev = node, node = trie_next_node(node, value, plen)) {
1669 unsigned int eqbits;
1670 /* Check if this edge can be followed. */
1671 eqbits = prefix_equal_bits(node->prefix, node->nbits, value, plen);
1673 if (eqbits < node->nbits) { /* Mismatch, nothing more to be found. */
1674 /* Bit at offset 'plen' differed. */
1675 *checkbits = plen + 1; /* Includes the first mismatching bit. */
1678 /* Full match, check if rules exist at this prefix length. */
1679 if (node->n_rules > 0) {
1683 /* Dead end, exclude the other branch if it exists. */
1684 *checkbits = !prev || trie_is_leaf(prev) ? plen : plen + 1;
1689 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
1690 unsigned int *checkbits)
1692 const struct mf_field *mf = trie->field;
1694 /* Check that current flow matches the prerequisites for the trie
1695 * field. Some match fields are used for multiple purposes, so we
1696 * must check that the trie is relevant for this flow. */
1697 if (mf_are_prereqs_ok(mf, flow)) {
1698 return trie_lookup_value(trie->root,
1699 &((ovs_be32 *)flow)[mf->flow_be32ofs],
1702 *checkbits = 0; /* Value not used in this case. */
1706 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
1707 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
1708 * 'miniflow_index' is not NULL. */
1710 minimask_get_prefix_len(const struct minimask *minimask,
1711 const struct mf_field *mf)
1713 unsigned int nbits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
1714 uint8_t u32_ofs = mf->flow_be32ofs;
1715 uint8_t u32_end = u32_ofs + mf->n_bytes / 4;
1717 for (; u32_ofs < u32_end; ++u32_ofs) {
1719 mask = ntohl((OVS_FORCE ovs_be32)minimask_get(minimask, u32_ofs));
1721 /* Validate mask, count the mask length. */
1724 return 0; /* No bits allowed after mask ended. */
1727 if (~mask & (~mask + 1)) {
1728 return 0; /* Mask not contiguous. */
1730 mask_tz = ctz32(mask);
1731 nbits += 32 - mask_tz;
1739 * This is called only when mask prefix is known to be CIDR and non-zero.
1740 * Relies on the fact that the flow and mask have the same map, and since
1741 * the mask is CIDR, the storage for the flow field exists even if it
1742 * happened to be zeros.
1744 static const ovs_be32 *
1745 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
1747 return match->flow.values +
1748 count_1bits(match->flow.map & ((UINT64_C(1) << mf->flow_be32ofs) - 1));
1751 /* Insert rule in to the prefix tree.
1752 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1755 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1757 const ovs_be32 *prefix = minimatch_get_prefix(&rule->match, trie->field);
1758 struct trie_node *node;
1759 struct trie_node **edge;
1762 /* Walk the tree. */
1763 for (edge = &trie->root;
1764 (node = *edge) != NULL;
1765 edge = trie_next_edge(node, prefix, ofs)) {
1766 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1768 if (eqbits < node->nbits) {
1769 /* Mismatch, new node needs to be inserted above. */
1770 int old_branch = get_bit_at(node->prefix, eqbits);
1772 /* New parent node. */
1773 *edge = trie_branch_create(prefix, ofs - eqbits, eqbits,
1774 ofs == mlen ? 1 : 0);
1776 /* Adjust old node for its new position in the tree. */
1777 node->prefix <<= eqbits;
1778 node->nbits -= eqbits;
1779 (*edge)->edges[old_branch] = node;
1781 /* Check if need a new branch for the new rule. */
1783 (*edge)->edges[!old_branch]
1784 = trie_branch_create(prefix, ofs, mlen - ofs, 1);
1788 /* Full match so far. */
1791 /* Full match at the current node, rule needs to be added here. */
1796 /* Must insert a new tree branch for the new rule. */
1797 *edge = trie_branch_create(prefix, ofs, mlen - ofs, 1);
1800 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1803 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1805 const ovs_be32 *prefix = minimatch_get_prefix(&rule->match, trie->field);
1806 struct trie_node *node;
1807 struct trie_node **edges[sizeof(union mf_value) * 8];
1808 int depth = 0, ofs = 0;
1810 /* Walk the tree. */
1811 for (edges[depth] = &trie->root;
1812 (node = *edges[depth]) != NULL;
1813 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
1814 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1815 if (eqbits < node->nbits) {
1816 /* Mismatch, nothing to be removed. This should never happen, as
1817 * only rules in the classifier are ever removed. */
1818 break; /* Log a warning. */
1820 /* Full match so far. */
1824 /* Full prefix match at the current node, remove rule here. */
1825 if (!node->n_rules) {
1826 break; /* Log a warning. */
1830 /* Check if can prune the tree. */
1831 while (!node->n_rules && !(node->edges[0] && node->edges[1])) {
1832 /* No rules and at most one child node, remove this node. */
1833 struct trie_node *next;
1834 next = node->edges[0] ? node->edges[0] : node->edges[1];
1837 if (node->nbits + next->nbits > TRIE_PREFIX_BITS) {
1838 break; /* Cannot combine. */
1840 /* Combine node with next. */
1841 next->prefix = node->prefix | next->prefix >> node->nbits;
1842 next->nbits += node->nbits;
1844 trie_node_destroy(node);
1845 /* Update the parent's edge. */
1846 *edges[depth] = next;
1847 if (next || !depth) {
1848 /* Branch not pruned or at root, nothing more to do. */
1851 node = *edges[--depth];
1856 /* Cannot go deeper. This should never happen, since only rules
1857 * that actually exist in the classifier are ever removed. */
1858 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");