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);
35 /* Prefix trie for a 'field' */
37 const struct mf_field *field; /* Trie field, or NULL. */
38 struct trie_node *root; /* NULL if none. */
41 struct cls_classifier {
42 int n_rules; /* Total number of rules. */
43 uint8_t n_flow_segments;
44 uint8_t flow_segments[CLS_MAX_INDICES]; /* Flow segment boundaries to use
45 * for staged lookup. */
46 struct hmap subtables; /* Contains "struct cls_subtable"s. */
47 struct list subtables_priority; /* Subtables in descending priority order.
49 struct hmap partitions; /* Contains "struct cls_partition"s. */
50 struct cls_trie tries[CLS_MAX_TRIES]; /* Prefix tries. */
54 /* A set of rules that all have the same fields wildcarded. */
56 struct hmap_node hmap_node; /* Within struct cls_classifier 'subtables'
58 struct list list_node; /* Within classifier 'subtables_priority' list.
60 struct hmap rules; /* Contains "struct cls_rule"s. */
61 struct minimask mask; /* Wildcards for fields. */
62 int n_rules; /* Number of rules, including duplicates. */
63 unsigned int max_priority; /* Max priority of any rule in the subtable. */
64 unsigned int max_count; /* Count of max_priority rules. */
65 tag_type tag; /* Tag generated from mask for partitioning. */
66 uint8_t n_indices; /* How many indices to use. */
67 uint8_t index_ofs[CLS_MAX_INDICES]; /* u32 flow segment boundaries. */
68 struct hindex indices[CLS_MAX_INDICES]; /* Staged lookup indices. */
69 unsigned int trie_plen[CLS_MAX_TRIES]; /* Trie prefix length in 'mask'. */
72 /* Associates a metadata value (that is, a value of the OpenFlow 1.1+ metadata
73 * field) with tags for the "cls_subtable"s that contain rules that match that
75 struct cls_partition {
76 struct hmap_node hmap_node; /* In struct cls_classifier's 'partitions'
78 ovs_be64 metadata; /* metadata value for this partition. */
79 tag_type tags; /* OR of each flow's cls_subtable tag. */
80 struct tag_tracker tracker; /* Tracks the bits in 'tags'. */
86 static struct cls_subtable *find_subtable(const struct cls_classifier *,
87 const struct minimask *);
88 static struct cls_subtable *insert_subtable(struct cls_classifier *,
89 const struct minimask *);
91 static void destroy_subtable(struct cls_classifier *, struct cls_subtable *);
93 static void update_subtables_after_insertion(struct cls_classifier *,
94 struct cls_subtable *,
95 unsigned int new_priority);
96 static void update_subtables_after_removal(struct cls_classifier *,
97 struct cls_subtable *,
98 unsigned int del_priority);
100 static struct cls_rule *find_match_wc(const struct cls_subtable *,
101 const struct flow *, struct trie_ctx *,
102 unsigned int n_tries,
103 struct flow_wildcards *);
104 static struct cls_rule *find_equal(struct cls_subtable *,
105 const struct miniflow *, uint32_t hash);
106 static struct cls_rule *insert_rule(struct cls_classifier *,
107 struct cls_subtable *, struct cls_rule *);
109 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list. */
110 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD) \
111 for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
112 #define FOR_EACH_RULE_IN_LIST_SAFE(RULE, NEXT, HEAD) \
113 for ((RULE) = (HEAD); \
114 (RULE) != NULL && ((NEXT) = next_rule_in_list(RULE), true); \
117 static struct cls_rule *next_rule_in_list__(struct cls_rule *);
118 static struct cls_rule *next_rule_in_list(struct cls_rule *);
120 static unsigned int minimask_get_prefix_len(const struct minimask *,
121 const struct mf_field *);
122 static void trie_init(struct cls_classifier *, int trie_idx,
123 const struct mf_field *);
124 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
125 unsigned int *checkbits);
127 static void trie_destroy(struct trie_node *);
128 static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
129 static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
130 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
132 static bool mask_prefix_bits_set(const struct flow_wildcards *,
133 uint8_t be32ofs, unsigned int nbits);
135 /* flow/miniflow/minimask/minimatch utilities.
136 * These are only used by the classifier, so place them here to allow
137 * for better optimization. */
139 static inline uint64_t
140 miniflow_get_map_in_range(const struct miniflow *miniflow,
141 uint8_t start, uint8_t end, unsigned int *offset)
143 uint64_t map = miniflow->map;
147 uint64_t msk = (UINT64_C(1) << start) - 1; /* 'start' LSBs set */
148 *offset = count_1bits(map & msk);
151 if (end < FLOW_U32S) {
152 uint64_t msk = (UINT64_C(1) << end) - 1; /* 'end' LSBs set */
158 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
159 * 'mask', given 'basis'.
161 * The hash values returned by this function are the same as those returned by
162 * miniflow_hash_in_minimask(), only the form of the arguments differ. */
163 static inline uint32_t
164 flow_hash_in_minimask(const struct flow *flow, const struct minimask *mask,
167 const uint32_t *flow_u32 = (const uint32_t *)flow;
168 const uint32_t *p = mask->masks.values;
173 for (map = mask->masks.map; map; map = zero_rightmost_1bit(map)) {
174 hash = mhash_add(hash, flow_u32[raw_ctz(map)] & *p++);
177 return mhash_finish(hash, (p - mask->masks.values) * 4);
180 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
181 * 'mask', given 'basis'.
183 * The hash values returned by this function are the same as those returned by
184 * flow_hash_in_minimask(), only the form of the arguments differ. */
185 static inline uint32_t
186 miniflow_hash_in_minimask(const struct miniflow *flow,
187 const struct minimask *mask, uint32_t basis)
189 const uint32_t *p = mask->masks.values;
190 uint32_t hash = basis;
193 MINIFLOW_FOR_EACH_IN_MAP(flow_u32, flow, mask->masks.map) {
194 hash = mhash_add(hash, flow_u32 & *p++);
197 return mhash_finish(hash, (p - mask->masks.values) * 4);
200 /* Returns a hash value for the bits of range [start, end) in 'flow',
201 * where there are 1-bits in 'mask', given 'hash'.
203 * The hash values returned by this function are the same as those returned by
204 * minimatch_hash_range(), only the form of the arguments differ. */
205 static inline uint32_t
206 flow_hash_in_minimask_range(const struct flow *flow,
207 const struct minimask *mask,
208 uint8_t start, uint8_t end, uint32_t *basis)
210 const uint32_t *flow_u32 = (const uint32_t *)flow;
212 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
214 const uint32_t *p = mask->masks.values + offset;
215 uint32_t hash = *basis;
217 for (; map; map = zero_rightmost_1bit(map)) {
218 hash = mhash_add(hash, flow_u32[raw_ctz(map)] & *p++);
221 *basis = hash; /* Allow continuation from the unfinished value. */
222 return mhash_finish(hash, (p - mask->masks.values) * 4);
225 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask. */
227 flow_wildcards_fold_minimask(struct flow_wildcards *wc,
228 const struct minimask *mask)
230 flow_union_with_miniflow(&wc->masks, &mask->masks);
233 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask
234 * in range [start, end). */
236 flow_wildcards_fold_minimask_range(struct flow_wildcards *wc,
237 const struct minimask *mask,
238 uint8_t start, uint8_t end)
240 uint32_t *dst_u32 = (uint32_t *)&wc->masks;
242 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
244 const uint32_t *p = mask->masks.values + offset;
246 for (; map; map = zero_rightmost_1bit(map)) {
247 dst_u32[raw_ctz(map)] |= *p++;
251 /* Returns a hash value for 'flow', given 'basis'. */
252 static inline uint32_t
253 miniflow_hash(const struct miniflow *flow, uint32_t basis)
255 const uint32_t *p = flow->values;
256 uint32_t hash = basis;
257 uint64_t hash_map = 0;
260 for (map = flow->map; map; map = zero_rightmost_1bit(map)) {
262 hash = mhash_add(hash, *p);
263 hash_map |= rightmost_1bit(map);
267 hash = mhash_add(hash, hash_map);
268 hash = mhash_add(hash, hash_map >> 32);
270 return mhash_finish(hash, p - flow->values);
273 /* Returns a hash value for 'mask', given 'basis'. */
274 static inline uint32_t
275 minimask_hash(const struct minimask *mask, uint32_t basis)
277 return miniflow_hash(&mask->masks, basis);
280 /* Returns a hash value for 'match', given 'basis'. */
281 static inline uint32_t
282 minimatch_hash(const struct minimatch *match, uint32_t basis)
284 return miniflow_hash(&match->flow, minimask_hash(&match->mask, basis));
287 /* Returns a hash value for the bits of range [start, end) in 'minimatch',
290 * The hash values returned by this function are the same as those returned by
291 * flow_hash_in_minimask_range(), only the form of the arguments differ. */
292 static inline uint32_t
293 minimatch_hash_range(const struct minimatch *match, uint8_t start, uint8_t end,
297 const uint32_t *p, *q;
298 uint32_t hash = *basis;
301 n = count_1bits(miniflow_get_map_in_range(&match->mask.masks, start, end,
303 q = match->mask.masks.values + offset;
304 p = match->flow.values + offset;
306 for (i = 0; i < n; i++) {
307 hash = mhash_add(hash, p[i] & q[i]);
309 *basis = hash; /* Allow continuation from the unfinished value. */
310 return mhash_finish(hash, (offset + n) * 4);
316 /* Initializes 'rule' to match packets specified by 'match' at the given
317 * 'priority'. 'match' must satisfy the invariant described in the comment at
318 * the definition of struct match.
320 * The caller must eventually destroy 'rule' with cls_rule_destroy().
322 * (OpenFlow uses priorities between 0 and UINT16_MAX, inclusive, but
323 * internally Open vSwitch supports a wider range.) */
325 cls_rule_init(struct cls_rule *rule,
326 const struct match *match, unsigned int priority)
328 minimatch_init(&rule->match, match);
329 rule->priority = priority;
332 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
334 cls_rule_init_from_minimatch(struct cls_rule *rule,
335 const struct minimatch *match,
336 unsigned int priority)
338 minimatch_clone(&rule->match, match);
339 rule->priority = priority;
342 /* Initializes 'dst' as a copy of 'src'.
344 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
346 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
348 minimatch_clone(&dst->match, &src->match);
349 dst->priority = src->priority;
352 /* Initializes 'dst' with the data in 'src', destroying 'src'.
354 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
356 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
358 minimatch_move(&dst->match, &src->match);
359 dst->priority = src->priority;
362 /* Frees memory referenced by 'rule'. Doesn't free 'rule' itself (it's
363 * normally embedded into a larger structure).
365 * ('rule' must not currently be in a classifier.) */
367 cls_rule_destroy(struct cls_rule *rule)
369 minimatch_destroy(&rule->match);
372 /* Returns true if 'a' and 'b' match the same packets at the same priority,
373 * false if they differ in some way. */
375 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
377 return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
380 /* Returns a hash value for 'rule', folding in 'basis'. */
382 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
384 return minimatch_hash(&rule->match, hash_int(rule->priority, basis));
387 /* Appends a string describing 'rule' to 's'. */
389 cls_rule_format(const struct cls_rule *rule, struct ds *s)
391 minimatch_format(&rule->match, s, rule->priority);
394 /* Returns true if 'rule' matches every packet, false otherwise. */
396 cls_rule_is_catchall(const struct cls_rule *rule)
398 return minimask_is_catchall(&rule->match.mask);
401 /* Initializes 'cls' as a classifier that initially contains no classification
404 classifier_init(struct classifier *cls_, const uint8_t *flow_segments)
406 struct cls_classifier *cls = xmalloc(sizeof *cls);
408 fat_rwlock_init(&cls_->rwlock);
413 hmap_init(&cls->subtables);
414 list_init(&cls->subtables_priority);
415 hmap_init(&cls->partitions);
416 cls->n_flow_segments = 0;
418 while (cls->n_flow_segments < CLS_MAX_INDICES
419 && *flow_segments < FLOW_U32S) {
420 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
426 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
427 * caller's responsibility. */
429 classifier_destroy(struct classifier *cls_)
432 struct cls_classifier *cls = cls_->cls;
433 struct cls_subtable *partition, *next_partition;
434 struct cls_subtable *subtable, *next_subtable;
437 fat_rwlock_destroy(&cls_->rwlock);
442 for (i = 0; i < cls->n_tries; i++) {
443 trie_destroy(cls->tries[i].root);
446 HMAP_FOR_EACH_SAFE (subtable, next_subtable, hmap_node,
448 destroy_subtable(cls, subtable);
450 hmap_destroy(&cls->subtables);
452 HMAP_FOR_EACH_SAFE (partition, next_partition, hmap_node,
454 hmap_remove(&cls->partitions, &partition->hmap_node);
457 hmap_destroy(&cls->partitions);
463 /* We use uint64_t as a set for the fields below. */
464 BUILD_ASSERT_DECL(MFF_N_IDS <= 64);
466 /* Set the fields for which prefix lookup should be performed. */
468 classifier_set_prefix_fields(struct classifier *cls_,
469 const enum mf_field_id *trie_fields,
470 unsigned int n_fields)
472 struct cls_classifier *cls = cls_->cls;
476 for (i = 0, trie = 0; i < n_fields && trie < CLS_MAX_TRIES; i++) {
477 const struct mf_field *field = mf_from_id(trie_fields[i]);
478 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
479 /* Incompatible field. This is the only place where we
480 * enforce these requirements, but the rest of the trie code
481 * depends on the flow_be32ofs to be non-negative and the
482 * field length to be a multiple of 32 bits. */
486 if (fields & (UINT64_C(1) << trie_fields[i])) {
487 /* Duplicate field, there is no need to build more than
488 * one index for any one field. */
491 fields |= UINT64_C(1) << trie_fields[i];
493 if (trie >= cls->n_tries || field != cls->tries[trie].field) {
494 trie_init(cls, trie, field);
499 /* Destroy the rest. */
500 for (i = trie; i < cls->n_tries; i++) {
501 trie_init(cls, i, NULL);
507 trie_init(struct cls_classifier *cls, int trie_idx,
508 const struct mf_field *field)
510 struct cls_trie *trie = &cls->tries[trie_idx];
511 struct cls_subtable *subtable;
513 if (trie_idx < cls->n_tries) {
514 trie_destroy(trie->root);
519 /* Add existing rules to the trie. */
520 LIST_FOR_EACH (subtable, list_node, &cls->subtables_priority) {
523 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
524 /* Initialize subtable's prefix length on this field. */
525 subtable->trie_plen[trie_idx] = plen;
528 struct cls_rule *head;
530 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
531 struct cls_rule *rule;
533 FOR_EACH_RULE_IN_LIST (rule, head) {
534 trie_insert(trie, rule, plen);
541 /* Returns true if 'cls' contains no classification rules, false otherwise. */
543 classifier_is_empty(const struct classifier *cls)
545 return cls->cls->n_rules == 0;
548 /* Returns the number of rules in 'cls'. */
550 classifier_count(const struct classifier *cls)
552 return cls->cls->n_rules;
556 hash_metadata(ovs_be64 metadata_)
558 uint64_t metadata = (OVS_FORCE uint64_t) metadata_;
559 return hash_uint64(metadata);
562 static struct cls_partition *
563 find_partition(const struct cls_classifier *cls, ovs_be64 metadata,
566 struct cls_partition *partition;
568 HMAP_FOR_EACH_IN_BUCKET (partition, hmap_node, hash, &cls->partitions) {
569 if (partition->metadata == metadata) {
577 static struct cls_partition *
578 create_partition(struct cls_classifier *cls, struct cls_subtable *subtable,
581 uint32_t hash = hash_metadata(metadata);
582 struct cls_partition *partition = find_partition(cls, metadata, hash);
584 partition = xmalloc(sizeof *partition);
585 partition->metadata = metadata;
587 tag_tracker_init(&partition->tracker);
588 hmap_insert(&cls->partitions, &partition->hmap_node, hash);
590 tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
594 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
595 * must not modify or free it.
597 * If 'cls' already contains an identical rule (including wildcards, values of
598 * fixed fields, and priority), replaces the old rule by 'rule' and returns the
599 * rule that was replaced. The caller takes ownership of the returned rule and
600 * is thus responsible for destroying it with cls_rule_destroy(), freeing the
601 * memory block in which it resides, etc., as necessary.
603 * Returns NULL if 'cls' does not contain a rule with an identical key, after
604 * inserting the new rule. In this case, no rules are displaced by the new
605 * rule, even rules that cannot have any effect because the new rule matches a
606 * superset of their flows and has higher priority. */
608 classifier_replace(struct classifier *cls_, struct cls_rule *rule)
610 struct cls_classifier *cls = cls_->cls;
611 struct cls_rule *old_rule;
612 struct cls_subtable *subtable;
614 subtable = find_subtable(cls, &rule->match.mask);
616 subtable = insert_subtable(cls, &rule->match.mask);
619 old_rule = insert_rule(cls, subtable, rule);
623 if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
624 ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
625 rule->partition = create_partition(cls, subtable, metadata);
627 rule->partition = NULL;
633 for (i = 0; i < cls->n_tries; i++) {
634 if (subtable->trie_plen[i]) {
635 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
639 rule->partition = old_rule->partition;
644 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
645 * must not modify or free it.
647 * 'cls' must not contain an identical rule (including wildcards, values of
648 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
651 classifier_insert(struct classifier *cls, struct cls_rule *rule)
653 struct cls_rule *displaced_rule = classifier_replace(cls, rule);
654 ovs_assert(!displaced_rule);
657 /* Removes 'rule' from 'cls'. It is the caller's responsibility to destroy
658 * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
659 * resides, etc., as necessary. */
661 classifier_remove(struct classifier *cls_, struct cls_rule *rule)
663 struct cls_classifier *cls = cls_->cls;
664 struct cls_partition *partition;
665 struct cls_rule *head;
666 struct cls_subtable *subtable;
669 subtable = find_subtable(cls, &rule->match.mask);
671 for (i = 0; i < cls->n_tries; i++) {
672 if (subtable->trie_plen[i]) {
673 trie_remove(&cls->tries[i], rule, subtable->trie_plen[i]);
677 /* Remove rule node from indices. */
678 for (i = 0; i < subtable->n_indices; i++) {
679 hindex_remove(&subtable->indices[i], &rule->index_nodes[i]);
682 head = find_equal(subtable, &rule->match.flow, rule->hmap_node.hash);
684 list_remove(&rule->list);
685 } else if (list_is_empty(&rule->list)) {
686 hmap_remove(&subtable->rules, &rule->hmap_node);
688 struct cls_rule *next = CONTAINER_OF(rule->list.next,
689 struct cls_rule, list);
691 list_remove(&rule->list);
692 hmap_replace(&subtable->rules, &rule->hmap_node, &next->hmap_node);
695 partition = rule->partition;
697 tag_tracker_subtract(&partition->tracker, &partition->tags,
699 if (!partition->tags) {
700 hmap_remove(&cls->partitions, &partition->hmap_node);
705 if (--subtable->n_rules == 0) {
706 destroy_subtable(cls, subtable);
708 update_subtables_after_removal(cls, subtable, rule->priority);
714 /* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
715 * subtables which have more than 'match_plen' bits in their corresponding
716 * field at offset 'be32ofs'. If skipped, 'maskbits' prefix bits should be
717 * unwildcarded to quarantee datapath flow matches only packets it should. */
719 const struct cls_trie *trie;
720 bool lookup_done; /* Status of the lookup. */
721 uint8_t be32ofs; /* U32 offset of the field in question. */
722 unsigned int match_plen; /* Longest prefix than could possibly match. */
723 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
727 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
730 ctx->be32ofs = trie->field->flow_be32ofs;
731 ctx->lookup_done = false;
734 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
735 * Returns a null pointer if no rules in 'cls' match 'flow'. If multiple rules
736 * of equal priority match 'flow', returns one arbitrarily.
738 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
739 * set of bits that were significant in the lookup. At some point
740 * earlier, 'wc' should have been initialized (e.g., by
741 * flow_wildcards_init_catchall()). */
743 classifier_lookup(const struct classifier *cls_, const struct flow *flow,
744 struct flow_wildcards *wc)
746 struct cls_classifier *cls = cls_->cls;
747 const struct cls_partition *partition;
748 struct cls_subtable *subtable;
749 struct cls_rule *best;
751 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
754 /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
755 * then 'flow' cannot possibly match in 'subtable':
757 * - If flow->metadata maps to a given 'partition', then we can use
758 * 'tags' for 'partition->tags'.
760 * - If flow->metadata has no partition, then no rule in 'cls' has an
761 * exact-match for flow->metadata. That means that we don't need to
762 * search any subtable that includes flow->metadata in its mask.
764 * In either case, we always need to search any cls_subtables that do not
765 * include flow->metadata in its mask. One way to do that would be to
766 * check the "cls_subtable"s explicitly for that, but that would require an
767 * extra branch per subtable. Instead, we mark such a cls_subtable's
768 * 'tags' as TAG_ALL and make sure that 'tags' is never empty. This means
769 * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
770 * need a special case.
772 partition = (hmap_is_empty(&cls->partitions)
774 : find_partition(cls, flow->metadata,
775 hash_metadata(flow->metadata)));
776 tags = partition ? partition->tags : TAG_ARBITRARY;
778 /* Initialize trie contexts for match_find_wc(). */
779 for (i = 0; i < cls->n_tries; i++) {
780 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
783 LIST_FOR_EACH (subtable, list_node, &cls->subtables_priority) {
784 struct cls_rule *rule;
786 if (!tag_intersects(tags, subtable->tag)) {
790 rule = find_match_wc(subtable, flow, trie_ctx, cls->n_tries, wc);
793 LIST_FOR_EACH_CONTINUE (subtable, list_node,
794 &cls->subtables_priority) {
795 if (subtable->max_priority <= best->priority) {
796 /* Subtables are in descending priority order,
797 * can not find anything better. */
800 if (!tag_intersects(tags, subtable->tag)) {
804 rule = find_match_wc(subtable, flow, trie_ctx, cls->n_tries,
806 if (rule && rule->priority > best->priority) {
817 /* Returns true if 'target' satisifies 'match', that is, if each bit for which
818 * 'match' specifies a particular value has the correct value in 'target'. */
820 minimatch_matches_miniflow(const struct minimatch *match,
821 const struct miniflow *target)
823 const uint32_t *flowp = (const uint32_t *)match->flow.values;
824 const uint32_t *maskp = (const uint32_t *)match->mask.masks.values;
827 MINIFLOW_FOR_EACH_IN_MAP(target_u32, target, match->mask.masks.map) {
828 if ((*flowp++ ^ target_u32) & *maskp++) {
836 static inline struct cls_rule *
837 find_match_miniflow(const struct cls_subtable *subtable,
838 const struct miniflow *flow,
841 struct cls_rule *rule;
843 HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &subtable->rules) {
844 if (minimatch_matches_miniflow(&rule->match, flow)) {
852 /* Finds and returns the highest-priority rule in 'cls' that matches
853 * 'miniflow'. Returns a null pointer if no rules in 'cls' match 'flow'.
854 * If multiple rules of equal priority match 'flow', returns one arbitrarily.
856 * This function is optimized for the userspace datapath, which only ever has
857 * one priority value for it's flows!
859 struct cls_rule *classifier_lookup_miniflow_first(const struct classifier *cls_,
860 const struct miniflow *flow)
862 struct cls_classifier *cls = cls_->cls;
863 struct cls_subtable *subtable;
865 LIST_FOR_EACH (subtable, list_node, &cls->subtables_priority) {
866 struct cls_rule *rule;
868 rule = find_match_miniflow(subtable, flow,
869 miniflow_hash_in_minimask(flow,
880 /* Finds and returns a rule in 'cls' with exactly the same priority and
881 * matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
882 * contain an exact match. */
884 classifier_find_rule_exactly(const struct classifier *cls_,
885 const struct cls_rule *target)
887 struct cls_classifier *cls = cls_->cls;
888 struct cls_rule *head, *rule;
889 struct cls_subtable *subtable;
891 subtable = find_subtable(cls, &target->match.mask);
896 /* Skip if there is no hope. */
897 if (target->priority > subtable->max_priority) {
901 head = find_equal(subtable, &target->match.flow,
902 miniflow_hash_in_minimask(&target->match.flow,
903 &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 : 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. */
916 classifier_find_match_exactly(const struct classifier *cls,
917 const struct match *target,
918 unsigned int priority)
920 struct cls_rule *retval;
923 cls_rule_init(&cr, target, priority);
924 retval = classifier_find_rule_exactly(cls, &cr);
925 cls_rule_destroy(&cr);
930 /* Checks if 'target' would overlap any other rule in 'cls'. Two rules are
931 * considered to overlap if both rules have the same priority and a packet
932 * could match both. */
934 classifier_rule_overlaps(const struct classifier *cls_,
935 const struct cls_rule *target)
937 struct cls_classifier *cls = cls_->cls;
938 struct cls_subtable *subtable;
940 /* Iterate subtables in the descending max priority order. */
941 LIST_FOR_EACH (subtable, list_node, &cls->subtables_priority) {
942 uint32_t storage[FLOW_U32S];
943 struct minimask mask;
944 struct cls_rule *head;
946 if (target->priority > subtable->max_priority) {
947 break; /* Can skip this and the rest of the subtables. */
950 minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
951 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
952 struct cls_rule *rule;
954 FOR_EACH_RULE_IN_LIST (rule, head) {
955 if (rule->priority < target->priority) {
956 break; /* Rules in descending priority order. */
958 if (rule->priority == target->priority
959 && miniflow_equal_in_minimask(&target->match.flow,
960 &rule->match.flow, &mask)) {
970 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
971 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
972 * function returns true if, for every field:
974 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
977 * - 'criteria' wildcards the field,
979 * Conversely, 'rule' does not match 'criteria' and this function returns false
980 * if, for at least one field:
982 * - 'criteria' and 'rule' specify different values for the field, or
984 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
986 * Equivalently, the truth table for whether a field matches is:
991 * r +---------+---------+
992 * i wild | yes | yes |
994 * e +---------+---------+
995 * r exact | no |if values|
997 * a +---------+---------+
999 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
1000 * commands and by OpenFlow 1.0 aggregate and flow stats.
1002 * Ignores rule->priority. */
1004 cls_rule_is_loose_match(const struct cls_rule *rule,
1005 const struct minimatch *criteria)
1007 return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
1008 && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
1015 rule_matches(const struct cls_rule *rule, const struct cls_rule *target)
1018 || miniflow_equal_in_minimask(&rule->match.flow,
1019 &target->match.flow,
1020 &target->match.mask));
1023 static struct cls_rule *
1024 search_subtable(const struct cls_subtable *subtable,
1025 const struct cls_rule *target)
1027 if (!target || !minimask_has_extra(&subtable->mask, &target->match.mask)) {
1028 struct cls_rule *rule;
1030 HMAP_FOR_EACH (rule, hmap_node, &subtable->rules) {
1031 if (rule_matches(rule, target)) {
1039 /* Initializes 'cursor' for iterating through rules in 'cls':
1041 * - If 'target' is null, the cursor will visit every rule in 'cls'.
1043 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1044 * such that cls_rule_is_loose_match(rule, target) returns true.
1046 * Ignores target->priority. */
1048 cls_cursor_init(struct cls_cursor *cursor, const struct classifier *cls,
1049 const struct cls_rule *target)
1051 cursor->cls = cls->cls;
1052 cursor->target = target && !cls_rule_is_catchall(target) ? target : NULL;
1055 /* Returns the first matching cls_rule in 'cursor''s iteration, or a null
1056 * pointer if there are no matches. */
1058 cls_cursor_first(struct cls_cursor *cursor)
1060 struct cls_subtable *subtable;
1062 HMAP_FOR_EACH (subtable, hmap_node, &cursor->cls->subtables) {
1063 struct cls_rule *rule = search_subtable(subtable, cursor->target);
1065 cursor->subtable = subtable;
1073 /* Returns the next matching cls_rule in 'cursor''s iteration, or a null
1074 * pointer if there are no more matches. */
1076 cls_cursor_next(struct cls_cursor *cursor, const struct cls_rule *rule_)
1078 struct cls_rule *rule = CONST_CAST(struct cls_rule *, rule_);
1079 const struct cls_subtable *subtable;
1080 struct cls_rule *next;
1082 next = next_rule_in_list__(rule);
1083 if (next->priority < rule->priority) {
1087 /* 'next' is the head of the list, that is, the rule that is included in
1088 * the subtable's hmap. (This is important when the classifier contains
1089 * rules that differ only in priority.) */
1091 HMAP_FOR_EACH_CONTINUE (rule, hmap_node, &cursor->subtable->rules) {
1092 if (rule_matches(rule, cursor->target)) {
1097 subtable = cursor->subtable;
1098 HMAP_FOR_EACH_CONTINUE (subtable, hmap_node, &cursor->cls->subtables) {
1099 rule = search_subtable(subtable, cursor->target);
1101 cursor->subtable = subtable;
1109 static struct cls_subtable *
1110 find_subtable(const struct cls_classifier *cls, const struct minimask *mask)
1112 struct cls_subtable *subtable;
1114 HMAP_FOR_EACH_IN_BUCKET (subtable, hmap_node, minimask_hash(mask, 0),
1116 if (minimask_equal(mask, &subtable->mask)) {
1123 static struct cls_subtable *
1124 insert_subtable(struct cls_classifier *cls, const struct minimask *mask)
1126 uint32_t hash = minimask_hash(mask, 0);
1127 struct cls_subtable *subtable;
1129 struct flow_wildcards old, new;
1132 subtable = xzalloc(sizeof *subtable);
1133 hmap_init(&subtable->rules);
1134 minimask_clone(&subtable->mask, mask);
1136 /* Init indices for segmented lookup, if any. */
1137 flow_wildcards_init_catchall(&new);
1140 for (i = 0; i < cls->n_flow_segments; i++) {
1141 flow_wildcards_fold_minimask_range(&new, mask, prev,
1142 cls->flow_segments[i]);
1143 /* Add an index if it adds mask bits. */
1144 if (!flow_wildcards_equal(&new, &old)) {
1145 hindex_init(&subtable->indices[index]);
1146 subtable->index_ofs[index] = cls->flow_segments[i];
1150 prev = cls->flow_segments[i];
1152 /* Check if the rest of the subtable's mask adds any bits,
1153 * and remove the last index if it doesn't. */
1155 flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U32S);
1156 if (flow_wildcards_equal(&new, &old)) {
1158 subtable->index_ofs[index] = 0;
1159 hindex_destroy(&subtable->indices[index]);
1162 subtable->n_indices = index;
1164 hmap_insert(&cls->subtables, &subtable->hmap_node, hash);
1165 list_push_back(&cls->subtables_priority, &subtable->list_node);
1166 subtable->tag = (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1167 ? tag_create_deterministic(hash)
1170 for (i = 0; i < cls->n_tries; i++) {
1171 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1172 cls->tries[i].field);
1179 destroy_subtable(struct cls_classifier *cls, struct cls_subtable *subtable)
1183 for (i = 0; i < subtable->n_indices; i++) {
1184 hindex_destroy(&subtable->indices[i]);
1186 minimask_destroy(&subtable->mask);
1187 hmap_remove(&cls->subtables, &subtable->hmap_node);
1188 hmap_destroy(&subtable->rules);
1189 list_remove(&subtable->list_node);
1193 /* This function performs the following updates for 'subtable' in 'cls'
1194 * following the addition of a new rule with priority 'new_priority' to
1197 * - Update 'subtable->max_priority' and 'subtable->max_count' if necessary.
1199 * - Update 'subtable''s position in 'cls->subtables_priority' if necessary.
1201 * This function should only be called after adding a new rule, not after
1202 * replacing a rule by an identical one or modifying a rule in-place. */
1204 update_subtables_after_insertion(struct cls_classifier *cls,
1205 struct cls_subtable *subtable,
1206 unsigned int new_priority)
1208 if (new_priority == subtable->max_priority) {
1209 ++subtable->max_count;
1210 } else if (new_priority > subtable->max_priority) {
1211 struct cls_subtable *iter;
1213 subtable->max_priority = new_priority;
1214 subtable->max_count = 1;
1216 /* Possibly move 'subtable' earlier in the priority list. If we break
1217 * out of the loop, then 'subtable' should be moved just after that
1218 * 'iter'. If the loop terminates normally, then 'iter' will be the
1219 * list head and we'll move subtable just after that (e.g. to the front
1222 LIST_FOR_EACH_REVERSE_CONTINUE (iter, list_node,
1223 &cls->subtables_priority) {
1224 if (iter->max_priority >= subtable->max_priority) {
1229 /* Move 'subtable' just after 'iter' (unless it's already there). */
1230 if (iter->list_node.next != &subtable->list_node) {
1231 list_splice(iter->list_node.next,
1232 &subtable->list_node, subtable->list_node.next);
1237 /* This function performs the following updates for 'subtable' in 'cls'
1238 * following the deletion of a rule with priority 'del_priority' from
1241 * - Update 'subtable->max_priority' and 'subtable->max_count' if necessary.
1243 * - Update 'subtable''s position in 'cls->subtables_priority' if necessary.
1245 * This function should only be called after removing a rule, not after
1246 * replacing a rule by an identical one or modifying a rule in-place. */
1248 update_subtables_after_removal(struct cls_classifier *cls,
1249 struct cls_subtable *subtable,
1250 unsigned int del_priority)
1252 struct cls_subtable *iter;
1254 if (del_priority == subtable->max_priority && --subtable->max_count == 0) {
1255 struct cls_rule *head;
1257 subtable->max_priority = 0;
1258 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
1259 if (head->priority > subtable->max_priority) {
1260 subtable->max_priority = head->priority;
1261 subtable->max_count = 1;
1262 } else if (head->priority == subtable->max_priority) {
1263 ++subtable->max_count;
1267 /* Possibly move 'subtable' later in the priority list. If we break
1268 * out of the loop, then 'subtable' should be moved just before that
1269 * 'iter'. If the loop terminates normally, then 'iter' will be the
1270 * list head and we'll move subtable just before that (e.g. to the back
1273 LIST_FOR_EACH_CONTINUE (iter, list_node, &cls->subtables_priority) {
1274 if (iter->max_priority <= subtable->max_priority) {
1279 /* Move 'subtable' just before 'iter' (unless it's already there). */
1280 if (iter->list_node.prev != &subtable->list_node) {
1281 list_splice(&iter->list_node,
1282 &subtable->list_node, subtable->list_node.next);
1292 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1293 * lookup results. */
1295 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1296 const unsigned int field_plen[CLS_MAX_TRIES],
1297 const struct range ofs, const struct flow *flow,
1298 struct flow_wildcards *wc)
1302 /* Check if we could avoid fully unwildcarding the next level of
1303 * fields using the prefix tries. The trie checks are done only as
1304 * needed to avoid folding in additional bits to the wildcards mask. */
1305 for (j = 0; j < n_tries; j++) {
1306 /* Is the trie field relevant for this subtable? */
1307 if (field_plen[j]) {
1308 struct trie_ctx *ctx = &trie_ctx[j];
1309 uint8_t be32ofs = ctx->be32ofs;
1311 /* Is the trie field within the current range of fields? */
1312 if (be32ofs >= ofs.start && be32ofs < ofs.end) {
1313 /* On-demand trie lookup. */
1314 if (!ctx->lookup_done) {
1315 ctx->match_plen = trie_lookup(ctx->trie, flow,
1317 ctx->lookup_done = true;
1319 /* Possible to skip the rest of the subtable if subtable's
1320 * prefix on the field is longer than what is known to match
1321 * based on the trie lookup. */
1322 if (field_plen[j] > ctx->match_plen) {
1323 /* RFC: We want the trie lookup to never result in
1324 * unwildcarding any bits that would not be unwildcarded
1325 * otherwise. Since the trie is shared by the whole
1326 * classifier, it is possible that the 'maskbits' contain
1327 * bits that are irrelevant for the partition of the
1328 * classifier relevant for the current flow. */
1330 /* Can skip if the field is already unwildcarded. */
1331 if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1334 /* Check that the trie result will not unwildcard more bits
1335 * than this stage will. */
1336 if (ctx->maskbits <= field_plen[j]) {
1337 /* Unwildcard the bits and skip the rest. */
1338 mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1339 /* Note: Prerequisite already unwildcarded, as the only
1340 * prerequisite of the supported trie lookup fields is
1341 * the ethertype, which is currently always
1353 static inline struct cls_rule *
1354 find_match(const struct cls_subtable *subtable, const struct flow *flow,
1357 struct cls_rule *rule;
1359 HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &subtable->rules) {
1360 if (minimatch_matches_flow(&rule->match, flow)) {
1368 static struct cls_rule *
1369 find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
1370 struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1371 struct flow_wildcards *wc)
1373 uint32_t basis = 0, hash;
1374 struct cls_rule *rule = NULL;
1379 return find_match(subtable, flow,
1380 flow_hash_in_minimask(flow, &subtable->mask, 0));
1384 /* Try to finish early by checking fields in segments. */
1385 for (i = 0; i < subtable->n_indices; i++) {
1386 struct hindex_node *inode;
1387 ofs.end = subtable->index_ofs[i];
1389 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1393 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1395 ofs.start = ofs.end;
1396 inode = hindex_node_with_hash(&subtable->indices[i], hash);
1398 /* No match, can stop immediately, but must fold in the mask
1399 * covered so far. */
1403 /* If we have narrowed down to a single rule already, check whether
1404 * that rule matches. If it does match, then we're done. If it does
1405 * not match, then we know that we will never get a match, but we do
1406 * not yet know how many wildcards we need to fold into 'wc' so we
1407 * continue iterating through indices to find that out. (We won't
1408 * waste time calling minimatch_matches_flow() again because we've set
1411 * This check shows a measurable benefit with non-trivial flow tables.
1413 * (Rare) hash collisions may cause us to miss the opportunity for this
1415 if (!inode->s && !rule) {
1416 ASSIGN_CONTAINER(rule, inode - i, index_nodes);
1417 if (minimatch_matches_flow(&rule->match, flow)) {
1422 ofs.end = FLOW_U32S;
1423 /* Trie check for the final range. */
1424 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1428 /* Multiple potential matches exist, look for one. */
1429 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1431 rule = find_match(subtable, flow, hash);
1433 /* We already narrowed the matching candidates down to just 'rule',
1434 * but it didn't match. */
1438 /* Must unwildcard all the fields, as they were looked at. */
1439 flow_wildcards_fold_minimask(wc, &subtable->mask);
1443 /* Must unwildcard the fields looked up so far, if any. */
1445 flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, ofs.start);
1450 static struct cls_rule *
1451 find_equal(struct cls_subtable *subtable, const struct miniflow *flow,
1454 struct cls_rule *head;
1456 HMAP_FOR_EACH_WITH_HASH (head, hmap_node, hash, &subtable->rules) {
1457 if (miniflow_equal(&head->match.flow, flow)) {
1464 static struct cls_rule *
1465 insert_rule(struct cls_classifier *cls, struct cls_subtable *subtable,
1466 struct cls_rule *new)
1468 struct cls_rule *head;
1469 struct cls_rule *old = NULL;
1471 uint32_t basis = 0, hash;
1472 uint8_t prev_be32ofs = 0;
1474 /* Add new node to segment indices. */
1475 for (i = 0; i < subtable->n_indices; i++) {
1476 hash = minimatch_hash_range(&new->match, prev_be32ofs,
1477 subtable->index_ofs[i], &basis);
1478 hindex_insert(&subtable->indices[i], &new->index_nodes[i], hash);
1479 prev_be32ofs = subtable->index_ofs[i];
1481 hash = minimatch_hash_range(&new->match, prev_be32ofs, FLOW_U32S, &basis);
1482 head = find_equal(subtable, &new->match.flow, hash);
1484 hmap_insert(&subtable->rules, &new->hmap_node, hash);
1485 list_init(&new->list);
1488 /* Scan the list for the insertion point that will keep the list in
1489 * order of decreasing priority. */
1490 struct cls_rule *rule;
1492 new->hmap_node.hash = hash; /* Otherwise done by hmap_insert. */
1494 FOR_EACH_RULE_IN_LIST (rule, head) {
1495 if (new->priority >= rule->priority) {
1497 /* 'new' is the new highest-priority flow in the list. */
1498 hmap_replace(&subtable->rules,
1499 &rule->hmap_node, &new->hmap_node);
1502 if (new->priority == rule->priority) {
1503 list_replace(&new->list, &rule->list);
1507 list_insert(&rule->list, &new->list);
1513 /* Insert 'new' at the end of the list. */
1514 list_push_back(&head->list, &new->list);
1519 update_subtables_after_insertion(cls, subtable, new->priority);
1521 /* Remove old node from indices. */
1522 for (i = 0; i < subtable->n_indices; i++) {
1523 hindex_remove(&subtable->indices[i], &old->index_nodes[i]);
1529 static struct cls_rule *
1530 next_rule_in_list__(struct cls_rule *rule)
1532 struct cls_rule *next = OBJECT_CONTAINING(rule->list.next, next, list);
1536 static struct cls_rule *
1537 next_rule_in_list(struct cls_rule *rule)
1539 struct cls_rule *next = next_rule_in_list__(rule);
1540 return next->priority < rule->priority ? next : NULL;
1543 /* A longest-prefix match tree. */
1545 uint32_t prefix; /* Prefix bits for this node, MSB first. */
1546 uint8_t nbits; /* Never zero, except for the root node. */
1547 unsigned int n_rules; /* Number of rules that have this prefix. */
1548 struct trie_node *edges[2]; /* Both NULL if leaf. */
1551 /* Max bits per node. Must fit in struct trie_node's 'prefix'.
1552 * Also tested with 16, 8, and 5 to stress the implementation. */
1553 #define TRIE_PREFIX_BITS 32
1555 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1556 * Prefixes are in the network byte order, and the offset 0 corresponds to
1557 * the most significant bit of the first byte. The offset can be read as
1558 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1560 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1564 pr += ofs / 32; /* Where to start. */
1565 ofs %= 32; /* How many bits to skip at 'pr'. */
1567 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1568 if (plen > 32 - ofs) { /* Need more than we have already? */
1569 prefix |= ntohl(*++pr) >> (32 - ofs);
1571 /* Return with possible unwanted bits at the end. */
1575 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1576 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1577 * corresponds to the most significant bit of the first byte. The offset can
1578 * be read as "how many bits to skip from the start of the prefix starting at
1581 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1586 if (plen > TRIE_PREFIX_BITS) {
1587 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1589 /* Return with unwanted bits cleared. */
1590 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1593 /* Return the number of equal bits in 'nbits' of 'prefix's MSBs and a 'value'
1594 * starting at "MSB 0"-based offset 'ofs'. */
1596 prefix_equal_bits(uint32_t prefix, unsigned int nbits, const ovs_be32 value[],
1599 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, nbits);
1600 /* Set the bit after the relevant bits to limit the result. */
1601 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - nbits));
1604 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1605 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1607 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1608 unsigned int ofs, unsigned int plen)
1610 return prefix_equal_bits(node->prefix, MIN(node->nbits, plen - ofs),
1614 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1615 * be greater than 31. */
1617 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1619 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1622 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1623 * be between 0 and 31, inclusive. */
1625 get_bit_at(const uint32_t prefix, unsigned int ofs)
1627 return (prefix >> (31 - ofs)) & 1u;
1630 /* Create new branch. */
1631 static struct trie_node *
1632 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1633 unsigned int n_rules)
1635 struct trie_node *node = xmalloc(sizeof *node);
1637 node->prefix = trie_get_prefix(prefix, ofs, plen);
1639 if (plen <= TRIE_PREFIX_BITS) {
1641 node->edges[0] = NULL;
1642 node->edges[1] = NULL;
1643 node->n_rules = n_rules;
1644 } else { /* Need intermediate nodes. */
1645 struct trie_node *subnode = trie_branch_create(prefix,
1646 ofs + TRIE_PREFIX_BITS,
1647 plen - TRIE_PREFIX_BITS,
1649 int bit = get_bit_at(subnode->prefix, 0);
1650 node->nbits = TRIE_PREFIX_BITS;
1651 node->edges[bit] = subnode;
1652 node->edges[!bit] = NULL;
1659 trie_node_destroy(struct trie_node *node)
1665 trie_destroy(struct trie_node *node)
1668 trie_destroy(node->edges[0]);
1669 trie_destroy(node->edges[1]);
1675 trie_is_leaf(const struct trie_node *trie)
1677 return !trie->edges[0] && !trie->edges[1]; /* No children. */
1681 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1684 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1687 for (i = 0; i < nbits / 32; i++) {
1688 mask[i] = OVS_BE32_MAX;
1691 mask[i] |= htonl(~0u << (32 - nbits % 32));
1696 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
1699 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1701 ovs_be32 zeroes = 0;
1703 for (i = 0; i < nbits / 32; i++) {
1707 zeroes |= ~mask[i] & htonl(~0u << (32 - nbits % 32));
1710 return !zeroes; /* All 'nbits' bits set. */
1713 static struct trie_node **
1714 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
1717 return node->edges + be_get_bit_at(value, ofs);
1720 static const struct trie_node *
1721 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
1724 return node->edges[be_get_bit_at(value, ofs)];
1727 /* Return the prefix mask length necessary to find the longest-prefix match for
1728 * the '*value' in the prefix tree 'node'.
1729 * '*checkbits' is set to the number of bits in the prefix mask necessary to
1730 * determine a mismatch, in case there are longer prefixes in the tree below
1731 * the one that matched.
1734 trie_lookup_value(const struct trie_node *node, const ovs_be32 value[],
1735 unsigned int *checkbits)
1737 unsigned int plen = 0, match_len = 0;
1738 const struct trie_node *prev = NULL;
1740 for (; node; prev = node, node = trie_next_node(node, value, plen)) {
1741 unsigned int eqbits;
1742 /* Check if this edge can be followed. */
1743 eqbits = prefix_equal_bits(node->prefix, node->nbits, value, plen);
1745 if (eqbits < node->nbits) { /* Mismatch, nothing more to be found. */
1746 /* Bit at offset 'plen' differed. */
1747 *checkbits = plen + 1; /* Includes the first mismatching bit. */
1750 /* Full match, check if rules exist at this prefix length. */
1751 if (node->n_rules > 0) {
1755 /* Dead end, exclude the other branch if it exists. */
1756 *checkbits = !prev || trie_is_leaf(prev) ? plen : plen + 1;
1761 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
1762 unsigned int *checkbits)
1764 const struct mf_field *mf = trie->field;
1766 /* Check that current flow matches the prerequisites for the trie
1767 * field. Some match fields are used for multiple purposes, so we
1768 * must check that the trie is relevant for this flow. */
1769 if (mf_are_prereqs_ok(mf, flow)) {
1770 return trie_lookup_value(trie->root,
1771 &((ovs_be32 *)flow)[mf->flow_be32ofs],
1774 *checkbits = 0; /* Value not used in this case. */
1778 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
1779 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
1780 * 'miniflow_index' is not NULL. */
1782 minimask_get_prefix_len(const struct minimask *minimask,
1783 const struct mf_field *mf)
1785 unsigned int nbits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
1786 uint8_t u32_ofs = mf->flow_be32ofs;
1787 uint8_t u32_end = u32_ofs + mf->n_bytes / 4;
1789 for (; u32_ofs < u32_end; ++u32_ofs) {
1791 mask = ntohl((OVS_FORCE ovs_be32)minimask_get(minimask, u32_ofs));
1793 /* Validate mask, count the mask length. */
1796 return 0; /* No bits allowed after mask ended. */
1799 if (~mask & (~mask + 1)) {
1800 return 0; /* Mask not contiguous. */
1802 mask_tz = ctz32(mask);
1803 nbits += 32 - mask_tz;
1811 * This is called only when mask prefix is known to be CIDR and non-zero.
1812 * Relies on the fact that the flow and mask have the same map, and since
1813 * the mask is CIDR, the storage for the flow field exists even if it
1814 * happened to be zeros.
1816 static const ovs_be32 *
1817 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
1819 return match->flow.values +
1820 count_1bits(match->flow.map & ((UINT64_C(1) << mf->flow_be32ofs) - 1));
1823 /* Insert rule in to the prefix tree.
1824 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1827 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1829 const ovs_be32 *prefix = minimatch_get_prefix(&rule->match, trie->field);
1830 struct trie_node *node;
1831 struct trie_node **edge;
1834 /* Walk the tree. */
1835 for (edge = &trie->root;
1836 (node = *edge) != NULL;
1837 edge = trie_next_edge(node, prefix, ofs)) {
1838 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1840 if (eqbits < node->nbits) {
1841 /* Mismatch, new node needs to be inserted above. */
1842 int old_branch = get_bit_at(node->prefix, eqbits);
1844 /* New parent node. */
1845 *edge = trie_branch_create(prefix, ofs - eqbits, eqbits,
1846 ofs == mlen ? 1 : 0);
1848 /* Adjust old node for its new position in the tree. */
1849 node->prefix <<= eqbits;
1850 node->nbits -= eqbits;
1851 (*edge)->edges[old_branch] = node;
1853 /* Check if need a new branch for the new rule. */
1855 (*edge)->edges[!old_branch]
1856 = trie_branch_create(prefix, ofs, mlen - ofs, 1);
1860 /* Full match so far. */
1863 /* Full match at the current node, rule needs to be added here. */
1868 /* Must insert a new tree branch for the new rule. */
1869 *edge = trie_branch_create(prefix, ofs, mlen - ofs, 1);
1872 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1875 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1877 const ovs_be32 *prefix = minimatch_get_prefix(&rule->match, trie->field);
1878 struct trie_node *node;
1879 struct trie_node **edges[sizeof(union mf_value) * 8];
1880 int depth = 0, ofs = 0;
1882 /* Walk the tree. */
1883 for (edges[depth] = &trie->root;
1884 (node = *edges[depth]) != NULL;
1885 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
1886 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1887 if (eqbits < node->nbits) {
1888 /* Mismatch, nothing to be removed. This should never happen, as
1889 * only rules in the classifier are ever removed. */
1890 break; /* Log a warning. */
1892 /* Full match so far. */
1896 /* Full prefix match at the current node, remove rule here. */
1897 if (!node->n_rules) {
1898 break; /* Log a warning. */
1902 /* Check if can prune the tree. */
1903 while (!node->n_rules && !(node->edges[0] && node->edges[1])) {
1904 /* No rules and at most one child node, remove this node. */
1905 struct trie_node *next;
1906 next = node->edges[0] ? node->edges[0] : node->edges[1];
1909 if (node->nbits + next->nbits > TRIE_PREFIX_BITS) {
1910 break; /* Cannot combine. */
1912 /* Combine node with next. */
1913 next->prefix = node->prefix | next->prefix >> node->nbits;
1914 next->nbits += node->nbits;
1916 trie_node_destroy(node);
1917 /* Update the parent's edge. */
1918 *edges[depth] = next;
1919 if (next || !depth) {
1920 /* Branch not pruned or at root, nothing more to do. */
1923 node = *edges[--depth];
1928 /* Cannot go deeper. This should never happen, since only rules
1929 * that actually exist in the classifier are ever removed. */
1930 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");