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"
29 #include "ovs-thread.h"
36 VLOG_DEFINE_THIS_MODULE(classifier);
41 /* Ports trie depends on both ports sharing the same ovs_be32. */
42 #define TP_PORTS_OFS32 (offsetof(struct flow, tp_src) / 4)
43 BUILD_ASSERT_DECL(TP_PORTS_OFS32 == offsetof(struct flow, tp_dst) / 4);
45 /* Prefix trie for a 'field' */
47 const struct mf_field *field; /* Trie field, or NULL. */
48 struct trie_node *root; /* NULL if none. */
52 CLS_MAX_INDICES = 3 /* Maximum number of lookup indices per subtable. */
55 struct cls_classifier {
56 int n_rules; /* Total number of rules. */
57 uint8_t n_flow_segments;
58 uint8_t flow_segments[CLS_MAX_INDICES]; /* Flow segment boundaries to use
59 * for staged lookup. */
60 struct cmap subtables_map; /* Contains "struct cls_subtable"s. */
61 struct pvector subtables;
62 struct cmap partitions; /* Contains "struct cls_partition"s. */
63 struct cls_trie tries[CLS_MAX_TRIES]; /* Prefix tries. */
67 /* A set of rules that all have the same fields wildcarded. */
69 struct cmap_node cmap_node; /* Within struct cls_classifier
71 struct cmap rules; /* Contains "struct cls_rule"s. */
72 int n_rules; /* Number of rules, including duplicates. */
73 unsigned int max_priority; /* Max priority of any rule in the subtable. */
74 unsigned int max_count; /* Count of max_priority rules. */
75 tag_type tag; /* Tag generated from mask for partitioning. */
76 uint8_t n_indices; /* How many indices to use. */
77 uint8_t index_ofs[CLS_MAX_INDICES]; /* u32 flow segment boundaries. */
78 struct cmap indices[CLS_MAX_INDICES]; /* Staged lookup indices. */
79 unsigned int trie_plen[CLS_MAX_TRIES]; /* Trie prefix length in 'mask'. */
81 struct trie_node *ports_trie; /* NULL if none. */
82 struct minimask mask; /* Wildcards for fields. */
83 /* 'mask' must be the last field. */
86 /* Associates a metadata value (that is, a value of the OpenFlow 1.1+ metadata
87 * field) with tags for the "cls_subtable"s that contain rules that match that
89 struct cls_partition {
90 struct cmap_node cmap_node; /* In struct cls_classifier's 'partitions'
92 ovs_be64 metadata; /* metadata value for this partition. */
93 tag_type tags; /* OR of each flow's cls_subtable tag. */
94 struct tag_tracker tracker; /* Tracks the bits in 'tags'. */
97 /* Internal representation of a rule in a "struct cls_subtable". */
99 struct cls_rule *cls_rule;
100 struct cmap_node index_nodes[CLS_MAX_INDICES]; /* Within subtable's
102 struct cmap_node cmap_node; /* Within struct cls_subtable 'rules'. */
103 unsigned int priority; /* Larger numbers are higher priorities. */
104 struct cls_partition *partition;
105 struct list list; /* List of identical, lower-priority rules. */
106 struct miniflow flow; /* Matching rule. Mask is in the subtable. */
107 /* 'flow' must be the last field. */
110 static struct cls_match *
111 cls_match_alloc(struct cls_rule *rule)
113 int count = count_1bits(rule->match.flow.map);
115 struct cls_match *cls_match
116 = xmalloc(sizeof *cls_match - sizeof cls_match->flow.inline_values
117 + MINIFLOW_VALUES_SIZE(count));
119 cls_match->cls_rule = rule;
120 miniflow_clone_inline(&cls_match->flow, &rule->match.flow, count);
121 cls_match->priority = rule->priority;
122 rule->cls_match = cls_match;
127 static struct cls_subtable *find_subtable(const struct cls_classifier *,
128 const struct minimask *);
129 static struct cls_subtable *insert_subtable(struct cls_classifier *,
130 const struct minimask *);
132 static void destroy_subtable(struct cls_classifier *, struct cls_subtable *);
134 static struct cls_match *find_match_wc(const struct cls_subtable *,
135 const struct flow *, struct trie_ctx *,
136 unsigned int n_tries,
137 struct flow_wildcards *);
138 static struct cls_match *find_equal(struct cls_subtable *,
139 const struct miniflow *, uint32_t hash);
140 static struct cls_match *insert_rule(struct cls_classifier *,
141 struct cls_subtable *, struct cls_rule *);
143 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list. */
144 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD) \
145 for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
146 #define FOR_EACH_RULE_IN_LIST_SAFE(RULE, NEXT, HEAD) \
147 for ((RULE) = (HEAD); \
148 (RULE) != NULL && ((NEXT) = next_rule_in_list(RULE), true); \
151 static struct cls_match *next_rule_in_list__(struct cls_match *);
152 static struct cls_match *next_rule_in_list(struct cls_match *);
154 static unsigned int minimask_get_prefix_len(const struct minimask *,
155 const struct mf_field *);
156 static void trie_init(struct cls_classifier *, int trie_idx,
157 const struct mf_field *);
158 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
159 unsigned int *checkbits);
160 static unsigned int trie_lookup_value(const struct trie_node *,
161 const ovs_be32 value[],
162 unsigned int value_bits,
163 unsigned int *checkbits);
164 static void trie_destroy(struct trie_node *);
165 static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
166 static void trie_insert_prefix(struct trie_node **, const ovs_be32 *prefix,
168 static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
169 static void trie_remove_prefix(struct trie_node **, const ovs_be32 *prefix,
171 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
173 static bool mask_prefix_bits_set(const struct flow_wildcards *,
174 uint8_t be32ofs, unsigned int nbits);
176 /* flow/miniflow/minimask/minimatch utilities.
177 * These are only used by the classifier, so place them here to allow
178 * for better optimization. */
180 static inline uint64_t
181 miniflow_get_map_in_range(const struct miniflow *miniflow,
182 uint8_t start, uint8_t end, unsigned int *offset)
184 uint64_t map = miniflow->map;
188 uint64_t msk = (UINT64_C(1) << start) - 1; /* 'start' LSBs set */
189 *offset = count_1bits(map & msk);
192 if (end < FLOW_U32S) {
193 uint64_t msk = (UINT64_C(1) << end) - 1; /* 'end' LSBs set */
199 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
200 * 'mask', given 'basis'.
202 * The hash values returned by this function are the same as those returned by
203 * miniflow_hash_in_minimask(), only the form of the arguments differ. */
204 static inline uint32_t
205 flow_hash_in_minimask(const struct flow *flow, const struct minimask *mask,
208 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
209 const uint32_t *flow_u32 = (const uint32_t *)flow;
210 const uint32_t *p = mask_values;
215 for (map = mask->masks.map; map; map = zero_rightmost_1bit(map)) {
216 hash = hash_add(hash, flow_u32[raw_ctz(map)] & *p++);
219 return hash_finish(hash, (p - mask_values) * 4);
222 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
223 * 'mask', given 'basis'.
225 * The hash values returned by this function are the same as those returned by
226 * flow_hash_in_minimask(), only the form of the arguments differ. */
227 static inline uint32_t
228 miniflow_hash_in_minimask(const struct miniflow *flow,
229 const struct minimask *mask, uint32_t basis)
231 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
232 const uint32_t *p = mask_values;
233 uint32_t hash = basis;
236 MINIFLOW_FOR_EACH_IN_MAP(flow_u32, flow, mask->masks.map) {
237 hash = hash_add(hash, flow_u32 & *p++);
240 return hash_finish(hash, (p - mask_values) * 4);
243 /* Returns a hash value for the bits of range [start, end) in 'flow',
244 * where there are 1-bits in 'mask', given 'hash'.
246 * The hash values returned by this function are the same as those returned by
247 * minimatch_hash_range(), only the form of the arguments differ. */
248 static inline uint32_t
249 flow_hash_in_minimask_range(const struct flow *flow,
250 const struct minimask *mask,
251 uint8_t start, uint8_t end, uint32_t *basis)
253 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
254 const uint32_t *flow_u32 = (const uint32_t *)flow;
256 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
258 const uint32_t *p = mask_values + offset;
259 uint32_t hash = *basis;
261 for (; map; map = zero_rightmost_1bit(map)) {
262 hash = hash_add(hash, flow_u32[raw_ctz(map)] & *p++);
265 *basis = hash; /* Allow continuation from the unfinished value. */
266 return hash_finish(hash, (p - mask_values) * 4);
269 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask. */
271 flow_wildcards_fold_minimask(struct flow_wildcards *wc,
272 const struct minimask *mask)
274 flow_union_with_miniflow(&wc->masks, &mask->masks);
277 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask
278 * in range [start, end). */
280 flow_wildcards_fold_minimask_range(struct flow_wildcards *wc,
281 const struct minimask *mask,
282 uint8_t start, uint8_t end)
284 uint32_t *dst_u32 = (uint32_t *)&wc->masks;
286 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
288 const uint32_t *p = miniflow_get_u32_values(&mask->masks) + offset;
290 for (; map; map = zero_rightmost_1bit(map)) {
291 dst_u32[raw_ctz(map)] |= *p++;
295 /* Returns a hash value for 'flow', given 'basis'. */
296 static inline uint32_t
297 miniflow_hash(const struct miniflow *flow, uint32_t basis)
299 const uint32_t *values = miniflow_get_u32_values(flow);
300 const uint32_t *p = values;
301 uint32_t hash = basis;
302 uint64_t hash_map = 0;
305 for (map = flow->map; map; map = zero_rightmost_1bit(map)) {
307 hash = hash_add(hash, *p);
308 hash_map |= rightmost_1bit(map);
312 hash = hash_add(hash, hash_map);
313 hash = hash_add(hash, hash_map >> 32);
315 return hash_finish(hash, p - values);
318 /* Returns a hash value for 'mask', given 'basis'. */
319 static inline uint32_t
320 minimask_hash(const struct minimask *mask, uint32_t basis)
322 return miniflow_hash(&mask->masks, basis);
325 /* Returns a hash value for 'match', given 'basis'. */
326 static inline uint32_t
327 minimatch_hash(const struct minimatch *match, uint32_t basis)
329 return miniflow_hash(&match->flow, minimask_hash(&match->mask, basis));
332 /* Returns a hash value for the bits of range [start, end) in 'minimatch',
335 * The hash values returned by this function are the same as those returned by
336 * flow_hash_in_minimask_range(), only the form of the arguments differ. */
337 static inline uint32_t
338 minimatch_hash_range(const struct minimatch *match, uint8_t start, uint8_t end,
342 const uint32_t *p, *q;
343 uint32_t hash = *basis;
346 n = count_1bits(miniflow_get_map_in_range(&match->mask.masks, start, end,
348 q = miniflow_get_u32_values(&match->mask.masks) + offset;
349 p = miniflow_get_u32_values(&match->flow) + offset;
351 for (i = 0; i < n; i++) {
352 hash = hash_add(hash, p[i] & q[i]);
354 *basis = hash; /* Allow continuation from the unfinished value. */
355 return hash_finish(hash, (offset + n) * 4);
361 /* Initializes 'rule' to match packets specified by 'match' at the given
362 * 'priority'. 'match' must satisfy the invariant described in the comment at
363 * the definition of struct match.
365 * The caller must eventually destroy 'rule' with cls_rule_destroy().
367 * (OpenFlow uses priorities between 0 and UINT16_MAX, inclusive, but
368 * internally Open vSwitch supports a wider range.) */
370 cls_rule_init(struct cls_rule *rule,
371 const struct match *match, unsigned int priority)
373 minimatch_init(&rule->match, match);
374 rule->priority = priority;
375 rule->cls_match = NULL;
378 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
380 cls_rule_init_from_minimatch(struct cls_rule *rule,
381 const struct minimatch *match,
382 unsigned int priority)
384 minimatch_clone(&rule->match, match);
385 rule->priority = priority;
386 rule->cls_match = NULL;
389 /* Initializes 'dst' as a copy of 'src'.
391 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
393 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
395 minimatch_clone(&dst->match, &src->match);
396 dst->priority = src->priority;
397 dst->cls_match = NULL;
400 /* Initializes 'dst' with the data in 'src', destroying 'src'.
402 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
404 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
406 minimatch_move(&dst->match, &src->match);
407 dst->priority = src->priority;
408 dst->cls_match = NULL;
411 /* Frees memory referenced by 'rule'. Doesn't free 'rule' itself (it's
412 * normally embedded into a larger structure).
414 * ('rule' must not currently be in a classifier.) */
416 cls_rule_destroy(struct cls_rule *rule)
418 ovs_assert(!rule->cls_match);
419 minimatch_destroy(&rule->match);
422 /* Returns true if 'a' and 'b' match the same packets at the same priority,
423 * false if they differ in some way. */
425 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
427 return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
430 /* Returns a hash value for 'rule', folding in 'basis'. */
432 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
434 return minimatch_hash(&rule->match, hash_int(rule->priority, basis));
437 /* Appends a string describing 'rule' to 's'. */
439 cls_rule_format(const struct cls_rule *rule, struct ds *s)
441 minimatch_format(&rule->match, s, rule->priority);
444 /* Returns true if 'rule' matches every packet, false otherwise. */
446 cls_rule_is_catchall(const struct cls_rule *rule)
448 return minimask_is_catchall(&rule->match.mask);
451 /* Initializes 'cls' as a classifier that initially contains no classification
454 classifier_init(struct classifier *cls_, const uint8_t *flow_segments)
456 struct cls_classifier *cls = xmalloc(sizeof *cls);
458 fat_rwlock_init(&cls_->rwlock);
463 cmap_init(&cls->subtables_map);
464 pvector_init(&cls->subtables);
465 cmap_init(&cls->partitions);
466 cls->n_flow_segments = 0;
468 while (cls->n_flow_segments < CLS_MAX_INDICES
469 && *flow_segments < FLOW_U32S) {
470 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
476 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
477 * caller's responsibility. */
479 classifier_destroy(struct classifier *cls_)
482 struct cls_classifier *cls = cls_->cls;
483 struct cls_partition *partition, *next_partition;
484 struct cls_subtable *subtable, *next_subtable;
487 fat_rwlock_destroy(&cls_->rwlock);
492 for (i = 0; i < cls->n_tries; i++) {
493 trie_destroy(cls->tries[i].root);
496 CMAP_FOR_EACH_SAFE (subtable, next_subtable, cmap_node,
497 &cls->subtables_map) {
498 destroy_subtable(cls, subtable);
500 cmap_destroy(&cls->subtables_map);
502 CMAP_FOR_EACH_SAFE (partition, next_partition, cmap_node,
504 ovsrcu_postpone(free, partition);
506 cmap_destroy(&cls->partitions);
508 pvector_destroy(&cls->subtables);
513 /* We use uint64_t as a set for the fields below. */
514 BUILD_ASSERT_DECL(MFF_N_IDS <= 64);
516 /* Set the fields for which prefix lookup should be performed. */
518 classifier_set_prefix_fields(struct classifier *cls_,
519 const enum mf_field_id *trie_fields,
520 unsigned int n_fields)
522 struct cls_classifier *cls = cls_->cls;
526 for (i = 0, trie = 0; i < n_fields && trie < CLS_MAX_TRIES; i++) {
527 const struct mf_field *field = mf_from_id(trie_fields[i]);
528 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
529 /* Incompatible field. This is the only place where we
530 * enforce these requirements, but the rest of the trie code
531 * depends on the flow_be32ofs to be non-negative and the
532 * field length to be a multiple of 32 bits. */
536 if (fields & (UINT64_C(1) << trie_fields[i])) {
537 /* Duplicate field, there is no need to build more than
538 * one index for any one field. */
541 fields |= UINT64_C(1) << trie_fields[i];
543 if (trie >= cls->n_tries || field != cls->tries[trie].field) {
544 trie_init(cls, trie, field);
549 /* Destroy the rest. */
550 for (i = trie; i < cls->n_tries; i++) {
551 trie_init(cls, i, NULL);
557 trie_init(struct cls_classifier *cls, int trie_idx,
558 const struct mf_field *field)
560 struct cls_trie *trie = &cls->tries[trie_idx];
561 struct cls_subtable *subtable;
563 if (trie_idx < cls->n_tries) {
564 trie_destroy(trie->root);
569 /* Add existing rules to the trie. */
570 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
573 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
574 /* Initialize subtable's prefix length on this field. */
575 subtable->trie_plen[trie_idx] = plen;
578 struct cls_match *head;
580 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
581 struct cls_match *match;
583 FOR_EACH_RULE_IN_LIST (match, head) {
584 trie_insert(trie, match->cls_rule, plen);
591 /* Returns true if 'cls' contains no classification rules, false otherwise. */
593 classifier_is_empty(const struct classifier *cls)
595 return cls->cls->n_rules == 0;
598 /* Returns the number of rules in 'cls'. */
600 classifier_count(const struct classifier *cls)
602 return cls->cls->n_rules;
606 hash_metadata(ovs_be64 metadata_)
608 uint64_t metadata = (OVS_FORCE uint64_t) metadata_;
609 return hash_uint64(metadata);
612 static struct cls_partition *
613 find_partition(const struct cls_classifier *cls, ovs_be64 metadata,
616 struct cls_partition *partition;
618 CMAP_FOR_EACH_WITH_HASH (partition, cmap_node, hash, &cls->partitions) {
619 if (partition->metadata == metadata) {
627 static struct cls_partition *
628 create_partition(struct cls_classifier *cls, struct cls_subtable *subtable,
631 uint32_t hash = hash_metadata(metadata);
632 struct cls_partition *partition = find_partition(cls, metadata, hash);
634 partition = xmalloc(sizeof *partition);
635 partition->metadata = metadata;
637 tag_tracker_init(&partition->tracker);
638 cmap_insert(&cls->partitions, &partition->cmap_node, hash);
640 tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
644 static inline ovs_be32 minimatch_get_ports(const struct minimatch *match)
646 /* Could optimize to use the same map if needed for fast path. */
647 return MINIFLOW_GET_BE32(&match->flow, tp_src)
648 & MINIFLOW_GET_BE32(&match->mask.masks, tp_src);
651 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
652 * must not modify or free it.
654 * If 'cls' already contains an identical rule (including wildcards, values of
655 * fixed fields, and priority), replaces the old rule by 'rule' and returns the
656 * rule that was replaced. The caller takes ownership of the returned rule and
657 * is thus responsible for destroying it with cls_rule_destroy(), freeing the
658 * memory block in which it resides, etc., as necessary.
660 * Returns NULL if 'cls' does not contain a rule with an identical key, after
661 * inserting the new rule. In this case, no rules are displaced by the new
662 * rule, even rules that cannot have any effect because the new rule matches a
663 * superset of their flows and has higher priority. */
665 classifier_replace(struct classifier *cls_, struct cls_rule *rule)
667 struct cls_classifier *cls = cls_->cls;
668 struct cls_match *old_rule;
669 struct cls_subtable *subtable;
671 subtable = find_subtable(cls, &rule->match.mask);
673 subtable = insert_subtable(cls, &rule->match.mask);
676 old_rule = insert_rule(cls, subtable, rule);
680 rule->cls_match->partition = NULL;
681 if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
682 ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
683 rule->cls_match->partition = create_partition(cls, subtable,
689 for (i = 0; i < cls->n_tries; i++) {
690 if (subtable->trie_plen[i]) {
691 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
696 if (subtable->ports_mask_len) {
697 /* We mask the value to be inserted to always have the wildcarded
698 * bits in known (zero) state, so we can include them in comparison
699 * and they will always match (== their original value does not
701 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
703 trie_insert_prefix(&subtable->ports_trie, &masked_ports,
704 subtable->ports_mask_len);
709 struct cls_rule *old_cls_rule = old_rule->cls_rule;
711 rule->cls_match->partition = old_rule->partition;
712 old_cls_rule->cls_match = NULL;
714 /* 'old_rule' contains a cmap_node, which may not be freed
716 ovsrcu_postpone(free, old_rule);
722 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
723 * must not modify or free it.
725 * 'cls' must not contain an identical rule (including wildcards, values of
726 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
729 classifier_insert(struct classifier *cls, struct cls_rule *rule)
731 struct cls_rule *displaced_rule = classifier_replace(cls, rule);
732 ovs_assert(!displaced_rule);
735 /* Removes 'rule' from 'cls'. It is the caller's responsibility to destroy
736 * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
737 * resides, etc., as necessary. */
739 classifier_remove(struct classifier *cls_, struct cls_rule *rule)
741 struct cls_classifier *cls = cls_->cls;
742 struct cls_partition *partition;
743 struct cls_match *cls_match = rule->cls_match;
744 struct cls_match *head;
745 struct cls_subtable *subtable;
747 uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
748 uint8_t prev_be32ofs = 0;
750 ovs_assert(cls_match);
752 subtable = find_subtable(cls, &rule->match.mask);
753 ovs_assert(subtable);
755 if (subtable->ports_mask_len) {
756 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
758 trie_remove_prefix(&subtable->ports_trie,
759 &masked_ports, subtable->ports_mask_len);
761 for (i = 0; i < cls->n_tries; i++) {
762 if (subtable->trie_plen[i]) {
763 trie_remove(&cls->tries[i], rule, subtable->trie_plen[i]);
767 /* Remove rule node from indices. */
768 for (i = 0; i < subtable->n_indices; i++) {
769 ihash[i] = minimatch_hash_range(&rule->match, prev_be32ofs,
770 subtable->index_ofs[i], &basis);
771 cmap_remove(&subtable->indices[i], &cls_match->index_nodes[i],
773 prev_be32ofs = subtable->index_ofs[i];
775 hash = minimatch_hash_range(&rule->match, prev_be32ofs, FLOW_U32S, &basis);
777 head = find_equal(subtable, &rule->match.flow, hash);
778 if (head != cls_match) {
779 list_remove(&cls_match->list);
780 } else if (list_is_empty(&cls_match->list)) {
781 cmap_remove(&subtable->rules, &cls_match->cmap_node, hash);
783 struct cls_match *next = CONTAINER_OF(cls_match->list.next,
784 struct cls_match, list);
786 list_remove(&cls_match->list);
787 cmap_replace(&subtable->rules, &cls_match->cmap_node,
788 &next->cmap_node, hash);
791 partition = cls_match->partition;
793 tag_tracker_subtract(&partition->tracker, &partition->tags,
795 if (!partition->tags) {
796 cmap_remove(&cls->partitions, &partition->cmap_node,
797 hash_metadata(partition->metadata));
798 ovsrcu_postpone(free, partition);
802 if (--subtable->n_rules == 0) {
803 destroy_subtable(cls, subtable);
804 } else if (subtable->max_priority == cls_match->priority
805 && --subtable->max_count == 0) {
806 /* Find the new 'max_priority' and 'max_count'. */
807 struct cls_match *head;
808 unsigned int max_priority = 0;
810 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
811 if (head->priority > max_priority) {
812 max_priority = head->priority;
813 subtable->max_count = 1;
814 } else if (head->priority == max_priority) {
815 ++subtable->max_count;
818 subtable->max_priority = max_priority;
819 pvector_change_priority(&cls->subtables, subtable, max_priority);
824 rule->cls_match = NULL;
825 ovsrcu_postpone(free, cls_match);
828 /* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
829 * subtables which have more than 'match_plen' bits in their corresponding
830 * field at offset 'be32ofs'. If skipped, 'maskbits' prefix bits should be
831 * unwildcarded to quarantee datapath flow matches only packets it should. */
833 const struct cls_trie *trie;
834 bool lookup_done; /* Status of the lookup. */
835 uint8_t be32ofs; /* U32 offset of the field in question. */
836 unsigned int match_plen; /* Longest prefix than could possibly match. */
837 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
841 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
844 ctx->be32ofs = trie->field->flow_be32ofs;
845 ctx->lookup_done = false;
848 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
849 * Returns a null pointer if no rules in 'cls' match 'flow'. If multiple rules
850 * of equal priority match 'flow', returns one arbitrarily.
852 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
853 * set of bits that were significant in the lookup. At some point
854 * earlier, 'wc' should have been initialized (e.g., by
855 * flow_wildcards_init_catchall()). */
857 classifier_lookup(const struct classifier *cls_, const struct flow *flow,
858 struct flow_wildcards *wc)
860 struct cls_classifier *cls = cls_->cls;
861 const struct cls_partition *partition;
863 int64_t best_priority = -1;
864 const struct cls_match *best;
865 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
866 struct cls_subtable *subtable;
868 /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
869 * then 'flow' cannot possibly match in 'subtable':
871 * - If flow->metadata maps to a given 'partition', then we can use
872 * 'tags' for 'partition->tags'.
874 * - If flow->metadata has no partition, then no rule in 'cls' has an
875 * exact-match for flow->metadata. That means that we don't need to
876 * search any subtable that includes flow->metadata in its mask.
878 * In either case, we always need to search any cls_subtables that do not
879 * include flow->metadata in its mask. One way to do that would be to
880 * check the "cls_subtable"s explicitly for that, but that would require an
881 * extra branch per subtable. Instead, we mark such a cls_subtable's
882 * 'tags' as TAG_ALL and make sure that 'tags' is never empty. This means
883 * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
884 * need a special case.
886 partition = (cmap_is_empty(&cls->partitions)
888 : find_partition(cls, flow->metadata,
889 hash_metadata(flow->metadata)));
890 tags = partition ? partition->tags : TAG_ARBITRARY;
892 /* Initialize trie contexts for match_find_wc(). */
893 for (int i = 0; i < cls->n_tries; i++) {
894 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
898 PVECTOR_FOR_EACH_PRIORITY(subtable, best_priority, 2,
899 sizeof(struct cls_subtable), &cls->subtables) {
900 struct cls_match *rule;
902 if (!tag_intersects(tags, subtable->tag)) {
906 rule = find_match_wc(subtable, flow, trie_ctx, cls->n_tries, wc);
907 if (rule && (int64_t)rule->priority > best_priority) {
908 best_priority = (int64_t)rule->priority;
913 return best ? best->cls_rule : NULL;
916 /* Returns true if 'target' satisifies 'match', that is, if each bit for which
917 * 'match' specifies a particular value has the correct value in 'target'.
919 * 'flow' and 'mask' have the same mask! */
921 miniflow_and_mask_matches_miniflow(const struct miniflow *flow,
922 const struct minimask *mask,
923 const struct miniflow *target)
925 const uint32_t *flowp = miniflow_get_u32_values(flow);
926 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
929 MINIFLOW_FOR_EACH_IN_MAP(target_u32, target, mask->masks.map) {
930 if ((*flowp++ ^ target_u32) & *maskp++) {
938 static inline struct cls_match *
939 find_match_miniflow(const struct cls_subtable *subtable,
940 const struct miniflow *flow,
943 struct cls_match *rule;
945 CMAP_FOR_EACH_WITH_HASH (rule, cmap_node, hash, &subtable->rules) {
946 if (miniflow_and_mask_matches_miniflow(&rule->flow, &subtable->mask,
955 /* For each miniflow in 'flows' performs a classifier lookup writing the result
956 * into the corresponding slot in 'rules'. If a particular entry in 'flows' is
957 * NULL it is skipped.
959 * This function is optimized for use in the userspace datapath and therefore
960 * does not implement a lot of features available in the standard
961 * classifier_lookup() function. Specifically, it does not implement
962 * priorities, instead returning any rule which matches the flow. */
964 classifier_lookup_miniflow_batch(const struct classifier *cls_,
965 const struct miniflow **flows,
966 struct cls_rule **rules, size_t len)
968 struct cls_classifier *cls = cls_->cls;
969 struct cls_subtable *subtable;
972 memset(rules, 0, len * sizeof *rules);
973 PVECTOR_FOR_EACH (subtable, &cls->subtables) {
974 for (i = begin; i < len; i++) {
975 struct cls_match *match;
978 if (OVS_UNLIKELY(rules[i] || !flows[i])) {
982 hash = miniflow_hash_in_minimask(flows[i], &subtable->mask, 0);
983 match = find_match_miniflow(subtable, flows[i], hash);
984 if (OVS_UNLIKELY(match)) {
985 rules[i] = match->cls_rule;
989 while (begin < len && (rules[begin] || !flows[begin])) {
998 /* Finds and returns a rule in 'cls' with exactly the same priority and
999 * matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
1000 * contain an exact match. */
1002 classifier_find_rule_exactly(const struct classifier *cls_,
1003 const struct cls_rule *target)
1005 struct cls_classifier *cls = cls_->cls;
1006 struct cls_match *head, *rule;
1007 struct cls_subtable *subtable;
1009 subtable = find_subtable(cls, &target->match.mask);
1014 /* Skip if there is no hope. */
1015 if (target->priority > subtable->max_priority) {
1019 head = find_equal(subtable, &target->match.flow,
1020 miniflow_hash_in_minimask(&target->match.flow,
1021 &target->match.mask, 0));
1022 FOR_EACH_RULE_IN_LIST (rule, head) {
1023 if (target->priority >= rule->priority) {
1024 return target->priority == rule->priority ? rule->cls_rule : NULL;
1030 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
1031 * same matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
1032 * contain an exact match. */
1034 classifier_find_match_exactly(const struct classifier *cls,
1035 const struct match *target,
1036 unsigned int priority)
1038 struct cls_rule *retval;
1041 cls_rule_init(&cr, target, priority);
1042 retval = classifier_find_rule_exactly(cls, &cr);
1043 cls_rule_destroy(&cr);
1048 /* Checks if 'target' would overlap any other rule in 'cls'. Two rules are
1049 * considered to overlap if both rules have the same priority and a packet
1050 * could match both. */
1052 classifier_rule_overlaps(const struct classifier *cls_,
1053 const struct cls_rule *target)
1055 struct cls_classifier *cls = cls_->cls;
1056 struct cls_subtable *subtable;
1057 int64_t stop_at_priority = (int64_t)target->priority - 1;
1059 /* Iterate subtables in the descending max priority order. */
1060 PVECTOR_FOR_EACH_PRIORITY (subtable, stop_at_priority, 2,
1061 sizeof(struct cls_subtable), &cls->subtables) {
1062 uint32_t storage[FLOW_U32S];
1063 struct minimask mask;
1064 struct cls_match *head;
1066 minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
1067 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
1068 struct cls_match *rule;
1070 FOR_EACH_RULE_IN_LIST (rule, head) {
1071 if (rule->priority < target->priority) {
1072 break; /* Rules in descending priority order. */
1074 if (rule->priority == target->priority
1075 && miniflow_equal_in_minimask(&target->match.flow,
1076 &rule->flow, &mask)) {
1086 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
1087 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
1088 * function returns true if, for every field:
1090 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
1093 * - 'criteria' wildcards the field,
1095 * Conversely, 'rule' does not match 'criteria' and this function returns false
1096 * if, for at least one field:
1098 * - 'criteria' and 'rule' specify different values for the field, or
1100 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
1102 * Equivalently, the truth table for whether a field matches is:
1107 * r +---------+---------+
1108 * i wild | yes | yes |
1110 * e +---------+---------+
1111 * r exact | no |if values|
1113 * a +---------+---------+
1115 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
1116 * commands and by OpenFlow 1.0 aggregate and flow stats.
1118 * Ignores rule->priority. */
1120 cls_rule_is_loose_match(const struct cls_rule *rule,
1121 const struct minimatch *criteria)
1123 return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
1124 && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
1131 rule_matches(const struct cls_match *rule, const struct cls_rule *target)
1134 || miniflow_equal_in_minimask(&rule->flow,
1135 &target->match.flow,
1136 &target->match.mask));
1139 static struct cls_match *
1140 search_subtable(const struct cls_subtable *subtable,
1141 struct cls_cursor *cursor)
1144 || !minimask_has_extra(&subtable->mask, &cursor->target->match.mask)) {
1145 struct cls_match *rule;
1147 CMAP_CURSOR_FOR_EACH (rule, cmap_node, &cursor->rules,
1149 if (rule_matches(rule, cursor->target)) {
1157 /* Initializes 'cursor' for iterating through rules in 'cls':
1159 * - If 'target' is null, the cursor will visit every rule in 'cls'.
1161 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1162 * such that cls_rule_is_loose_match(rule, target) returns true.
1164 * Ignores target->priority. */
1166 cls_cursor_init(struct cls_cursor *cursor, const struct classifier *cls,
1167 const struct cls_rule *target)
1169 cursor->cls = cls->cls;
1170 cursor->target = target && !cls_rule_is_catchall(target) ? target : NULL;
1173 /* Returns the first matching cls_rule in 'cursor''s iteration, or a null
1174 * pointer if there are no matches. */
1176 cls_cursor_first(struct cls_cursor *cursor)
1178 struct cls_subtable *subtable;
1180 CMAP_CURSOR_FOR_EACH (subtable, cmap_node, &cursor->subtables,
1181 &cursor->cls->subtables_map) {
1182 struct cls_match *rule = search_subtable(subtable, cursor);
1185 cursor->subtable = subtable;
1186 return rule->cls_rule;
1193 /* Returns the next matching cls_rule in 'cursor''s iteration, or a null
1194 * pointer if there are no more matches. */
1196 cls_cursor_next(struct cls_cursor *cursor, const struct cls_rule *rule_)
1198 struct cls_match *rule = CONST_CAST(struct cls_match *, rule_->cls_match);
1199 const struct cls_subtable *subtable;
1200 struct cls_match *next;
1202 next = next_rule_in_list__(rule);
1203 if (next->priority < rule->priority) {
1204 return next->cls_rule;
1207 /* 'next' is the head of the list, that is, the rule that is included in
1208 * the subtable's map. (This is important when the classifier contains
1209 * rules that differ only in priority.) */
1211 CMAP_CURSOR_FOR_EACH_CONTINUE (rule, cmap_node, &cursor->rules) {
1212 if (rule_matches(rule, cursor->target)) {
1213 return rule->cls_rule;
1217 subtable = cursor->subtable;
1218 CMAP_CURSOR_FOR_EACH_CONTINUE (subtable, cmap_node, &cursor->subtables) {
1219 rule = search_subtable(subtable, cursor);
1221 cursor->subtable = subtable;
1222 return rule->cls_rule;
1229 static struct cls_subtable *
1230 find_subtable(const struct cls_classifier *cls, const struct minimask *mask)
1232 struct cls_subtable *subtable;
1234 CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, minimask_hash(mask, 0),
1235 &cls->subtables_map) {
1236 if (minimask_equal(mask, &subtable->mask)) {
1243 static struct cls_subtable *
1244 insert_subtable(struct cls_classifier *cls, const struct minimask *mask)
1246 uint32_t hash = minimask_hash(mask, 0);
1247 struct cls_subtable *subtable;
1249 struct flow_wildcards old, new;
1251 int count = count_1bits(mask->masks.map);
1253 subtable = xzalloc(sizeof *subtable - sizeof mask->masks.inline_values
1254 + MINIFLOW_VALUES_SIZE(count));
1255 cmap_init(&subtable->rules);
1256 miniflow_clone_inline(&subtable->mask.masks, &mask->masks, count);
1258 /* Init indices for segmented lookup, if any. */
1259 flow_wildcards_init_catchall(&new);
1262 for (i = 0; i < cls->n_flow_segments; i++) {
1263 flow_wildcards_fold_minimask_range(&new, mask, prev,
1264 cls->flow_segments[i]);
1265 /* Add an index if it adds mask bits. */
1266 if (!flow_wildcards_equal(&new, &old)) {
1267 cmap_init(&subtable->indices[index]);
1268 subtable->index_ofs[index] = cls->flow_segments[i];
1272 prev = cls->flow_segments[i];
1274 /* Check if the rest of the subtable's mask adds any bits,
1275 * and remove the last index if it doesn't. */
1277 flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U32S);
1278 if (flow_wildcards_equal(&new, &old)) {
1280 subtable->index_ofs[index] = 0;
1281 cmap_destroy(&subtable->indices[index]);
1284 subtable->n_indices = index;
1286 subtable->tag = (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1287 ? tag_create_deterministic(hash)
1290 for (i = 0; i < cls->n_tries; i++) {
1291 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1292 cls->tries[i].field);
1296 subtable->ports_trie = NULL;
1297 subtable->ports_mask_len
1298 = 32 - ctz32(ntohl(MINIFLOW_GET_BE32(&mask->masks, tp_src)));
1300 cmap_insert(&cls->subtables_map, &subtable->cmap_node, hash);
1306 destroy_subtable(struct cls_classifier *cls, struct cls_subtable *subtable)
1310 pvector_remove(&cls->subtables, subtable);
1311 trie_destroy(subtable->ports_trie);
1313 for (i = 0; i < subtable->n_indices; i++) {
1314 cmap_destroy(&subtable->indices[i]);
1316 cmap_remove(&cls->subtables_map, &subtable->cmap_node,
1317 minimask_hash(&subtable->mask, 0));
1318 minimask_destroy(&subtable->mask);
1319 cmap_destroy(&subtable->rules);
1320 ovsrcu_postpone(free, subtable);
1328 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1329 * lookup results. */
1331 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1332 const unsigned int field_plen[CLS_MAX_TRIES],
1333 const struct range ofs, const struct flow *flow,
1334 struct flow_wildcards *wc)
1338 /* Check if we could avoid fully unwildcarding the next level of
1339 * fields using the prefix tries. The trie checks are done only as
1340 * needed to avoid folding in additional bits to the wildcards mask. */
1341 for (j = 0; j < n_tries; j++) {
1342 /* Is the trie field relevant for this subtable? */
1343 if (field_plen[j]) {
1344 struct trie_ctx *ctx = &trie_ctx[j];
1345 uint8_t be32ofs = ctx->be32ofs;
1347 /* Is the trie field within the current range of fields? */
1348 if (be32ofs >= ofs.start && be32ofs < ofs.end) {
1349 /* On-demand trie lookup. */
1350 if (!ctx->lookup_done) {
1351 ctx->match_plen = trie_lookup(ctx->trie, flow,
1353 ctx->lookup_done = true;
1355 /* Possible to skip the rest of the subtable if subtable's
1356 * prefix on the field is longer than what is known to match
1357 * based on the trie lookup. */
1358 if (field_plen[j] > ctx->match_plen) {
1359 /* RFC: We want the trie lookup to never result in
1360 * unwildcarding any bits that would not be unwildcarded
1361 * otherwise. Since the trie is shared by the whole
1362 * classifier, it is possible that the 'maskbits' contain
1363 * bits that are irrelevant for the partition of the
1364 * classifier relevant for the current flow. */
1366 /* Can skip if the field is already unwildcarded. */
1367 if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1370 /* Check that the trie result will not unwildcard more bits
1371 * than this stage will. */
1372 if (ctx->maskbits <= field_plen[j]) {
1373 /* Unwildcard the bits and skip the rest. */
1374 mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1375 /* Note: Prerequisite already unwildcarded, as the only
1376 * prerequisite of the supported trie lookup fields is
1377 * the ethertype, which is currently always
1389 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1390 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1391 * value has the correct value in 'target'.
1393 * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
1394 * target, mask) but this is faster because of the invariant that
1395 * flow->map and mask->masks.map are the same, and that this version
1396 * takes the 'wc'. */
1398 miniflow_and_mask_matches_flow(const struct miniflow *flow,
1399 const struct minimask *mask,
1400 const struct flow *target)
1402 const uint32_t *flowp = miniflow_get_u32_values(flow);
1403 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1406 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1407 uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & *maskp++;
1417 static inline struct cls_match *
1418 find_match(const struct cls_subtable *subtable, const struct flow *flow,
1421 struct cls_match *rule;
1423 CMAP_FOR_EACH_WITH_HASH (rule, cmap_node, hash, &subtable->rules) {
1424 if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
1433 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1434 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1435 * value has the correct value in 'target'.
1437 * This function is equivalent to miniflow_and_mask_matches_flow() but this
1438 * version fills in the mask bits in 'wc'. */
1440 miniflow_and_mask_matches_flow_wc(const struct miniflow *flow,
1441 const struct minimask *mask,
1442 const struct flow *target,
1443 struct flow_wildcards *wc)
1445 const uint32_t *flowp = miniflow_get_u32_values(flow);
1446 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1449 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1450 uint32_t mask = *maskp++;
1451 uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & mask;
1454 /* Only unwildcard if none of the differing bits is already
1456 if (!(flow_u32_value(&wc->masks, idx) & diff)) {
1457 /* Keep one bit of the difference. */
1458 *flow_u32_lvalue(&wc->masks, idx) |= rightmost_1bit(diff);
1462 /* Fill in the bits that were looked at. */
1463 *flow_u32_lvalue(&wc->masks, idx) |= mask;
1469 /* Unwildcard the fields looked up so far, if any. */
1471 fill_range_wc(const struct cls_subtable *subtable, struct flow_wildcards *wc,
1475 flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, to);
1479 static struct cls_match *
1480 find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
1481 struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1482 struct flow_wildcards *wc)
1484 uint32_t basis = 0, hash;
1485 struct cls_match *rule;
1489 if (OVS_UNLIKELY(!wc)) {
1490 return find_match(subtable, flow,
1491 flow_hash_in_minimask(flow, &subtable->mask, 0));
1495 /* Try to finish early by checking fields in segments. */
1496 for (i = 0; i < subtable->n_indices; i++) {
1497 struct cmap_node *inode;
1499 ofs.end = subtable->index_ofs[i];
1501 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1503 /* 'wc' bits for the trie field set, now unwildcard the preceding
1504 * bits used so far. */
1505 fill_range_wc(subtable, wc, ofs.start);
1508 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1510 inode = cmap_find(&subtable->indices[i], hash);
1512 /* No match, can stop immediately, but must fold in the bits
1513 * used in lookup so far. */
1514 fill_range_wc(subtable, wc, ofs.end);
1518 /* If we have narrowed down to a single rule already, check whether
1519 * that rule matches. Either way, we're done.
1521 * (Rare) hash collisions may cause us to miss the opportunity for this
1523 if (!cmap_node_next(inode)) {
1524 ASSIGN_CONTAINER(rule, inode - i, index_nodes);
1525 if (miniflow_and_mask_matches_flow_wc(&rule->flow, &subtable->mask,
1531 ofs.start = ofs.end;
1533 ofs.end = FLOW_U32S;
1534 /* Trie check for the final range. */
1535 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1536 fill_range_wc(subtable, wc, ofs.start);
1539 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1541 rule = find_match(subtable, flow, hash);
1542 if (!rule && subtable->ports_mask_len) {
1543 /* Ports are always part of the final range, if any.
1544 * No match was found for the ports. Use the ports trie to figure out
1545 * which ports bits to unwildcard. */
1547 ovs_be32 value, mask;
1549 mask = MINIFLOW_GET_BE32(&subtable->mask.masks, tp_src);
1550 value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
1551 trie_lookup_value(subtable->ports_trie, &value, 32, &mbits);
1553 ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
1554 mask & htonl(~0 << (32 - mbits));
1556 /* Unwildcard all bits in the mask upto the ports, as they were used
1557 * to determine there is no match. */
1558 fill_range_wc(subtable, wc, TP_PORTS_OFS32);
1562 /* Must unwildcard all the fields, as they were looked at. */
1563 flow_wildcards_fold_minimask(wc, &subtable->mask);
1567 static struct cls_match *
1568 find_equal(struct cls_subtable *subtable, const struct miniflow *flow,
1571 struct cls_match *head;
1573 CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1574 if (miniflow_equal(&head->flow, flow)) {
1581 static struct cls_match *
1582 insert_rule(struct cls_classifier *cls, struct cls_subtable *subtable,
1583 struct cls_rule *new_rule)
1585 struct cls_match *old = NULL;
1586 struct cls_match *new = cls_match_alloc(new_rule);
1587 struct cls_match *head;
1589 uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
1590 uint8_t prev_be32ofs = 0;
1592 /* Add new node to segment indices. */
1593 for (i = 0; i < subtable->n_indices; i++) {
1594 ihash[i] = minimatch_hash_range(&new_rule->match, prev_be32ofs,
1595 subtable->index_ofs[i], &basis);
1596 cmap_insert(&subtable->indices[i], &new->index_nodes[i], ihash[i]);
1597 prev_be32ofs = subtable->index_ofs[i];
1599 hash = minimatch_hash_range(&new_rule->match, prev_be32ofs, FLOW_U32S,
1601 head = find_equal(subtable, &new_rule->match.flow, hash);
1603 cmap_insert(&subtable->rules, &new->cmap_node, hash);
1604 list_init(&new->list);
1607 /* Scan the list for the insertion point that will keep the list in
1608 * order of decreasing priority. */
1609 struct cls_match *rule;
1611 FOR_EACH_RULE_IN_LIST (rule, head) {
1612 if (new->priority >= rule->priority) {
1614 /* 'new' is the new highest-priority flow in the list. */
1615 cmap_replace(&subtable->rules, &rule->cmap_node,
1616 &new->cmap_node, hash);
1619 if (new->priority == rule->priority) {
1620 list_replace(&new->list, &rule->list);
1623 list_insert(&rule->list, &new->list);
1629 /* Insert 'new' at the end of the list. */
1630 list_push_back(&head->list, &new->list);
1635 subtable->n_rules++;
1637 /* Rule was added, not replaced. Update 'subtable's 'max_priority'
1638 * and 'max_count', if necessary. */
1639 if (subtable->n_rules == 1) {
1640 subtable->max_priority = new->priority;
1641 subtable->max_count = 1;
1642 pvector_insert(&cls->subtables, subtable, new->priority);
1643 } else if (subtable->max_priority == new->priority) {
1644 ++subtable->max_count;
1645 } else if (new->priority > subtable->max_priority) {
1646 subtable->max_priority = new->priority;
1647 subtable->max_count = 1;
1648 pvector_change_priority(&cls->subtables, subtable, new->priority);
1651 /* Remove old node from indices. */
1652 for (i = 0; i < subtable->n_indices; i++) {
1653 cmap_remove(&subtable->indices[i], &old->index_nodes[i], ihash[i]);
1659 static struct cls_match *
1660 next_rule_in_list__(struct cls_match *rule)
1662 struct cls_match *next = OBJECT_CONTAINING(rule->list.next, next, list);
1666 static struct cls_match *
1667 next_rule_in_list(struct cls_match *rule)
1669 struct cls_match *next = next_rule_in_list__(rule);
1670 return next->priority < rule->priority ? next : NULL;
1673 /* A longest-prefix match tree. */
1675 uint32_t prefix; /* Prefix bits for this node, MSB first. */
1676 uint8_t nbits; /* Never zero, except for the root node. */
1677 unsigned int n_rules; /* Number of rules that have this prefix. */
1678 struct trie_node *edges[2]; /* Both NULL if leaf. */
1681 /* Max bits per node. Must fit in struct trie_node's 'prefix'.
1682 * Also tested with 16, 8, and 5 to stress the implementation. */
1683 #define TRIE_PREFIX_BITS 32
1685 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1686 * Prefixes are in the network byte order, and the offset 0 corresponds to
1687 * the most significant bit of the first byte. The offset can be read as
1688 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1690 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1694 pr += ofs / 32; /* Where to start. */
1695 ofs %= 32; /* How many bits to skip at 'pr'. */
1697 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1698 if (plen > 32 - ofs) { /* Need more than we have already? */
1699 prefix |= ntohl(*++pr) >> (32 - ofs);
1701 /* Return with possible unwanted bits at the end. */
1705 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1706 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1707 * corresponds to the most significant bit of the first byte. The offset can
1708 * be read as "how many bits to skip from the start of the prefix starting at
1711 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1716 if (plen > TRIE_PREFIX_BITS) {
1717 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1719 /* Return with unwanted bits cleared. */
1720 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1723 /* Return the number of equal bits in 'nbits' of 'prefix's MSBs and a 'value'
1724 * starting at "MSB 0"-based offset 'ofs'. */
1726 prefix_equal_bits(uint32_t prefix, unsigned int nbits, const ovs_be32 value[],
1729 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, nbits);
1730 /* Set the bit after the relevant bits to limit the result. */
1731 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - nbits));
1734 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1735 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1737 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1738 unsigned int ofs, unsigned int plen)
1740 return prefix_equal_bits(node->prefix, MIN(node->nbits, plen - ofs),
1744 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1745 * be greater than 31. */
1747 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1749 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1752 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1753 * be between 0 and 31, inclusive. */
1755 get_bit_at(const uint32_t prefix, unsigned int ofs)
1757 return (prefix >> (31 - ofs)) & 1u;
1760 /* Create new branch. */
1761 static struct trie_node *
1762 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1763 unsigned int n_rules)
1765 struct trie_node *node = xmalloc(sizeof *node);
1767 node->prefix = trie_get_prefix(prefix, ofs, plen);
1769 if (plen <= TRIE_PREFIX_BITS) {
1771 node->edges[0] = NULL;
1772 node->edges[1] = NULL;
1773 node->n_rules = n_rules;
1774 } else { /* Need intermediate nodes. */
1775 struct trie_node *subnode = trie_branch_create(prefix,
1776 ofs + TRIE_PREFIX_BITS,
1777 plen - TRIE_PREFIX_BITS,
1779 int bit = get_bit_at(subnode->prefix, 0);
1780 node->nbits = TRIE_PREFIX_BITS;
1781 node->edges[bit] = subnode;
1782 node->edges[!bit] = NULL;
1789 trie_node_destroy(struct trie_node *node)
1795 trie_destroy(struct trie_node *node)
1798 trie_destroy(node->edges[0]);
1799 trie_destroy(node->edges[1]);
1805 trie_is_leaf(const struct trie_node *trie)
1807 return !trie->edges[0] && !trie->edges[1]; /* No children. */
1811 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1814 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1817 for (i = 0; i < nbits / 32; i++) {
1818 mask[i] = OVS_BE32_MAX;
1821 mask[i] |= htonl(~0u << (32 - nbits % 32));
1826 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
1829 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1831 ovs_be32 zeroes = 0;
1833 for (i = 0; i < nbits / 32; i++) {
1837 zeroes |= ~mask[i] & htonl(~0u << (32 - nbits % 32));
1840 return !zeroes; /* All 'nbits' bits set. */
1843 static struct trie_node **
1844 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
1847 return node->edges + be_get_bit_at(value, ofs);
1850 static const struct trie_node *
1851 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
1854 return node->edges[be_get_bit_at(value, ofs)];
1857 /* Return the prefix mask length necessary to find the longest-prefix match for
1858 * the '*value' in the prefix tree 'node'.
1859 * '*checkbits' is set to the number of bits in the prefix mask necessary to
1860 * determine a mismatch, in case there are longer prefixes in the tree below
1861 * the one that matched.
1864 trie_lookup_value(const struct trie_node *node, const ovs_be32 value[],
1865 unsigned int n_bits, unsigned int *checkbits)
1867 unsigned int ofs = 0, match_len = 0;
1868 const struct trie_node *prev = NULL;
1870 for (; node; prev = node, node = trie_next_node(node, value, ofs)) {
1871 unsigned int eqbits;
1872 /* Check if this edge can be followed. */
1873 eqbits = prefix_equal_bits(node->prefix, node->nbits, value, ofs);
1875 if (eqbits < node->nbits) { /* Mismatch, nothing more to be found. */
1876 /* Bit at offset 'ofs' differed. */
1877 *checkbits = ofs + 1; /* Includes the first mismatching bit. */
1880 /* Full match, check if rules exist at this prefix length. */
1881 if (node->n_rules > 0) {
1884 if (ofs >= n_bits) {
1885 *checkbits = n_bits; /* Full prefix. */
1889 /* node == NULL. Full match so far, but we came to a dead end.
1890 * need to exclude the other branch if it exists. */
1891 *checkbits = !prev || trie_is_leaf(prev) ? ofs : ofs + 1;
1896 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
1897 unsigned int *checkbits)
1899 const struct mf_field *mf = trie->field;
1901 /* Check that current flow matches the prerequisites for the trie
1902 * field. Some match fields are used for multiple purposes, so we
1903 * must check that the trie is relevant for this flow. */
1904 if (mf_are_prereqs_ok(mf, flow)) {
1905 return trie_lookup_value(trie->root,
1906 &((ovs_be32 *)flow)[mf->flow_be32ofs],
1907 mf->n_bits, checkbits);
1909 *checkbits = 0; /* Value not used in this case. */
1913 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
1914 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
1915 * 'miniflow_index' is not NULL. */
1917 minimask_get_prefix_len(const struct minimask *minimask,
1918 const struct mf_field *mf)
1920 unsigned int nbits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
1921 uint8_t u32_ofs = mf->flow_be32ofs;
1922 uint8_t u32_end = u32_ofs + mf->n_bytes / 4;
1924 for (; u32_ofs < u32_end; ++u32_ofs) {
1926 mask = ntohl((OVS_FORCE ovs_be32)minimask_get(minimask, u32_ofs));
1928 /* Validate mask, count the mask length. */
1931 return 0; /* No bits allowed after mask ended. */
1934 if (~mask & (~mask + 1)) {
1935 return 0; /* Mask not contiguous. */
1937 mask_tz = ctz32(mask);
1938 nbits += 32 - mask_tz;
1946 * This is called only when mask prefix is known to be CIDR and non-zero.
1947 * Relies on the fact that the flow and mask have the same map, and since
1948 * the mask is CIDR, the storage for the flow field exists even if it
1949 * happened to be zeros.
1951 static const ovs_be32 *
1952 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
1954 return miniflow_get_be32_values(&match->flow) +
1955 count_1bits(match->flow.map & ((UINT64_C(1) << mf->flow_be32ofs) - 1));
1958 /* Insert rule in to the prefix tree.
1959 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1962 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1964 trie_insert_prefix(&trie->root,
1965 minimatch_get_prefix(&rule->match, trie->field), mlen);
1969 trie_insert_prefix(struct trie_node **edge, const ovs_be32 *prefix, int mlen)
1971 struct trie_node *node;
1974 /* Walk the tree. */
1975 for (; (node = *edge) != NULL;
1976 edge = trie_next_edge(node, prefix, ofs)) {
1977 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1979 if (eqbits < node->nbits) {
1980 /* Mismatch, new node needs to be inserted above. */
1981 int old_branch = get_bit_at(node->prefix, eqbits);
1983 /* New parent node. */
1984 *edge = trie_branch_create(prefix, ofs - eqbits, eqbits,
1985 ofs == mlen ? 1 : 0);
1987 /* Adjust old node for its new position in the tree. */
1988 node->prefix <<= eqbits;
1989 node->nbits -= eqbits;
1990 (*edge)->edges[old_branch] = node;
1992 /* Check if need a new branch for the new rule. */
1994 (*edge)->edges[!old_branch]
1995 = trie_branch_create(prefix, ofs, mlen - ofs, 1);
1999 /* Full match so far. */
2002 /* Full match at the current node, rule needs to be added here. */
2007 /* Must insert a new tree branch for the new rule. */
2008 *edge = trie_branch_create(prefix, ofs, mlen - ofs, 1);
2011 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2014 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2016 trie_remove_prefix(&trie->root,
2017 minimatch_get_prefix(&rule->match, trie->field), mlen);
2020 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2023 trie_remove_prefix(struct trie_node **root, const ovs_be32 *prefix, int mlen)
2025 struct trie_node *node;
2026 struct trie_node **edges[sizeof(union mf_value) * 8];
2027 int depth = 0, ofs = 0;
2029 /* Walk the tree. */
2030 for (edges[0] = root;
2031 (node = *edges[depth]) != NULL;
2032 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
2033 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2035 if (eqbits < node->nbits) {
2036 /* Mismatch, nothing to be removed. This should never happen, as
2037 * only rules in the classifier are ever removed. */
2038 break; /* Log a warning. */
2040 /* Full match so far. */
2044 /* Full prefix match at the current node, remove rule here. */
2045 if (!node->n_rules) {
2046 break; /* Log a warning. */
2050 /* Check if can prune the tree. */
2051 while (!node->n_rules && !(node->edges[0] && node->edges[1])) {
2052 /* No rules and at most one child node, remove this node. */
2053 struct trie_node *next;
2054 next = node->edges[0] ? node->edges[0] : node->edges[1];
2057 if (node->nbits + next->nbits > TRIE_PREFIX_BITS) {
2058 break; /* Cannot combine. */
2060 /* Combine node with next. */
2061 next->prefix = node->prefix | next->prefix >> node->nbits;
2062 next->nbits += node->nbits;
2064 trie_node_destroy(node);
2065 /* Update the parent's edge. */
2066 *edges[depth] = next;
2067 if (next || !depth) {
2068 /* Branch not pruned or at root, nothing more to do. */
2071 node = *edges[--depth];
2076 /* Cannot go deeper. This should never happen, since only rules
2077 * that actually exist in the classifier are ever removed. */
2078 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");