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"
30 #include "ovs-thread.h"
37 VLOG_DEFINE_THIS_MODULE(classifier);
42 /* Ports trie depends on both ports sharing the same ovs_be32. */
43 #define TP_PORTS_OFS32 (offsetof(struct flow, tp_src) / 4)
44 BUILD_ASSERT_DECL(TP_PORTS_OFS32 == offsetof(struct flow, tp_dst) / 4);
46 /* Prefix trie for a 'field' */
48 const struct mf_field *field; /* Trie field, or NULL. */
49 struct trie_node *root; /* NULL if none. */
53 CLS_MAX_INDICES = 3 /* Maximum number of lookup indices per subtable. */
56 struct cls_classifier {
57 int n_rules; /* Total number of rules. */
58 uint8_t n_flow_segments;
59 uint8_t flow_segments[CLS_MAX_INDICES]; /* Flow segment boundaries to use
60 * for staged lookup. */
61 struct hmap subtables_map; /* Contains "struct cls_subtable"s. */
62 struct pvector subtables;
63 struct hmap partitions; /* Contains "struct cls_partition"s. */
64 struct cls_trie tries[CLS_MAX_TRIES]; /* Prefix tries. */
68 /* A set of rules that all have the same fields wildcarded. */
70 struct hmap_node hmap_node; /* Within struct cls_classifier 'subtables_map'
72 struct hmap rules; /* Contains "struct cls_rule"s. */
73 int n_rules; /* Number of rules, including duplicates. */
74 unsigned int max_priority; /* Max priority of any rule in the subtable. */
75 unsigned int max_count; /* Count of max_priority rules. */
76 tag_type tag; /* Tag generated from mask for partitioning. */
77 uint8_t n_indices; /* How many indices to use. */
78 uint8_t index_ofs[CLS_MAX_INDICES]; /* u32 flow segment boundaries. */
79 struct hindex indices[CLS_MAX_INDICES]; /* Staged lookup indices. */
80 unsigned int trie_plen[CLS_MAX_TRIES]; /* Trie prefix length in 'mask'. */
82 struct trie_node *ports_trie; /* NULL if none. */
83 struct minimask mask; /* Wildcards for fields. */
84 /* 'mask' must be the last field. */
87 /* Associates a metadata value (that is, a value of the OpenFlow 1.1+ metadata
88 * field) with tags for the "cls_subtable"s that contain rules that match that
90 struct cls_partition {
91 struct hmap_node hmap_node; /* In struct cls_classifier's 'partitions'
93 ovs_be64 metadata; /* metadata value for this partition. */
94 tag_type tags; /* OR of each flow's cls_subtable tag. */
95 struct tag_tracker tracker; /* Tracks the bits in 'tags'. */
98 /* Internal representation of a rule in a "struct cls_subtable". */
100 struct cls_rule *cls_rule;
101 struct hindex_node index_nodes[CLS_MAX_INDICES]; /* Within subtable's
103 struct hmap_node hmap_node; /* Within struct cls_subtable 'rules'. */
104 unsigned int priority; /* Larger numbers are higher priorities. */
105 struct cls_partition *partition;
106 struct list list; /* List of identical, lower-priority rules. */
107 struct miniflow flow; /* Matching rule. Mask is in the subtable. */
108 /* 'flow' must be the last field. */
111 static struct cls_match *
112 cls_match_alloc(struct cls_rule *rule)
114 int count = count_1bits(rule->match.flow.map);
116 struct cls_match *cls_match
117 = xmalloc(sizeof *cls_match - sizeof cls_match->flow.inline_values
118 + MINIFLOW_VALUES_SIZE(count));
120 cls_match->cls_rule = rule;
121 miniflow_clone_inline(&cls_match->flow, &rule->match.flow, count);
122 cls_match->priority = rule->priority;
123 rule->cls_match = cls_match;
128 static struct cls_subtable *find_subtable(const struct cls_classifier *,
129 const struct minimask *);
130 static struct cls_subtable *insert_subtable(struct cls_classifier *,
131 const struct minimask *);
133 static void destroy_subtable(struct cls_classifier *, struct cls_subtable *);
135 static struct cls_match *find_match_wc(const struct cls_subtable *,
136 const struct flow *, struct trie_ctx *,
137 unsigned int n_tries,
138 struct flow_wildcards *);
139 static struct cls_match *find_equal(struct cls_subtable *,
140 const struct miniflow *, uint32_t hash);
141 static struct cls_match *insert_rule(struct cls_classifier *,
142 struct cls_subtable *, struct cls_rule *);
144 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list. */
145 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD) \
146 for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
147 #define FOR_EACH_RULE_IN_LIST_SAFE(RULE, NEXT, HEAD) \
148 for ((RULE) = (HEAD); \
149 (RULE) != NULL && ((NEXT) = next_rule_in_list(RULE), true); \
152 static struct cls_match *next_rule_in_list__(struct cls_match *);
153 static struct cls_match *next_rule_in_list(struct cls_match *);
155 static unsigned int minimask_get_prefix_len(const struct minimask *,
156 const struct mf_field *);
157 static void trie_init(struct cls_classifier *, int trie_idx,
158 const struct mf_field *);
159 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
160 unsigned int *checkbits);
161 static unsigned int trie_lookup_value(const struct trie_node *,
162 const ovs_be32 value[],
163 unsigned int value_bits,
164 unsigned int *checkbits);
165 static void trie_destroy(struct trie_node *);
166 static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
167 static void trie_insert_prefix(struct trie_node **, const ovs_be32 *prefix,
169 static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
170 static void trie_remove_prefix(struct trie_node **, const ovs_be32 *prefix,
172 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
174 static bool mask_prefix_bits_set(const struct flow_wildcards *,
175 uint8_t be32ofs, unsigned int nbits);
177 /* flow/miniflow/minimask/minimatch utilities.
178 * These are only used by the classifier, so place them here to allow
179 * for better optimization. */
181 static inline uint64_t
182 miniflow_get_map_in_range(const struct miniflow *miniflow,
183 uint8_t start, uint8_t end, unsigned int *offset)
185 uint64_t map = miniflow->map;
189 uint64_t msk = (UINT64_C(1) << start) - 1; /* 'start' LSBs set */
190 *offset = count_1bits(map & msk);
193 if (end < FLOW_U32S) {
194 uint64_t msk = (UINT64_C(1) << end) - 1; /* 'end' LSBs set */
200 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
201 * 'mask', given 'basis'.
203 * The hash values returned by this function are the same as those returned by
204 * miniflow_hash_in_minimask(), only the form of the arguments differ. */
205 static inline uint32_t
206 flow_hash_in_minimask(const struct flow *flow, const struct minimask *mask,
209 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
210 const uint32_t *flow_u32 = (const uint32_t *)flow;
211 const uint32_t *p = mask_values;
216 for (map = mask->masks.map; map; map = zero_rightmost_1bit(map)) {
217 hash = mhash_add(hash, flow_u32[raw_ctz(map)] & *p++);
220 return mhash_finish(hash, (p - mask_values) * 4);
223 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
224 * 'mask', given 'basis'.
226 * The hash values returned by this function are the same as those returned by
227 * flow_hash_in_minimask(), only the form of the arguments differ. */
228 static inline uint32_t
229 miniflow_hash_in_minimask(const struct miniflow *flow,
230 const struct minimask *mask, uint32_t basis)
232 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
233 const uint32_t *p = mask_values;
234 uint32_t hash = basis;
237 MINIFLOW_FOR_EACH_IN_MAP(flow_u32, flow, mask->masks.map) {
238 hash = mhash_add(hash, flow_u32 & *p++);
241 return mhash_finish(hash, (p - mask_values) * 4);
244 /* Returns a hash value for the bits of range [start, end) in 'flow',
245 * where there are 1-bits in 'mask', given 'hash'.
247 * The hash values returned by this function are the same as those returned by
248 * minimatch_hash_range(), only the form of the arguments differ. */
249 static inline uint32_t
250 flow_hash_in_minimask_range(const struct flow *flow,
251 const struct minimask *mask,
252 uint8_t start, uint8_t end, uint32_t *basis)
254 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
255 const uint32_t *flow_u32 = (const uint32_t *)flow;
257 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
259 const uint32_t *p = mask_values + offset;
260 uint32_t hash = *basis;
262 for (; map; map = zero_rightmost_1bit(map)) {
263 hash = mhash_add(hash, flow_u32[raw_ctz(map)] & *p++);
266 *basis = hash; /* Allow continuation from the unfinished value. */
267 return mhash_finish(hash, (p - mask_values) * 4);
270 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask. */
272 flow_wildcards_fold_minimask(struct flow_wildcards *wc,
273 const struct minimask *mask)
275 flow_union_with_miniflow(&wc->masks, &mask->masks);
278 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask
279 * in range [start, end). */
281 flow_wildcards_fold_minimask_range(struct flow_wildcards *wc,
282 const struct minimask *mask,
283 uint8_t start, uint8_t end)
285 uint32_t *dst_u32 = (uint32_t *)&wc->masks;
287 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
289 const uint32_t *p = miniflow_get_u32_values(&mask->masks) + offset;
291 for (; map; map = zero_rightmost_1bit(map)) {
292 dst_u32[raw_ctz(map)] |= *p++;
296 /* Returns a hash value for 'flow', given 'basis'. */
297 static inline uint32_t
298 miniflow_hash(const struct miniflow *flow, uint32_t basis)
300 const uint32_t *values = miniflow_get_u32_values(flow);
301 const uint32_t *p = values;
302 uint32_t hash = basis;
303 uint64_t hash_map = 0;
306 for (map = flow->map; map; map = zero_rightmost_1bit(map)) {
308 hash = mhash_add(hash, *p);
309 hash_map |= rightmost_1bit(map);
313 hash = mhash_add(hash, hash_map);
314 hash = mhash_add(hash, hash_map >> 32);
316 return mhash_finish(hash, p - values);
319 /* Returns a hash value for 'mask', given 'basis'. */
320 static inline uint32_t
321 minimask_hash(const struct minimask *mask, uint32_t basis)
323 return miniflow_hash(&mask->masks, basis);
326 /* Returns a hash value for 'match', given 'basis'. */
327 static inline uint32_t
328 minimatch_hash(const struct minimatch *match, uint32_t basis)
330 return miniflow_hash(&match->flow, minimask_hash(&match->mask, basis));
333 /* Returns a hash value for the bits of range [start, end) in 'minimatch',
336 * The hash values returned by this function are the same as those returned by
337 * flow_hash_in_minimask_range(), only the form of the arguments differ. */
338 static inline uint32_t
339 minimatch_hash_range(const struct minimatch *match, uint8_t start, uint8_t end,
343 const uint32_t *p, *q;
344 uint32_t hash = *basis;
347 n = count_1bits(miniflow_get_map_in_range(&match->mask.masks, start, end,
349 q = miniflow_get_u32_values(&match->mask.masks) + offset;
350 p = miniflow_get_u32_values(&match->flow) + offset;
352 for (i = 0; i < n; i++) {
353 hash = mhash_add(hash, p[i] & q[i]);
355 *basis = hash; /* Allow continuation from the unfinished value. */
356 return mhash_finish(hash, (offset + n) * 4);
362 /* Initializes 'rule' to match packets specified by 'match' at the given
363 * 'priority'. 'match' must satisfy the invariant described in the comment at
364 * the definition of struct match.
366 * The caller must eventually destroy 'rule' with cls_rule_destroy().
368 * (OpenFlow uses priorities between 0 and UINT16_MAX, inclusive, but
369 * internally Open vSwitch supports a wider range.) */
371 cls_rule_init(struct cls_rule *rule,
372 const struct match *match, unsigned int priority)
374 minimatch_init(&rule->match, match);
375 rule->priority = priority;
376 rule->cls_match = NULL;
379 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
381 cls_rule_init_from_minimatch(struct cls_rule *rule,
382 const struct minimatch *match,
383 unsigned int priority)
385 minimatch_clone(&rule->match, match);
386 rule->priority = priority;
387 rule->cls_match = NULL;
390 /* Initializes 'dst' as a copy of 'src'.
392 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
394 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
396 minimatch_clone(&dst->match, &src->match);
397 dst->priority = src->priority;
398 dst->cls_match = NULL;
401 /* Initializes 'dst' with the data in 'src', destroying 'src'.
403 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
405 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
407 minimatch_move(&dst->match, &src->match);
408 dst->priority = src->priority;
409 dst->cls_match = NULL;
412 /* Frees memory referenced by 'rule'. Doesn't free 'rule' itself (it's
413 * normally embedded into a larger structure).
415 * ('rule' must not currently be in a classifier.) */
417 cls_rule_destroy(struct cls_rule *rule)
419 ovs_assert(!rule->cls_match);
420 minimatch_destroy(&rule->match);
423 /* Returns true if 'a' and 'b' match the same packets at the same priority,
424 * false if they differ in some way. */
426 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
428 return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
431 /* Returns a hash value for 'rule', folding in 'basis'. */
433 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
435 return minimatch_hash(&rule->match, hash_int(rule->priority, basis));
438 /* Appends a string describing 'rule' to 's'. */
440 cls_rule_format(const struct cls_rule *rule, struct ds *s)
442 minimatch_format(&rule->match, s, rule->priority);
445 /* Returns true if 'rule' matches every packet, false otherwise. */
447 cls_rule_is_catchall(const struct cls_rule *rule)
449 return minimask_is_catchall(&rule->match.mask);
452 /* Initializes 'cls' as a classifier that initially contains no classification
455 classifier_init(struct classifier *cls_, const uint8_t *flow_segments)
457 struct cls_classifier *cls = xmalloc(sizeof *cls);
459 fat_rwlock_init(&cls_->rwlock);
464 hmap_init(&cls->subtables_map);
465 pvector_init(&cls->subtables);
466 hmap_init(&cls->partitions);
467 cls->n_flow_segments = 0;
469 while (cls->n_flow_segments < CLS_MAX_INDICES
470 && *flow_segments < FLOW_U32S) {
471 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
477 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
478 * caller's responsibility. */
480 classifier_destroy(struct classifier *cls_)
483 struct cls_classifier *cls = cls_->cls;
484 struct cls_partition *partition, *next_partition;
485 struct cls_subtable *subtable, *next_subtable;
488 fat_rwlock_destroy(&cls_->rwlock);
493 for (i = 0; i < cls->n_tries; i++) {
494 trie_destroy(cls->tries[i].root);
497 HMAP_FOR_EACH_SAFE (subtable, next_subtable, hmap_node,
498 &cls->subtables_map) {
499 destroy_subtable(cls, subtable);
501 hmap_destroy(&cls->subtables_map);
503 HMAP_FOR_EACH_SAFE (partition, next_partition, hmap_node,
505 hmap_remove(&cls->partitions, &partition->hmap_node);
508 hmap_destroy(&cls->partitions);
510 pvector_destroy(&cls->subtables);
515 /* We use uint64_t as a set for the fields below. */
516 BUILD_ASSERT_DECL(MFF_N_IDS <= 64);
518 /* Set the fields for which prefix lookup should be performed. */
520 classifier_set_prefix_fields(struct classifier *cls_,
521 const enum mf_field_id *trie_fields,
522 unsigned int n_fields)
524 struct cls_classifier *cls = cls_->cls;
528 for (i = 0, trie = 0; i < n_fields && trie < CLS_MAX_TRIES; i++) {
529 const struct mf_field *field = mf_from_id(trie_fields[i]);
530 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
531 /* Incompatible field. This is the only place where we
532 * enforce these requirements, but the rest of the trie code
533 * depends on the flow_be32ofs to be non-negative and the
534 * field length to be a multiple of 32 bits. */
538 if (fields & (UINT64_C(1) << trie_fields[i])) {
539 /* Duplicate field, there is no need to build more than
540 * one index for any one field. */
543 fields |= UINT64_C(1) << trie_fields[i];
545 if (trie >= cls->n_tries || field != cls->tries[trie].field) {
546 trie_init(cls, trie, field);
551 /* Destroy the rest. */
552 for (i = trie; i < cls->n_tries; i++) {
553 trie_init(cls, i, NULL);
559 trie_init(struct cls_classifier *cls, int trie_idx,
560 const struct mf_field *field)
562 struct cls_trie *trie = &cls->tries[trie_idx];
563 struct cls_subtable *subtable;
565 if (trie_idx < cls->n_tries) {
566 trie_destroy(trie->root);
571 /* Add existing rules to the trie. */
572 HMAP_FOR_EACH (subtable, hmap_node, &cls->subtables_map) {
575 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
576 /* Initialize subtable's prefix length on this field. */
577 subtable->trie_plen[trie_idx] = plen;
580 struct cls_match *head;
582 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
583 struct cls_match *match;
585 FOR_EACH_RULE_IN_LIST (match, head) {
586 trie_insert(trie, match->cls_rule, plen);
593 /* Returns true if 'cls' contains no classification rules, false otherwise. */
595 classifier_is_empty(const struct classifier *cls)
597 return cls->cls->n_rules == 0;
600 /* Returns the number of rules in 'cls'. */
602 classifier_count(const struct classifier *cls)
604 return cls->cls->n_rules;
608 hash_metadata(ovs_be64 metadata_)
610 uint64_t metadata = (OVS_FORCE uint64_t) metadata_;
611 return hash_uint64(metadata);
614 static struct cls_partition *
615 find_partition(const struct cls_classifier *cls, ovs_be64 metadata,
618 struct cls_partition *partition;
620 HMAP_FOR_EACH_IN_BUCKET (partition, hmap_node, hash, &cls->partitions) {
621 if (partition->metadata == metadata) {
629 static struct cls_partition *
630 create_partition(struct cls_classifier *cls, struct cls_subtable *subtable,
633 uint32_t hash = hash_metadata(metadata);
634 struct cls_partition *partition = find_partition(cls, metadata, hash);
636 partition = xmalloc(sizeof *partition);
637 partition->metadata = metadata;
639 tag_tracker_init(&partition->tracker);
640 hmap_insert(&cls->partitions, &partition->hmap_node, hash);
642 tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
646 static inline ovs_be32 minimatch_get_ports(const struct minimatch *match)
648 /* Could optimize to use the same map if needed for fast path. */
649 return MINIFLOW_GET_BE32(&match->flow, tp_src)
650 & MINIFLOW_GET_BE32(&match->mask.masks, tp_src);
653 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
654 * must not modify or free it.
656 * If 'cls' already contains an identical rule (including wildcards, values of
657 * fixed fields, and priority), replaces the old rule by 'rule' and returns the
658 * rule that was replaced. The caller takes ownership of the returned rule and
659 * is thus responsible for destroying it with cls_rule_destroy(), freeing the
660 * memory block in which it resides, etc., as necessary.
662 * Returns NULL if 'cls' does not contain a rule with an identical key, after
663 * inserting the new rule. In this case, no rules are displaced by the new
664 * rule, even rules that cannot have any effect because the new rule matches a
665 * superset of their flows and has higher priority. */
667 classifier_replace(struct classifier *cls_, struct cls_rule *rule)
669 struct cls_classifier *cls = cls_->cls;
670 struct cls_match *old_rule;
671 struct cls_subtable *subtable;
673 subtable = find_subtable(cls, &rule->match.mask);
675 subtable = insert_subtable(cls, &rule->match.mask);
678 old_rule = insert_rule(cls, subtable, rule);
682 rule->cls_match->partition = NULL;
683 if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
684 ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
685 rule->cls_match->partition = create_partition(cls, subtable,
691 for (i = 0; i < cls->n_tries; i++) {
692 if (subtable->trie_plen[i]) {
693 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
698 if (subtable->ports_mask_len) {
699 /* We mask the value to be inserted to always have the wildcarded
700 * bits in known (zero) state, so we can include them in comparison
701 * and they will always match (== their original value does not
703 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
705 trie_insert_prefix(&subtable->ports_trie, &masked_ports,
706 subtable->ports_mask_len);
711 struct cls_rule *old_cls_rule = old_rule->cls_rule;
713 rule->cls_match->partition = old_rule->partition;
714 old_cls_rule->cls_match = NULL;
720 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
721 * must not modify or free it.
723 * 'cls' must not contain an identical rule (including wildcards, values of
724 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
727 classifier_insert(struct classifier *cls, struct cls_rule *rule)
729 struct cls_rule *displaced_rule = classifier_replace(cls, rule);
730 ovs_assert(!displaced_rule);
733 /* Removes 'rule' from 'cls'. It is the caller's responsibility to destroy
734 * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
735 * resides, etc., as necessary. */
737 classifier_remove(struct classifier *cls_, struct cls_rule *rule)
739 struct cls_classifier *cls = cls_->cls;
740 struct cls_partition *partition;
741 struct cls_match *cls_match = rule->cls_match;
742 struct cls_match *head;
743 struct cls_subtable *subtable;
746 ovs_assert(cls_match);
748 subtable = find_subtable(cls, &rule->match.mask);
749 ovs_assert(subtable);
751 if (subtable->ports_mask_len) {
752 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
754 trie_remove_prefix(&subtable->ports_trie,
755 &masked_ports, subtable->ports_mask_len);
757 for (i = 0; i < cls->n_tries; i++) {
758 if (subtable->trie_plen[i]) {
759 trie_remove(&cls->tries[i], rule, subtable->trie_plen[i]);
763 /* Remove rule node from indices. */
764 for (i = 0; i < subtable->n_indices; i++) {
765 hindex_remove(&subtable->indices[i], &cls_match->index_nodes[i]);
768 head = find_equal(subtable, &rule->match.flow, cls_match->hmap_node.hash);
769 if (head != cls_match) {
770 list_remove(&cls_match->list);
771 } else if (list_is_empty(&cls_match->list)) {
772 hmap_remove(&subtable->rules, &cls_match->hmap_node);
774 struct cls_match *next = CONTAINER_OF(cls_match->list.next,
775 struct cls_match, list);
777 list_remove(&cls_match->list);
778 hmap_replace(&subtable->rules, &cls_match->hmap_node,
782 partition = cls_match->partition;
784 tag_tracker_subtract(&partition->tracker, &partition->tags,
786 if (!partition->tags) {
787 hmap_remove(&cls->partitions, &partition->hmap_node);
792 if (--subtable->n_rules == 0) {
793 destroy_subtable(cls, subtable);
794 } else if (subtable->max_priority == cls_match->priority
795 && --subtable->max_count == 0) {
796 /* Find the new 'max_priority' and 'max_count'. */
797 struct cls_match *head;
798 unsigned int max_priority = 0;
800 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
801 if (head->priority > max_priority) {
802 max_priority = head->priority;
803 subtable->max_count = 1;
804 } else if (head->priority == max_priority) {
805 ++subtable->max_count;
808 subtable->max_priority = max_priority;
809 pvector_change_priority(&cls->subtables, subtable, max_priority);
814 rule->cls_match = NULL;
818 /* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
819 * subtables which have more than 'match_plen' bits in their corresponding
820 * field at offset 'be32ofs'. If skipped, 'maskbits' prefix bits should be
821 * unwildcarded to quarantee datapath flow matches only packets it should. */
823 const struct cls_trie *trie;
824 bool lookup_done; /* Status of the lookup. */
825 uint8_t be32ofs; /* U32 offset of the field in question. */
826 unsigned int match_plen; /* Longest prefix than could possibly match. */
827 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
831 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
834 ctx->be32ofs = trie->field->flow_be32ofs;
835 ctx->lookup_done = false;
838 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
839 * Returns a null pointer if no rules in 'cls' match 'flow'. If multiple rules
840 * of equal priority match 'flow', returns one arbitrarily.
842 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
843 * set of bits that were significant in the lookup. At some point
844 * earlier, 'wc' should have been initialized (e.g., by
845 * flow_wildcards_init_catchall()). */
847 classifier_lookup(const struct classifier *cls_, const struct flow *flow,
848 struct flow_wildcards *wc)
850 struct cls_classifier *cls = cls_->cls;
851 const struct cls_partition *partition;
853 int64_t best_priority = -1;
854 const struct cls_match *best;
855 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
856 struct cls_subtable *subtable;
858 /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
859 * then 'flow' cannot possibly match in 'subtable':
861 * - If flow->metadata maps to a given 'partition', then we can use
862 * 'tags' for 'partition->tags'.
864 * - If flow->metadata has no partition, then no rule in 'cls' has an
865 * exact-match for flow->metadata. That means that we don't need to
866 * search any subtable that includes flow->metadata in its mask.
868 * In either case, we always need to search any cls_subtables that do not
869 * include flow->metadata in its mask. One way to do that would be to
870 * check the "cls_subtable"s explicitly for that, but that would require an
871 * extra branch per subtable. Instead, we mark such a cls_subtable's
872 * 'tags' as TAG_ALL and make sure that 'tags' is never empty. This means
873 * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
874 * need a special case.
876 partition = (hmap_is_empty(&cls->partitions)
878 : find_partition(cls, flow->metadata,
879 hash_metadata(flow->metadata)));
880 tags = partition ? partition->tags : TAG_ARBITRARY;
882 /* Initialize trie contexts for match_find_wc(). */
883 for (int i = 0; i < cls->n_tries; i++) {
884 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
888 PVECTOR_FOR_EACH_PRIORITY(subtable, best_priority, 2,
889 sizeof(struct cls_subtable), &cls->subtables) {
890 struct cls_match *rule;
892 if (!tag_intersects(tags, subtable->tag)) {
896 rule = find_match_wc(subtable, flow, trie_ctx, cls->n_tries, wc);
897 if (rule && (int64_t)rule->priority > best_priority) {
898 best_priority = (int64_t)rule->priority;
903 return best ? best->cls_rule : NULL;
906 /* Returns true if 'target' satisifies 'match', that is, if each bit for which
907 * 'match' specifies a particular value has the correct value in 'target'.
909 * 'flow' and 'mask' have the same mask! */
911 miniflow_and_mask_matches_miniflow(const struct miniflow *flow,
912 const struct minimask *mask,
913 const struct miniflow *target)
915 const uint32_t *flowp = miniflow_get_u32_values(flow);
916 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
919 MINIFLOW_FOR_EACH_IN_MAP(target_u32, target, mask->masks.map) {
920 if ((*flowp++ ^ target_u32) & *maskp++) {
928 static inline struct cls_match *
929 find_match_miniflow(const struct cls_subtable *subtable,
930 const struct miniflow *flow,
933 struct cls_match *rule;
935 HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &subtable->rules) {
936 if (miniflow_and_mask_matches_miniflow(&rule->flow, &subtable->mask,
945 /* Finds and returns the highest-priority rule in 'cls' that matches
946 * 'miniflow'. Returns a null pointer if no rules in 'cls' match 'flow'.
947 * If multiple rules of equal priority match 'flow', returns one arbitrarily.
949 * This function is optimized for the userspace datapath, which only ever has
950 * one priority value for it's flows!
952 struct cls_rule *classifier_lookup_miniflow_first(const struct classifier *cls_,
953 const struct miniflow *flow)
955 struct cls_classifier *cls = cls_->cls;
956 struct cls_subtable *subtable;
958 PVECTOR_FOR_EACH (subtable, &cls->subtables) {
959 struct cls_match *rule;
961 rule = find_match_miniflow(subtable, flow,
962 miniflow_hash_in_minimask(flow,
966 return rule->cls_rule;
973 /* Finds and returns a rule in 'cls' with exactly the same priority and
974 * matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
975 * contain an exact match. */
977 classifier_find_rule_exactly(const struct classifier *cls_,
978 const struct cls_rule *target)
980 struct cls_classifier *cls = cls_->cls;
981 struct cls_match *head, *rule;
982 struct cls_subtable *subtable;
984 subtable = find_subtable(cls, &target->match.mask);
989 /* Skip if there is no hope. */
990 if (target->priority > subtable->max_priority) {
994 head = find_equal(subtable, &target->match.flow,
995 miniflow_hash_in_minimask(&target->match.flow,
996 &target->match.mask, 0));
997 FOR_EACH_RULE_IN_LIST (rule, head) {
998 if (target->priority >= rule->priority) {
999 return target->priority == rule->priority ? rule->cls_rule : NULL;
1005 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
1006 * same matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
1007 * contain an exact match. */
1009 classifier_find_match_exactly(const struct classifier *cls,
1010 const struct match *target,
1011 unsigned int priority)
1013 struct cls_rule *retval;
1016 cls_rule_init(&cr, target, priority);
1017 retval = classifier_find_rule_exactly(cls, &cr);
1018 cls_rule_destroy(&cr);
1023 /* Checks if 'target' would overlap any other rule in 'cls'. Two rules are
1024 * considered to overlap if both rules have the same priority and a packet
1025 * could match both. */
1027 classifier_rule_overlaps(const struct classifier *cls_,
1028 const struct cls_rule *target)
1030 struct cls_classifier *cls = cls_->cls;
1031 struct cls_subtable *subtable;
1032 int64_t stop_at_priority = (int64_t)target->priority - 1;
1034 /* Iterate subtables in the descending max priority order. */
1035 PVECTOR_FOR_EACH_PRIORITY (subtable, stop_at_priority, 2,
1036 sizeof(struct cls_subtable), &cls->subtables) {
1037 uint32_t storage[FLOW_U32S];
1038 struct minimask mask;
1039 struct cls_match *head;
1041 minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
1042 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
1043 struct cls_match *rule;
1045 FOR_EACH_RULE_IN_LIST (rule, head) {
1046 if (rule->priority < target->priority) {
1047 break; /* Rules in descending priority order. */
1049 if (rule->priority == target->priority
1050 && miniflow_equal_in_minimask(&target->match.flow,
1051 &rule->flow, &mask)) {
1061 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
1062 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
1063 * function returns true if, for every field:
1065 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
1068 * - 'criteria' wildcards the field,
1070 * Conversely, 'rule' does not match 'criteria' and this function returns false
1071 * if, for at least one field:
1073 * - 'criteria' and 'rule' specify different values for the field, or
1075 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
1077 * Equivalently, the truth table for whether a field matches is:
1082 * r +---------+---------+
1083 * i wild | yes | yes |
1085 * e +---------+---------+
1086 * r exact | no |if values|
1088 * a +---------+---------+
1090 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
1091 * commands and by OpenFlow 1.0 aggregate and flow stats.
1093 * Ignores rule->priority. */
1095 cls_rule_is_loose_match(const struct cls_rule *rule,
1096 const struct minimatch *criteria)
1098 return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
1099 && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
1106 rule_matches(const struct cls_match *rule, const struct cls_rule *target)
1109 || miniflow_equal_in_minimask(&rule->flow,
1110 &target->match.flow,
1111 &target->match.mask));
1114 static struct cls_match *
1115 search_subtable(const struct cls_subtable *subtable,
1116 const struct cls_rule *target)
1118 if (!target || !minimask_has_extra(&subtable->mask, &target->match.mask)) {
1119 struct cls_match *rule;
1121 HMAP_FOR_EACH (rule, hmap_node, &subtable->rules) {
1122 if (rule_matches(rule, target)) {
1130 /* Initializes 'cursor' for iterating through rules in 'cls':
1132 * - If 'target' is null, the cursor will visit every rule in 'cls'.
1134 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1135 * such that cls_rule_is_loose_match(rule, target) returns true.
1137 * Ignores target->priority. */
1139 cls_cursor_init(struct cls_cursor *cursor, const struct classifier *cls,
1140 const struct cls_rule *target)
1142 cursor->cls = cls->cls;
1143 cursor->target = target && !cls_rule_is_catchall(target) ? target : NULL;
1146 /* Returns the first matching cls_rule in 'cursor''s iteration, or a null
1147 * pointer if there are no matches. */
1149 cls_cursor_first(struct cls_cursor *cursor)
1151 struct cls_subtable *subtable;
1153 HMAP_FOR_EACH (subtable, hmap_node, &cursor->cls->subtables_map) {
1154 struct cls_match *rule = search_subtable(subtable, cursor->target);
1156 cursor->subtable = subtable;
1157 return rule->cls_rule;
1164 /* Returns the next matching cls_rule in 'cursor''s iteration, or a null
1165 * pointer if there are no more matches. */
1167 cls_cursor_next(struct cls_cursor *cursor, const struct cls_rule *rule_)
1169 struct cls_match *rule = CONST_CAST(struct cls_match *, rule_->cls_match);
1170 const struct cls_subtable *subtable;
1171 struct cls_match *next;
1173 next = next_rule_in_list__(rule);
1174 if (next->priority < rule->priority) {
1175 return next->cls_rule;
1178 /* 'next' is the head of the list, that is, the rule that is included in
1179 * the subtable's hmap. (This is important when the classifier contains
1180 * rules that differ only in priority.) */
1182 HMAP_FOR_EACH_CONTINUE (rule, hmap_node, &cursor->subtable->rules) {
1183 if (rule_matches(rule, cursor->target)) {
1184 return rule->cls_rule;
1188 subtable = cursor->subtable;
1189 HMAP_FOR_EACH_CONTINUE (subtable, hmap_node, &cursor->cls->subtables_map) {
1190 rule = search_subtable(subtable, cursor->target);
1192 cursor->subtable = subtable;
1193 return rule->cls_rule;
1200 static struct cls_subtable *
1201 find_subtable(const struct cls_classifier *cls, const struct minimask *mask)
1203 struct cls_subtable *subtable;
1205 HMAP_FOR_EACH_IN_BUCKET (subtable, hmap_node, minimask_hash(mask, 0),
1206 &cls->subtables_map) {
1207 if (minimask_equal(mask, &subtable->mask)) {
1214 static struct cls_subtable *
1215 insert_subtable(struct cls_classifier *cls, const struct minimask *mask)
1217 uint32_t hash = minimask_hash(mask, 0);
1218 struct cls_subtable *subtable;
1220 struct flow_wildcards old, new;
1222 int count = count_1bits(mask->masks.map);
1224 subtable = xzalloc(sizeof *subtable - sizeof mask->masks.inline_values
1225 + MINIFLOW_VALUES_SIZE(count));
1226 hmap_init(&subtable->rules);
1227 miniflow_clone_inline(&subtable->mask.masks, &mask->masks, count);
1229 /* Init indices for segmented lookup, if any. */
1230 flow_wildcards_init_catchall(&new);
1233 for (i = 0; i < cls->n_flow_segments; i++) {
1234 flow_wildcards_fold_minimask_range(&new, mask, prev,
1235 cls->flow_segments[i]);
1236 /* Add an index if it adds mask bits. */
1237 if (!flow_wildcards_equal(&new, &old)) {
1238 hindex_init(&subtable->indices[index]);
1239 subtable->index_ofs[index] = cls->flow_segments[i];
1243 prev = cls->flow_segments[i];
1245 /* Check if the rest of the subtable's mask adds any bits,
1246 * and remove the last index if it doesn't. */
1248 flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U32S);
1249 if (flow_wildcards_equal(&new, &old)) {
1251 subtable->index_ofs[index] = 0;
1252 hindex_destroy(&subtable->indices[index]);
1255 subtable->n_indices = index;
1257 subtable->tag = (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1258 ? tag_create_deterministic(hash)
1261 for (i = 0; i < cls->n_tries; i++) {
1262 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1263 cls->tries[i].field);
1267 subtable->ports_trie = NULL;
1268 subtable->ports_mask_len
1269 = 32 - ctz32(ntohl(MINIFLOW_GET_BE32(&mask->masks, tp_src)));
1271 hmap_insert(&cls->subtables_map, &subtable->hmap_node, hash);
1277 destroy_subtable(struct cls_classifier *cls, struct cls_subtable *subtable)
1281 pvector_remove(&cls->subtables, subtable);
1282 trie_destroy(subtable->ports_trie);
1284 for (i = 0; i < subtable->n_indices; i++) {
1285 hindex_destroy(&subtable->indices[i]);
1287 hmap_remove(&cls->subtables_map, &subtable->hmap_node);
1288 minimask_destroy(&subtable->mask);
1289 hmap_destroy(&subtable->rules);
1290 ovsrcu_postpone(free, subtable);
1298 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1299 * lookup results. */
1301 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1302 const unsigned int field_plen[CLS_MAX_TRIES],
1303 const struct range ofs, const struct flow *flow,
1304 struct flow_wildcards *wc)
1308 /* Check if we could avoid fully unwildcarding the next level of
1309 * fields using the prefix tries. The trie checks are done only as
1310 * needed to avoid folding in additional bits to the wildcards mask. */
1311 for (j = 0; j < n_tries; j++) {
1312 /* Is the trie field relevant for this subtable? */
1313 if (field_plen[j]) {
1314 struct trie_ctx *ctx = &trie_ctx[j];
1315 uint8_t be32ofs = ctx->be32ofs;
1317 /* Is the trie field within the current range of fields? */
1318 if (be32ofs >= ofs.start && be32ofs < ofs.end) {
1319 /* On-demand trie lookup. */
1320 if (!ctx->lookup_done) {
1321 ctx->match_plen = trie_lookup(ctx->trie, flow,
1323 ctx->lookup_done = true;
1325 /* Possible to skip the rest of the subtable if subtable's
1326 * prefix on the field is longer than what is known to match
1327 * based on the trie lookup. */
1328 if (field_plen[j] > ctx->match_plen) {
1329 /* RFC: We want the trie lookup to never result in
1330 * unwildcarding any bits that would not be unwildcarded
1331 * otherwise. Since the trie is shared by the whole
1332 * classifier, it is possible that the 'maskbits' contain
1333 * bits that are irrelevant for the partition of the
1334 * classifier relevant for the current flow. */
1336 /* Can skip if the field is already unwildcarded. */
1337 if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1340 /* Check that the trie result will not unwildcard more bits
1341 * than this stage will. */
1342 if (ctx->maskbits <= field_plen[j]) {
1343 /* Unwildcard the bits and skip the rest. */
1344 mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1345 /* Note: Prerequisite already unwildcarded, as the only
1346 * prerequisite of the supported trie lookup fields is
1347 * the ethertype, which is currently always
1359 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1360 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1361 * value has the correct value in 'target'.
1363 * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
1364 * target, mask) but this is faster because of the invariant that
1365 * flow->map and mask->masks.map are the same, and that this version
1366 * takes the 'wc'. */
1368 miniflow_and_mask_matches_flow(const struct miniflow *flow,
1369 const struct minimask *mask,
1370 const struct flow *target)
1372 const uint32_t *flowp = miniflow_get_u32_values(flow);
1373 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1376 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1377 uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & *maskp++;
1387 static inline struct cls_match *
1388 find_match(const struct cls_subtable *subtable, const struct flow *flow,
1391 struct cls_match *rule;
1393 HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &subtable->rules) {
1394 if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
1403 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1404 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1405 * value has the correct value in 'target'.
1407 * This function is equivalent to miniflow_and_mask_matches_flow() but this
1408 * version fills in the mask bits in 'wc'. */
1410 miniflow_and_mask_matches_flow_wc(const struct miniflow *flow,
1411 const struct minimask *mask,
1412 const struct flow *target,
1413 struct flow_wildcards *wc)
1415 const uint32_t *flowp = miniflow_get_u32_values(flow);
1416 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1419 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1420 uint32_t mask = *maskp++;
1421 uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & mask;
1424 /* Only unwildcard if none of the differing bits is already
1426 if (!(flow_u32_value(&wc->masks, idx) & diff)) {
1427 /* Keep one bit of the difference. */
1428 *flow_u32_lvalue(&wc->masks, idx) |= rightmost_1bit(diff);
1432 /* Fill in the bits that were looked at. */
1433 *flow_u32_lvalue(&wc->masks, idx) |= mask;
1439 /* Unwildcard the fields looked up so far, if any. */
1441 fill_range_wc(const struct cls_subtable *subtable, struct flow_wildcards *wc,
1445 flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, to);
1449 static struct cls_match *
1450 find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
1451 struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1452 struct flow_wildcards *wc)
1454 uint32_t basis = 0, hash;
1455 struct cls_match *rule;
1459 if (OVS_UNLIKELY(!wc)) {
1460 return find_match(subtable, flow,
1461 flow_hash_in_minimask(flow, &subtable->mask, 0));
1465 /* Try to finish early by checking fields in segments. */
1466 for (i = 0; i < subtable->n_indices; i++) {
1467 struct hindex_node *inode;
1468 ofs.end = subtable->index_ofs[i];
1470 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1472 /* 'wc' bits for the trie field set, now unwildcard the preceding
1473 * bits used so far. */
1474 fill_range_wc(subtable, wc, ofs.start);
1477 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1479 inode = hindex_node_with_hash(&subtable->indices[i], hash);
1481 /* No match, can stop immediately, but must fold in the bits
1482 * used in lookup so far. */
1483 fill_range_wc(subtable, wc, ofs.end);
1487 /* If we have narrowed down to a single rule already, check whether
1488 * that rule matches. Either way, we're done.
1490 * (Rare) hash collisions may cause us to miss the opportunity for this
1493 ASSIGN_CONTAINER(rule, inode - i, index_nodes);
1494 if (miniflow_and_mask_matches_flow_wc(&rule->flow, &subtable->mask,
1500 ofs.start = ofs.end;
1502 ofs.end = FLOW_U32S;
1503 /* Trie check for the final range. */
1504 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1505 fill_range_wc(subtable, wc, ofs.start);
1508 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1510 rule = find_match(subtable, flow, hash);
1511 if (!rule && subtable->ports_mask_len) {
1512 /* Ports are always part of the final range, if any.
1513 * No match was found for the ports. Use the ports trie to figure out
1514 * which ports bits to unwildcard. */
1516 ovs_be32 value, mask;
1518 mask = MINIFLOW_GET_BE32(&subtable->mask.masks, tp_src);
1519 value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
1520 trie_lookup_value(subtable->ports_trie, &value, 32, &mbits);
1522 ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
1523 mask & htonl(~0 << (32 - mbits));
1525 /* Unwildcard all bits in the mask upto the ports, as they were used
1526 * to determine there is no match. */
1527 fill_range_wc(subtable, wc, TP_PORTS_OFS32);
1531 /* Must unwildcard all the fields, as they were looked at. */
1532 flow_wildcards_fold_minimask(wc, &subtable->mask);
1536 static struct cls_match *
1537 find_equal(struct cls_subtable *subtable, const struct miniflow *flow,
1540 struct cls_match *head;
1542 HMAP_FOR_EACH_WITH_HASH (head, hmap_node, hash, &subtable->rules) {
1543 if (miniflow_equal(&head->flow, flow)) {
1550 static struct cls_match *
1551 insert_rule(struct cls_classifier *cls, struct cls_subtable *subtable,
1552 struct cls_rule *new)
1554 struct cls_match *cls_match = cls_match_alloc(new);
1555 struct cls_match *head;
1556 struct cls_match *old = NULL;
1558 uint32_t basis = 0, hash;
1559 uint8_t prev_be32ofs = 0;
1561 /* Add new node to segment indices. */
1562 for (i = 0; i < subtable->n_indices; i++) {
1563 hash = minimatch_hash_range(&new->match, prev_be32ofs,
1564 subtable->index_ofs[i], &basis);
1565 hindex_insert(&subtable->indices[i], &cls_match->index_nodes[i], hash);
1566 prev_be32ofs = subtable->index_ofs[i];
1568 hash = minimatch_hash_range(&new->match, prev_be32ofs, FLOW_U32S, &basis);
1569 head = find_equal(subtable, &new->match.flow, hash);
1571 hmap_insert(&subtable->rules, &cls_match->hmap_node, hash);
1572 list_init(&cls_match->list);
1575 /* Scan the list for the insertion point that will keep the list in
1576 * order of decreasing priority. */
1577 struct cls_match *rule;
1579 cls_match->hmap_node.hash = hash; /* Otherwise done by hmap_insert. */
1581 FOR_EACH_RULE_IN_LIST (rule, head) {
1582 if (cls_match->priority >= rule->priority) {
1584 /* 'cls_match' is the new highest-priority flow in the
1586 hmap_replace(&subtable->rules,
1587 &rule->hmap_node, &cls_match->hmap_node);
1590 if (cls_match->priority == rule->priority) {
1591 list_replace(&cls_match->list, &rule->list);
1594 list_insert(&rule->list, &cls_match->list);
1600 /* Insert 'new' at the end of the list. */
1601 list_push_back(&head->list, &cls_match->list);
1606 subtable->n_rules++;
1608 /* Rule was added, not replaced. Update 'subtable's 'max_priority'
1609 * and 'max_count', if necessary. */
1610 if (subtable->n_rules == 1) {
1611 subtable->max_priority = cls_match->priority;
1612 subtable->max_count = 1;
1613 pvector_insert(&cls->subtables, subtable, cls_match->priority);
1614 } else if (subtable->max_priority == cls_match->priority) {
1615 ++subtable->max_count;
1616 } else if (cls_match->priority > subtable->max_priority) {
1617 subtable->max_priority = cls_match->priority;
1618 subtable->max_count = 1;
1619 pvector_change_priority(&cls->subtables, subtable, cls_match->priority);
1622 /* Remove old node from indices. */
1623 for (i = 0; i < subtable->n_indices; i++) {
1624 hindex_remove(&subtable->indices[i], &old->index_nodes[i]);
1630 static struct cls_match *
1631 next_rule_in_list__(struct cls_match *rule)
1633 struct cls_match *next = OBJECT_CONTAINING(rule->list.next, next, list);
1637 static struct cls_match *
1638 next_rule_in_list(struct cls_match *rule)
1640 struct cls_match *next = next_rule_in_list__(rule);
1641 return next->priority < rule->priority ? next : NULL;
1644 /* A longest-prefix match tree. */
1646 uint32_t prefix; /* Prefix bits for this node, MSB first. */
1647 uint8_t nbits; /* Never zero, except for the root node. */
1648 unsigned int n_rules; /* Number of rules that have this prefix. */
1649 struct trie_node *edges[2]; /* Both NULL if leaf. */
1652 /* Max bits per node. Must fit in struct trie_node's 'prefix'.
1653 * Also tested with 16, 8, and 5 to stress the implementation. */
1654 #define TRIE_PREFIX_BITS 32
1656 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1657 * Prefixes are in the network byte order, and the offset 0 corresponds to
1658 * the most significant bit of the first byte. The offset can be read as
1659 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1661 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1665 pr += ofs / 32; /* Where to start. */
1666 ofs %= 32; /* How many bits to skip at 'pr'. */
1668 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1669 if (plen > 32 - ofs) { /* Need more than we have already? */
1670 prefix |= ntohl(*++pr) >> (32 - ofs);
1672 /* Return with possible unwanted bits at the end. */
1676 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1677 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1678 * corresponds to the most significant bit of the first byte. The offset can
1679 * be read as "how many bits to skip from the start of the prefix starting at
1682 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1687 if (plen > TRIE_PREFIX_BITS) {
1688 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1690 /* Return with unwanted bits cleared. */
1691 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1694 /* Return the number of equal bits in 'nbits' of 'prefix's MSBs and a 'value'
1695 * starting at "MSB 0"-based offset 'ofs'. */
1697 prefix_equal_bits(uint32_t prefix, unsigned int nbits, const ovs_be32 value[],
1700 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, nbits);
1701 /* Set the bit after the relevant bits to limit the result. */
1702 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - nbits));
1705 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1706 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1708 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1709 unsigned int ofs, unsigned int plen)
1711 return prefix_equal_bits(node->prefix, MIN(node->nbits, plen - ofs),
1715 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1716 * be greater than 31. */
1718 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1720 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1723 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1724 * be between 0 and 31, inclusive. */
1726 get_bit_at(const uint32_t prefix, unsigned int ofs)
1728 return (prefix >> (31 - ofs)) & 1u;
1731 /* Create new branch. */
1732 static struct trie_node *
1733 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1734 unsigned int n_rules)
1736 struct trie_node *node = xmalloc(sizeof *node);
1738 node->prefix = trie_get_prefix(prefix, ofs, plen);
1740 if (plen <= TRIE_PREFIX_BITS) {
1742 node->edges[0] = NULL;
1743 node->edges[1] = NULL;
1744 node->n_rules = n_rules;
1745 } else { /* Need intermediate nodes. */
1746 struct trie_node *subnode = trie_branch_create(prefix,
1747 ofs + TRIE_PREFIX_BITS,
1748 plen - TRIE_PREFIX_BITS,
1750 int bit = get_bit_at(subnode->prefix, 0);
1751 node->nbits = TRIE_PREFIX_BITS;
1752 node->edges[bit] = subnode;
1753 node->edges[!bit] = NULL;
1760 trie_node_destroy(struct trie_node *node)
1766 trie_destroy(struct trie_node *node)
1769 trie_destroy(node->edges[0]);
1770 trie_destroy(node->edges[1]);
1776 trie_is_leaf(const struct trie_node *trie)
1778 return !trie->edges[0] && !trie->edges[1]; /* No children. */
1782 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1785 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1788 for (i = 0; i < nbits / 32; i++) {
1789 mask[i] = OVS_BE32_MAX;
1792 mask[i] |= htonl(~0u << (32 - nbits % 32));
1797 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
1800 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1802 ovs_be32 zeroes = 0;
1804 for (i = 0; i < nbits / 32; i++) {
1808 zeroes |= ~mask[i] & htonl(~0u << (32 - nbits % 32));
1811 return !zeroes; /* All 'nbits' bits set. */
1814 static struct trie_node **
1815 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
1818 return node->edges + be_get_bit_at(value, ofs);
1821 static const struct trie_node *
1822 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
1825 return node->edges[be_get_bit_at(value, ofs)];
1828 /* Return the prefix mask length necessary to find the longest-prefix match for
1829 * the '*value' in the prefix tree 'node'.
1830 * '*checkbits' is set to the number of bits in the prefix mask necessary to
1831 * determine a mismatch, in case there are longer prefixes in the tree below
1832 * the one that matched.
1835 trie_lookup_value(const struct trie_node *node, const ovs_be32 value[],
1836 unsigned int n_bits, unsigned int *checkbits)
1838 unsigned int ofs = 0, match_len = 0;
1839 const struct trie_node *prev = NULL;
1841 for (; node; prev = node, node = trie_next_node(node, value, ofs)) {
1842 unsigned int eqbits;
1843 /* Check if this edge can be followed. */
1844 eqbits = prefix_equal_bits(node->prefix, node->nbits, value, ofs);
1846 if (eqbits < node->nbits) { /* Mismatch, nothing more to be found. */
1847 /* Bit at offset 'ofs' differed. */
1848 *checkbits = ofs + 1; /* Includes the first mismatching bit. */
1851 /* Full match, check if rules exist at this prefix length. */
1852 if (node->n_rules > 0) {
1855 if (ofs >= n_bits) {
1856 *checkbits = n_bits; /* Full prefix. */
1860 /* node == NULL. Full match so far, but we came to a dead end.
1861 * need to exclude the other branch if it exists. */
1862 *checkbits = !prev || trie_is_leaf(prev) ? ofs : ofs + 1;
1867 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
1868 unsigned int *checkbits)
1870 const struct mf_field *mf = trie->field;
1872 /* Check that current flow matches the prerequisites for the trie
1873 * field. Some match fields are used for multiple purposes, so we
1874 * must check that the trie is relevant for this flow. */
1875 if (mf_are_prereqs_ok(mf, flow)) {
1876 return trie_lookup_value(trie->root,
1877 &((ovs_be32 *)flow)[mf->flow_be32ofs],
1878 mf->n_bits, checkbits);
1880 *checkbits = 0; /* Value not used in this case. */
1884 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
1885 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
1886 * 'miniflow_index' is not NULL. */
1888 minimask_get_prefix_len(const struct minimask *minimask,
1889 const struct mf_field *mf)
1891 unsigned int nbits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
1892 uint8_t u32_ofs = mf->flow_be32ofs;
1893 uint8_t u32_end = u32_ofs + mf->n_bytes / 4;
1895 for (; u32_ofs < u32_end; ++u32_ofs) {
1897 mask = ntohl((OVS_FORCE ovs_be32)minimask_get(minimask, u32_ofs));
1899 /* Validate mask, count the mask length. */
1902 return 0; /* No bits allowed after mask ended. */
1905 if (~mask & (~mask + 1)) {
1906 return 0; /* Mask not contiguous. */
1908 mask_tz = ctz32(mask);
1909 nbits += 32 - mask_tz;
1917 * This is called only when mask prefix is known to be CIDR and non-zero.
1918 * Relies on the fact that the flow and mask have the same map, and since
1919 * the mask is CIDR, the storage for the flow field exists even if it
1920 * happened to be zeros.
1922 static const ovs_be32 *
1923 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
1925 return miniflow_get_be32_values(&match->flow) +
1926 count_1bits(match->flow.map & ((UINT64_C(1) << mf->flow_be32ofs) - 1));
1929 /* Insert rule in to the prefix tree.
1930 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1933 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1935 trie_insert_prefix(&trie->root,
1936 minimatch_get_prefix(&rule->match, trie->field), mlen);
1940 trie_insert_prefix(struct trie_node **edge, const ovs_be32 *prefix, int mlen)
1942 struct trie_node *node;
1945 /* Walk the tree. */
1946 for (; (node = *edge) != NULL;
1947 edge = trie_next_edge(node, prefix, ofs)) {
1948 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1950 if (eqbits < node->nbits) {
1951 /* Mismatch, new node needs to be inserted above. */
1952 int old_branch = get_bit_at(node->prefix, eqbits);
1954 /* New parent node. */
1955 *edge = trie_branch_create(prefix, ofs - eqbits, eqbits,
1956 ofs == mlen ? 1 : 0);
1958 /* Adjust old node for its new position in the tree. */
1959 node->prefix <<= eqbits;
1960 node->nbits -= eqbits;
1961 (*edge)->edges[old_branch] = node;
1963 /* Check if need a new branch for the new rule. */
1965 (*edge)->edges[!old_branch]
1966 = trie_branch_create(prefix, ofs, mlen - ofs, 1);
1970 /* Full match so far. */
1973 /* Full match at the current node, rule needs to be added here. */
1978 /* Must insert a new tree branch for the new rule. */
1979 *edge = trie_branch_create(prefix, ofs, mlen - ofs, 1);
1982 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1985 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1987 trie_remove_prefix(&trie->root,
1988 minimatch_get_prefix(&rule->match, trie->field), mlen);
1991 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1994 trie_remove_prefix(struct trie_node **root, const ovs_be32 *prefix, int mlen)
1996 struct trie_node *node;
1997 struct trie_node **edges[sizeof(union mf_value) * 8];
1998 int depth = 0, ofs = 0;
2000 /* Walk the tree. */
2001 for (edges[0] = root;
2002 (node = *edges[depth]) != NULL;
2003 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
2004 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2006 if (eqbits < node->nbits) {
2007 /* Mismatch, nothing to be removed. This should never happen, as
2008 * only rules in the classifier are ever removed. */
2009 break; /* Log a warning. */
2011 /* Full match so far. */
2015 /* Full prefix match at the current node, remove rule here. */
2016 if (!node->n_rules) {
2017 break; /* Log a warning. */
2021 /* Check if can prune the tree. */
2022 while (!node->n_rules && !(node->edges[0] && node->edges[1])) {
2023 /* No rules and at most one child node, remove this node. */
2024 struct trie_node *next;
2025 next = node->edges[0] ? node->edges[0] : node->edges[1];
2028 if (node->nbits + next->nbits > TRIE_PREFIX_BITS) {
2029 break; /* Cannot combine. */
2031 /* Combine node with next. */
2032 next->prefix = node->prefix | next->prefix >> node->nbits;
2033 next->nbits += node->nbits;
2035 trie_node_destroy(node);
2036 /* Update the parent's edge. */
2037 *edges[depth] = next;
2038 if (next || !depth) {
2039 /* Branch not pruned or at root, nothing more to do. */
2042 node = *edges[--depth];
2047 /* Cannot go deeper. This should never happen, since only rules
2048 * that actually exist in the classifier are ever removed. */
2049 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");