2 * Copyright (c) 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include "classifier.h"
20 #include <netinet/in.h>
21 #include "byte-order.h"
22 #include "dynamic-string.h"
27 #include "ovs-thread.h"
31 VLOG_DEFINE_THIS_MODULE(classifier);
35 /* Prefix trie for a 'field' */
37 const struct mf_field *field; /* Trie field, or NULL. */
38 struct trie_node *root; /* NULL if none. */
41 struct cls_subtable_entry {
42 struct cls_subtable *subtable;
43 const uint32_t *mask_values;
45 unsigned int max_priority;
48 struct cls_subtable_cache {
49 struct cls_subtable_entry *subtables;
50 size_t alloc_size; /* Number of allocated elements. */
51 size_t size; /* One past last valid array element. */
55 CLS_MAX_INDICES = 3 /* Maximum number of lookup indices per subtable. */
58 struct cls_classifier {
59 int n_rules; /* Total number of rules. */
60 uint8_t n_flow_segments;
61 uint8_t flow_segments[CLS_MAX_INDICES]; /* Flow segment boundaries to use
62 * for staged lookup. */
63 struct hmap subtables; /* Contains "struct cls_subtable"s. */
64 struct cls_subtable_cache subtables_priority;
65 struct hmap partitions; /* Contains "struct cls_partition"s. */
66 struct cls_trie tries[CLS_MAX_TRIES]; /* Prefix tries. */
70 /* A set of rules that all have the same fields wildcarded. */
72 struct hmap_node hmap_node; /* Within struct cls_classifier 'subtables'
74 struct hmap rules; /* Contains "struct cls_rule"s. */
75 struct minimask mask; /* Wildcards for fields. */
76 int n_rules; /* Number of rules, including duplicates. */
77 unsigned int max_priority; /* Max priority of any rule in the subtable. */
78 unsigned int max_count; /* Count of max_priority rules. */
79 tag_type tag; /* Tag generated from mask for partitioning. */
80 uint8_t n_indices; /* How many indices to use. */
81 uint8_t index_ofs[CLS_MAX_INDICES]; /* u32 flow segment boundaries. */
82 struct hindex indices[CLS_MAX_INDICES]; /* Staged lookup indices. */
83 unsigned int trie_plen[CLS_MAX_TRIES]; /* Trie prefix length in 'mask'. */
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 hmap_node hmap_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 hindex_node index_nodes[CLS_MAX_INDICES]; /* Within subtable's
102 struct hmap_node hmap_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 minimatch match; /* Matching rule. */
109 static struct cls_match *
110 cls_match_alloc(struct cls_rule *rule)
112 struct cls_match *cls_match = xmalloc(sizeof *cls_match);
114 cls_match->cls_rule = rule;
115 minimatch_clone(&cls_match->match, &rule->match);
116 cls_match->priority = rule->priority;
117 rule->cls_match = cls_match;
123 static struct cls_subtable *find_subtable(const struct cls_classifier *,
124 const struct minimask *);
125 static struct cls_subtable *insert_subtable(struct cls_classifier *,
126 const struct minimask *);
128 static void destroy_subtable(struct cls_classifier *, struct cls_subtable *);
130 static void update_subtables_after_insertion(struct cls_classifier *,
131 struct cls_subtable *,
132 unsigned int new_priority);
133 static void update_subtables_after_removal(struct cls_classifier *,
134 struct cls_subtable *,
135 unsigned int del_priority);
137 static struct cls_match *find_match_wc(const struct cls_subtable *,
138 const struct flow *, struct trie_ctx *,
139 unsigned int n_tries,
140 struct flow_wildcards *);
141 static struct cls_match *find_equal(struct cls_subtable *,
142 const struct miniflow *, uint32_t hash);
143 static struct cls_match *insert_rule(struct cls_classifier *,
144 struct cls_subtable *, struct cls_rule *);
146 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list. */
147 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD) \
148 for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
149 #define FOR_EACH_RULE_IN_LIST_SAFE(RULE, NEXT, HEAD) \
150 for ((RULE) = (HEAD); \
151 (RULE) != NULL && ((NEXT) = next_rule_in_list(RULE), true); \
154 static struct cls_match *next_rule_in_list__(struct cls_match *);
155 static struct cls_match *next_rule_in_list(struct cls_match *);
157 static unsigned int minimask_get_prefix_len(const struct minimask *,
158 const struct mf_field *);
159 static void trie_init(struct cls_classifier *, int trie_idx,
160 const struct mf_field *);
161 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
162 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_remove(struct cls_trie *, const struct cls_rule *, int mlen);
167 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
169 static bool mask_prefix_bits_set(const struct flow_wildcards *,
170 uint8_t be32ofs, unsigned int nbits);
173 cls_subtable_cache_init(struct cls_subtable_cache *array)
175 memset(array, 0, sizeof *array);
179 cls_subtable_cache_destroy(struct cls_subtable_cache *array)
181 free(array->subtables);
182 memset(array, 0, sizeof *array);
185 /* Array insertion. */
187 cls_subtable_cache_push_back(struct cls_subtable_cache *array,
188 struct cls_subtable_entry a)
190 if (array->size == array->alloc_size) {
191 array->subtables = x2nrealloc(array->subtables, &array->alloc_size,
195 array->subtables[array->size++] = a;
198 /* Only for rearranging entries in the same cache. */
200 cls_subtable_cache_splice(struct cls_subtable_entry *to,
201 struct cls_subtable_entry *start,
202 struct cls_subtable_entry *end)
205 /* Same as splicing entries to (start) from [end, to). */
206 struct cls_subtable_entry *temp = to;
207 to = start; start = end; end = temp;
210 while (start != end) {
211 struct cls_subtable_entry temp = *start;
213 memmove(to + 1, to, (start - to) * sizeof *to);
217 } /* Else nothing to be done. */
222 cls_subtable_cache_remove(struct cls_subtable_cache *array,
223 struct cls_subtable_entry *elem)
225 ssize_t size = (&array->subtables[array->size]
226 - (elem + 1)) * sizeof *elem;
228 memmove(elem, elem + 1, size);
233 #define CLS_SUBTABLE_CACHE_FOR_EACH(SUBTABLE, ITER, ARRAY) \
234 for (ITER = (ARRAY)->subtables; \
235 ITER < &(ARRAY)->subtables[(ARRAY)->size] \
236 && OVS_LIKELY(SUBTABLE = ITER->subtable); \
238 #define CLS_SUBTABLE_CACHE_FOR_EACH_CONTINUE(SUBTABLE, ITER, ARRAY) \
240 ITER < &(ARRAY)->subtables[(ARRAY)->size] \
241 && OVS_LIKELY(SUBTABLE = ITER->subtable); \
243 #define CLS_SUBTABLE_CACHE_FOR_EACH_REVERSE(SUBTABLE, ITER, ARRAY) \
244 for (ITER = &(ARRAY)->subtables[(ARRAY)->size]; \
245 ITER > (ARRAY)->subtables \
246 && OVS_LIKELY(SUBTABLE = (--ITER)->subtable);)
249 /* flow/miniflow/minimask/minimatch utilities.
250 * These are only used by the classifier, so place them here to allow
251 * for better optimization. */
253 static inline uint64_t
254 miniflow_get_map_in_range(const struct miniflow *miniflow,
255 uint8_t start, uint8_t end, unsigned int *offset)
257 uint64_t map = miniflow->map;
261 uint64_t msk = (UINT64_C(1) << start) - 1; /* 'start' LSBs set */
262 *offset = count_1bits(map & msk);
265 if (end < FLOW_U32S) {
266 uint64_t msk = (UINT64_C(1) << end) - 1; /* 'end' LSBs set */
272 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
273 * 'mask', given 'basis'.
275 * The hash values returned by this function are the same as those returned by
276 * miniflow_hash_in_minimask(), only the form of the arguments differ. */
277 static inline uint32_t
278 flow_hash_in_minimask(const struct flow *flow, const struct minimask *mask,
281 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
282 const uint32_t *flow_u32 = (const uint32_t *)flow;
283 const uint32_t *p = mask_values;
288 for (map = mask->masks.map; map; map = zero_rightmost_1bit(map)) {
289 hash = mhash_add(hash, flow_u32[raw_ctz(map)] & *p++);
292 return mhash_finish(hash, (p - mask_values) * 4);
295 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
296 * 'mask', given 'basis'.
298 * The hash values returned by this function are the same as those returned by
299 * flow_hash_in_minimask(), only the form of the arguments differ. */
300 static inline uint32_t
301 miniflow_hash_in_minimask(const struct miniflow *flow,
302 const struct minimask *mask, uint32_t basis)
304 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
305 const uint32_t *p = mask_values;
306 uint32_t hash = basis;
309 MINIFLOW_FOR_EACH_IN_MAP(flow_u32, flow, mask->masks.map) {
310 hash = mhash_add(hash, flow_u32 & *p++);
313 return mhash_finish(hash, (p - mask_values) * 4);
316 /* Returns a hash value for the bits of range [start, end) in 'flow',
317 * where there are 1-bits in 'mask', given 'hash'.
319 * The hash values returned by this function are the same as those returned by
320 * minimatch_hash_range(), only the form of the arguments differ. */
321 static inline uint32_t
322 flow_hash_in_minimask_range(const struct flow *flow,
323 const struct minimask *mask,
324 uint8_t start, uint8_t end, uint32_t *basis)
326 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
327 const uint32_t *flow_u32 = (const uint32_t *)flow;
329 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
331 const uint32_t *p = mask_values + offset;
332 uint32_t hash = *basis;
334 for (; map; map = zero_rightmost_1bit(map)) {
335 hash = mhash_add(hash, flow_u32[raw_ctz(map)] & *p++);
338 *basis = hash; /* Allow continuation from the unfinished value. */
339 return mhash_finish(hash, (p - mask_values) * 4);
342 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask. */
344 flow_wildcards_fold_minimask(struct flow_wildcards *wc,
345 const struct minimask *mask)
347 flow_union_with_miniflow(&wc->masks, &mask->masks);
350 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask
351 * in range [start, end). */
353 flow_wildcards_fold_minimask_range(struct flow_wildcards *wc,
354 const struct minimask *mask,
355 uint8_t start, uint8_t end)
357 uint32_t *dst_u32 = (uint32_t *)&wc->masks;
359 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
361 const uint32_t *p = miniflow_get_u32_values(&mask->masks) + offset;
363 for (; map; map = zero_rightmost_1bit(map)) {
364 dst_u32[raw_ctz(map)] |= *p++;
368 /* Returns a hash value for 'flow', given 'basis'. */
369 static inline uint32_t
370 miniflow_hash(const struct miniflow *flow, uint32_t basis)
372 const uint32_t *values = miniflow_get_u32_values(flow);
373 const uint32_t *p = values;
374 uint32_t hash = basis;
375 uint64_t hash_map = 0;
378 for (map = flow->map; map; map = zero_rightmost_1bit(map)) {
380 hash = mhash_add(hash, *p);
381 hash_map |= rightmost_1bit(map);
385 hash = mhash_add(hash, hash_map);
386 hash = mhash_add(hash, hash_map >> 32);
388 return mhash_finish(hash, p - values);
391 /* Returns a hash value for 'mask', given 'basis'. */
392 static inline uint32_t
393 minimask_hash(const struct minimask *mask, uint32_t basis)
395 return miniflow_hash(&mask->masks, basis);
398 /* Returns a hash value for 'match', given 'basis'. */
399 static inline uint32_t
400 minimatch_hash(const struct minimatch *match, uint32_t basis)
402 return miniflow_hash(&match->flow, minimask_hash(&match->mask, basis));
405 /* Returns a hash value for the bits of range [start, end) in 'minimatch',
408 * The hash values returned by this function are the same as those returned by
409 * flow_hash_in_minimask_range(), only the form of the arguments differ. */
410 static inline uint32_t
411 minimatch_hash_range(const struct minimatch *match, uint8_t start, uint8_t end,
415 const uint32_t *p, *q;
416 uint32_t hash = *basis;
419 n = count_1bits(miniflow_get_map_in_range(&match->mask.masks, start, end,
421 q = miniflow_get_u32_values(&match->mask.masks) + offset;
422 p = miniflow_get_u32_values(&match->flow) + offset;
424 for (i = 0; i < n; i++) {
425 hash = mhash_add(hash, p[i] & q[i]);
427 *basis = hash; /* Allow continuation from the unfinished value. */
428 return mhash_finish(hash, (offset + n) * 4);
434 /* Initializes 'rule' to match packets specified by 'match' at the given
435 * 'priority'. 'match' must satisfy the invariant described in the comment at
436 * the definition of struct match.
438 * The caller must eventually destroy 'rule' with cls_rule_destroy().
440 * (OpenFlow uses priorities between 0 and UINT16_MAX, inclusive, but
441 * internally Open vSwitch supports a wider range.) */
443 cls_rule_init(struct cls_rule *rule,
444 const struct match *match, unsigned int priority)
446 minimatch_init(&rule->match, match);
447 rule->priority = priority;
448 rule->cls_match = NULL;
451 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
453 cls_rule_init_from_minimatch(struct cls_rule *rule,
454 const struct minimatch *match,
455 unsigned int priority)
457 minimatch_clone(&rule->match, match);
458 rule->priority = priority;
459 rule->cls_match = NULL;
462 /* Initializes 'dst' as a copy of 'src'.
464 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
466 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
468 minimatch_clone(&dst->match, &src->match);
469 dst->priority = src->priority;
470 dst->cls_match = NULL;
473 /* Initializes 'dst' with the data in 'src', destroying 'src'.
475 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
477 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
479 minimatch_move(&dst->match, &src->match);
480 dst->priority = src->priority;
481 dst->cls_match = NULL;
484 /* Frees memory referenced by 'rule'. Doesn't free 'rule' itself (it's
485 * normally embedded into a larger structure).
487 * ('rule' must not currently be in a classifier.) */
489 cls_rule_destroy(struct cls_rule *rule)
491 ovs_assert(!rule->cls_match);
492 minimatch_destroy(&rule->match);
495 /* Returns true if 'a' and 'b' match the same packets at the same priority,
496 * false if they differ in some way. */
498 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
500 return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
503 /* Returns a hash value for 'rule', folding in 'basis'. */
505 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
507 return minimatch_hash(&rule->match, hash_int(rule->priority, basis));
510 /* Appends a string describing 'rule' to 's'. */
512 cls_rule_format(const struct cls_rule *rule, struct ds *s)
514 minimatch_format(&rule->match, s, rule->priority);
517 /* Returns true if 'rule' matches every packet, false otherwise. */
519 cls_rule_is_catchall(const struct cls_rule *rule)
521 return minimask_is_catchall(&rule->match.mask);
524 /* Initializes 'cls' as a classifier that initially contains no classification
527 classifier_init(struct classifier *cls_, const uint8_t *flow_segments)
529 struct cls_classifier *cls = xmalloc(sizeof *cls);
531 fat_rwlock_init(&cls_->rwlock);
536 hmap_init(&cls->subtables);
537 cls_subtable_cache_init(&cls->subtables_priority);
538 hmap_init(&cls->partitions);
539 cls->n_flow_segments = 0;
541 while (cls->n_flow_segments < CLS_MAX_INDICES
542 && *flow_segments < FLOW_U32S) {
543 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
549 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
550 * caller's responsibility. */
552 classifier_destroy(struct classifier *cls_)
555 struct cls_classifier *cls = cls_->cls;
556 struct cls_subtable *partition, *next_partition;
557 struct cls_subtable *subtable, *next_subtable;
560 fat_rwlock_destroy(&cls_->rwlock);
565 for (i = 0; i < cls->n_tries; i++) {
566 trie_destroy(cls->tries[i].root);
569 HMAP_FOR_EACH_SAFE (subtable, next_subtable, hmap_node,
571 destroy_subtable(cls, subtable);
573 hmap_destroy(&cls->subtables);
575 HMAP_FOR_EACH_SAFE (partition, next_partition, hmap_node,
577 hmap_remove(&cls->partitions, &partition->hmap_node);
580 hmap_destroy(&cls->partitions);
582 cls_subtable_cache_destroy(&cls->subtables_priority);
587 /* We use uint64_t as a set for the fields below. */
588 BUILD_ASSERT_DECL(MFF_N_IDS <= 64);
590 /* Set the fields for which prefix lookup should be performed. */
592 classifier_set_prefix_fields(struct classifier *cls_,
593 const enum mf_field_id *trie_fields,
594 unsigned int n_fields)
596 struct cls_classifier *cls = cls_->cls;
600 for (i = 0, trie = 0; i < n_fields && trie < CLS_MAX_TRIES; i++) {
601 const struct mf_field *field = mf_from_id(trie_fields[i]);
602 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
603 /* Incompatible field. This is the only place where we
604 * enforce these requirements, but the rest of the trie code
605 * depends on the flow_be32ofs to be non-negative and the
606 * field length to be a multiple of 32 bits. */
610 if (fields & (UINT64_C(1) << trie_fields[i])) {
611 /* Duplicate field, there is no need to build more than
612 * one index for any one field. */
615 fields |= UINT64_C(1) << trie_fields[i];
617 if (trie >= cls->n_tries || field != cls->tries[trie].field) {
618 trie_init(cls, trie, field);
623 /* Destroy the rest. */
624 for (i = trie; i < cls->n_tries; i++) {
625 trie_init(cls, i, NULL);
631 trie_init(struct cls_classifier *cls, int trie_idx,
632 const struct mf_field *field)
634 struct cls_trie *trie = &cls->tries[trie_idx];
635 struct cls_subtable *subtable;
636 struct cls_subtable_entry *iter;
638 if (trie_idx < cls->n_tries) {
639 trie_destroy(trie->root);
644 /* Add existing rules to the trie. */
645 CLS_SUBTABLE_CACHE_FOR_EACH (subtable, iter, &cls->subtables_priority) {
648 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
649 /* Initialize subtable's prefix length on this field. */
650 subtable->trie_plen[trie_idx] = plen;
653 struct cls_match *head;
655 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
656 struct cls_match *match;
658 FOR_EACH_RULE_IN_LIST (match, head) {
659 trie_insert(trie, match->cls_rule, plen);
666 /* Returns true if 'cls' contains no classification rules, false otherwise. */
668 classifier_is_empty(const struct classifier *cls)
670 return cls->cls->n_rules == 0;
673 /* Returns the number of rules in 'cls'. */
675 classifier_count(const struct classifier *cls)
677 return cls->cls->n_rules;
681 hash_metadata(ovs_be64 metadata_)
683 uint64_t metadata = (OVS_FORCE uint64_t) metadata_;
684 return hash_uint64(metadata);
687 static struct cls_partition *
688 find_partition(const struct cls_classifier *cls, ovs_be64 metadata,
691 struct cls_partition *partition;
693 HMAP_FOR_EACH_IN_BUCKET (partition, hmap_node, hash, &cls->partitions) {
694 if (partition->metadata == metadata) {
702 static struct cls_partition *
703 create_partition(struct cls_classifier *cls, struct cls_subtable *subtable,
706 uint32_t hash = hash_metadata(metadata);
707 struct cls_partition *partition = find_partition(cls, metadata, hash);
709 partition = xmalloc(sizeof *partition);
710 partition->metadata = metadata;
712 tag_tracker_init(&partition->tracker);
713 hmap_insert(&cls->partitions, &partition->hmap_node, hash);
715 tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
719 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
720 * must not modify or free it.
722 * If 'cls' already contains an identical rule (including wildcards, values of
723 * fixed fields, and priority), replaces the old rule by 'rule' and returns the
724 * rule that was replaced. The caller takes ownership of the returned rule and
725 * is thus responsible for destroying it with cls_rule_destroy(), freeing the
726 * memory block in which it resides, etc., as necessary.
728 * Returns NULL if 'cls' does not contain a rule with an identical key, after
729 * inserting the new rule. In this case, no rules are displaced by the new
730 * rule, even rules that cannot have any effect because the new rule matches a
731 * superset of their flows and has higher priority. */
733 classifier_replace(struct classifier *cls_, struct cls_rule *rule)
735 struct cls_classifier *cls = cls_->cls;
736 struct cls_match *old_rule;
737 struct cls_subtable *subtable;
739 subtable = find_subtable(cls, &rule->match.mask);
741 subtable = insert_subtable(cls, &rule->match.mask);
744 old_rule = insert_rule(cls, subtable, rule);
748 rule->cls_match->partition = NULL;
749 if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
750 ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
751 rule->cls_match->partition = create_partition(cls, subtable,
758 for (i = 0; i < cls->n_tries; i++) {
759 if (subtable->trie_plen[i]) {
760 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
765 struct cls_rule *old_cls_rule = old_rule->cls_rule;
767 rule->cls_match->partition = old_rule->partition;
768 old_cls_rule->cls_match = NULL;
774 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
775 * must not modify or free it.
777 * 'cls' must not contain an identical rule (including wildcards, values of
778 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
781 classifier_insert(struct classifier *cls, struct cls_rule *rule)
783 struct cls_rule *displaced_rule = classifier_replace(cls, rule);
784 ovs_assert(!displaced_rule);
787 /* Removes 'rule' from 'cls'. It is the caller's responsibility to destroy
788 * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
789 * resides, etc., as necessary. */
791 classifier_remove(struct classifier *cls_, struct cls_rule *rule)
793 struct cls_classifier *cls = cls_->cls;
794 struct cls_partition *partition;
795 struct cls_match *cls_match = rule->cls_match;
796 struct cls_match *head;
797 struct cls_subtable *subtable;
800 ovs_assert(cls_match);
802 subtable = find_subtable(cls, &rule->match.mask);
804 ovs_assert(subtable);
806 for (i = 0; i < cls->n_tries; i++) {
807 if (subtable->trie_plen[i]) {
808 trie_remove(&cls->tries[i], rule, subtable->trie_plen[i]);
812 /* Remove rule node from indices. */
813 for (i = 0; i < subtable->n_indices; i++) {
814 hindex_remove(&subtable->indices[i], &cls_match->index_nodes[i]);
817 head = find_equal(subtable, &rule->match.flow, cls_match->hmap_node.hash);
818 if (head != cls_match) {
819 list_remove(&cls_match->list);
820 } else if (list_is_empty(&cls_match->list)) {
821 hmap_remove(&subtable->rules, &cls_match->hmap_node);
823 struct cls_match *next = CONTAINER_OF(cls_match->list.next,
824 struct cls_match, list);
826 list_remove(&cls_match->list);
827 hmap_replace(&subtable->rules, &cls_match->hmap_node,
831 partition = cls_match->partition;
833 tag_tracker_subtract(&partition->tracker, &partition->tags,
835 if (!partition->tags) {
836 hmap_remove(&cls->partitions, &partition->hmap_node);
841 if (--subtable->n_rules == 0) {
842 destroy_subtable(cls, subtable);
844 update_subtables_after_removal(cls, subtable, cls_match->priority);
849 rule->cls_match = NULL;
853 /* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
854 * subtables which have more than 'match_plen' bits in their corresponding
855 * field at offset 'be32ofs'. If skipped, 'maskbits' prefix bits should be
856 * unwildcarded to quarantee datapath flow matches only packets it should. */
858 const struct cls_trie *trie;
859 bool lookup_done; /* Status of the lookup. */
860 uint8_t be32ofs; /* U32 offset of the field in question. */
861 unsigned int match_plen; /* Longest prefix than could possibly match. */
862 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
866 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
869 ctx->be32ofs = trie->field->flow_be32ofs;
870 ctx->lookup_done = false;
874 lookahead_subtable(const struct cls_subtable_entry *subtables)
876 ovs_prefetch_range(subtables->subtable, sizeof *subtables->subtable);
877 ovs_prefetch_range(subtables->mask_values, 1);
880 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
881 * Returns a null pointer if no rules in 'cls' match 'flow'. If multiple rules
882 * of equal priority match 'flow', returns one arbitrarily.
884 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
885 * set of bits that were significant in the lookup. At some point
886 * earlier, 'wc' should have been initialized (e.g., by
887 * flow_wildcards_init_catchall()). */
889 classifier_lookup(const struct classifier *cls_, const struct flow *flow,
890 struct flow_wildcards *wc)
892 struct cls_classifier *cls = cls_->cls;
893 const struct cls_partition *partition;
895 struct cls_match *best;
896 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
898 struct cls_subtable_entry *subtables = cls->subtables_priority.subtables;
899 int n_subtables = cls->subtables_priority.size;
900 int64_t best_priority = -1;
902 /* Prefetch the subtables array. */
903 ovs_prefetch_range(subtables, n_subtables * sizeof *subtables);
905 /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
906 * then 'flow' cannot possibly match in 'subtable':
908 * - If flow->metadata maps to a given 'partition', then we can use
909 * 'tags' for 'partition->tags'.
911 * - If flow->metadata has no partition, then no rule in 'cls' has an
912 * exact-match for flow->metadata. That means that we don't need to
913 * search any subtable that includes flow->metadata in its mask.
915 * In either case, we always need to search any cls_subtables that do not
916 * include flow->metadata in its mask. One way to do that would be to
917 * check the "cls_subtable"s explicitly for that, but that would require an
918 * extra branch per subtable. Instead, we mark such a cls_subtable's
919 * 'tags' as TAG_ALL and make sure that 'tags' is never empty. This means
920 * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
921 * need a special case.
923 partition = (hmap_is_empty(&cls->partitions)
925 : find_partition(cls, flow->metadata,
926 hash_metadata(flow->metadata)));
927 tags = partition ? partition->tags : TAG_ARBITRARY;
929 /* Initialize trie contexts for match_find_wc(). */
930 for (i = 0; i < cls->n_tries; i++) {
931 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
934 /* Prefetch the first subtables. */
935 if (n_subtables > 1) {
936 lookahead_subtable(subtables);
937 lookahead_subtable(subtables + 1);
941 for (i = 0; OVS_LIKELY(i < n_subtables); i++) {
942 struct cls_match *rule;
944 if ((int64_t)subtables[i].max_priority <= best_priority) {
945 /* Subtables are in descending priority order,
946 * can not find anything better. */
950 /* Prefetch a forthcoming subtable. */
951 if (i + 2 < n_subtables) {
952 lookahead_subtable(&subtables[i + 2]);
955 if (!tag_intersects(tags, subtables[i].tag)) {
959 rule = find_match_wc(subtables[i].subtable, flow, trie_ctx,
961 if (rule && (int64_t)rule->priority > best_priority) {
962 best_priority = (int64_t)rule->priority;
967 return best ? best->cls_rule : NULL;
970 /* Returns true if 'target' satisifies 'match', that is, if each bit for which
971 * 'match' specifies a particular value has the correct value in 'target'. */
973 minimatch_matches_miniflow(const struct minimatch *match,
974 const struct miniflow *target)
976 const uint32_t *flowp = miniflow_get_u32_values(&match->flow);
977 const uint32_t *maskp = miniflow_get_u32_values(&match->mask.masks);
980 MINIFLOW_FOR_EACH_IN_MAP(target_u32, target, match->mask.masks.map) {
981 if ((*flowp++ ^ target_u32) & *maskp++) {
989 static inline struct cls_match *
990 find_match_miniflow(const struct cls_subtable *subtable,
991 const struct miniflow *flow,
994 struct cls_match *rule;
996 HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &subtable->rules) {
997 if (minimatch_matches_miniflow(&rule->match, flow)) {
1005 /* Finds and returns the highest-priority rule in 'cls' that matches
1006 * 'miniflow'. Returns a null pointer if no rules in 'cls' match 'flow'.
1007 * If multiple rules of equal priority match 'flow', returns one arbitrarily.
1009 * This function is optimized for the userspace datapath, which only ever has
1010 * one priority value for it's flows!
1012 struct cls_rule *classifier_lookup_miniflow_first(const struct classifier *cls_,
1013 const struct miniflow *flow)
1015 struct cls_classifier *cls = cls_->cls;
1016 struct cls_subtable *subtable;
1017 struct cls_subtable_entry *iter;
1019 CLS_SUBTABLE_CACHE_FOR_EACH (subtable, iter, &cls->subtables_priority) {
1020 struct cls_match *rule;
1022 rule = find_match_miniflow(subtable, flow,
1023 miniflow_hash_in_minimask(flow,
1027 return rule->cls_rule;
1034 /* Finds and returns a rule in 'cls' with exactly the same priority and
1035 * matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
1036 * contain an exact match. */
1038 classifier_find_rule_exactly(const struct classifier *cls_,
1039 const struct cls_rule *target)
1041 struct cls_classifier *cls = cls_->cls;
1042 struct cls_match *head, *rule;
1043 struct cls_subtable *subtable;
1045 subtable = find_subtable(cls, &target->match.mask);
1050 /* Skip if there is no hope. */
1051 if (target->priority > subtable->max_priority) {
1055 head = find_equal(subtable, &target->match.flow,
1056 miniflow_hash_in_minimask(&target->match.flow,
1057 &target->match.mask, 0));
1058 FOR_EACH_RULE_IN_LIST (rule, head) {
1059 if (target->priority >= rule->priority) {
1060 return target->priority == rule->priority ? rule->cls_rule : NULL;
1066 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
1067 * same matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
1068 * contain an exact match. */
1070 classifier_find_match_exactly(const struct classifier *cls,
1071 const struct match *target,
1072 unsigned int priority)
1074 struct cls_rule *retval;
1077 cls_rule_init(&cr, target, priority);
1078 retval = classifier_find_rule_exactly(cls, &cr);
1079 cls_rule_destroy(&cr);
1084 /* Checks if 'target' would overlap any other rule in 'cls'. Two rules are
1085 * considered to overlap if both rules have the same priority and a packet
1086 * could match both. */
1088 classifier_rule_overlaps(const struct classifier *cls_,
1089 const struct cls_rule *target)
1091 struct cls_classifier *cls = cls_->cls;
1092 struct cls_subtable *subtable;
1093 struct cls_subtable_entry *iter;
1095 /* Iterate subtables in the descending max priority order. */
1096 CLS_SUBTABLE_CACHE_FOR_EACH (subtable, iter, &cls->subtables_priority) {
1097 uint32_t storage[FLOW_U32S];
1098 struct minimask mask;
1099 struct cls_match *head;
1101 if (target->priority > iter->max_priority) {
1102 break; /* Can skip this and the rest of the subtables. */
1105 minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
1106 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
1107 struct cls_match *rule;
1109 FOR_EACH_RULE_IN_LIST (rule, head) {
1110 if (rule->priority < target->priority) {
1111 break; /* Rules in descending priority order. */
1113 if (rule->priority == target->priority
1114 && miniflow_equal_in_minimask(&target->match.flow,
1115 &rule->match.flow, &mask)) {
1125 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
1126 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
1127 * function returns true if, for every field:
1129 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
1132 * - 'criteria' wildcards the field,
1134 * Conversely, 'rule' does not match 'criteria' and this function returns false
1135 * if, for at least one field:
1137 * - 'criteria' and 'rule' specify different values for the field, or
1139 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
1141 * Equivalently, the truth table for whether a field matches is:
1146 * r +---------+---------+
1147 * i wild | yes | yes |
1149 * e +---------+---------+
1150 * r exact | no |if values|
1152 * a +---------+---------+
1154 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
1155 * commands and by OpenFlow 1.0 aggregate and flow stats.
1157 * Ignores rule->priority. */
1159 cls_rule_is_loose_match(const struct cls_rule *rule,
1160 const struct minimatch *criteria)
1162 return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
1163 && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
1170 rule_matches(const struct cls_match *rule, const struct cls_rule *target)
1173 || miniflow_equal_in_minimask(&rule->match.flow,
1174 &target->match.flow,
1175 &target->match.mask));
1178 static struct cls_match *
1179 search_subtable(const struct cls_subtable *subtable,
1180 const struct cls_rule *target)
1182 if (!target || !minimask_has_extra(&subtable->mask, &target->match.mask)) {
1183 struct cls_match *rule;
1185 HMAP_FOR_EACH (rule, hmap_node, &subtable->rules) {
1186 if (rule_matches(rule, target)) {
1194 /* Initializes 'cursor' for iterating through rules in 'cls':
1196 * - If 'target' is null, the cursor will visit every rule in 'cls'.
1198 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1199 * such that cls_rule_is_loose_match(rule, target) returns true.
1201 * Ignores target->priority. */
1203 cls_cursor_init(struct cls_cursor *cursor, const struct classifier *cls,
1204 const struct cls_rule *target)
1206 cursor->cls = cls->cls;
1207 cursor->target = target && !cls_rule_is_catchall(target) ? target : NULL;
1210 /* Returns the first matching cls_rule in 'cursor''s iteration, or a null
1211 * pointer if there are no matches. */
1213 cls_cursor_first(struct cls_cursor *cursor)
1215 struct cls_subtable *subtable;
1217 HMAP_FOR_EACH (subtable, hmap_node, &cursor->cls->subtables) {
1218 struct cls_match *rule = search_subtable(subtable, cursor->target);
1220 cursor->subtable = subtable;
1221 return rule->cls_rule;
1228 /* Returns the next matching cls_rule in 'cursor''s iteration, or a null
1229 * pointer if there are no more matches. */
1231 cls_cursor_next(struct cls_cursor *cursor, const struct cls_rule *rule_)
1233 struct cls_match *rule = CONST_CAST(struct cls_match *, rule_->cls_match);
1234 const struct cls_subtable *subtable;
1235 struct cls_match *next;
1237 next = next_rule_in_list__(rule);
1238 if (next->priority < rule->priority) {
1239 return next->cls_rule;
1242 /* 'next' is the head of the list, that is, the rule that is included in
1243 * the subtable's hmap. (This is important when the classifier contains
1244 * rules that differ only in priority.) */
1246 HMAP_FOR_EACH_CONTINUE (rule, hmap_node, &cursor->subtable->rules) {
1247 if (rule_matches(rule, cursor->target)) {
1248 return rule->cls_rule;
1252 subtable = cursor->subtable;
1253 HMAP_FOR_EACH_CONTINUE (subtable, hmap_node, &cursor->cls->subtables) {
1254 rule = search_subtable(subtable, cursor->target);
1256 cursor->subtable = subtable;
1257 return rule->cls_rule;
1264 static struct cls_subtable *
1265 find_subtable(const struct cls_classifier *cls, const struct minimask *mask)
1267 struct cls_subtable *subtable;
1269 HMAP_FOR_EACH_IN_BUCKET (subtable, hmap_node, minimask_hash(mask, 0),
1271 if (minimask_equal(mask, &subtable->mask)) {
1278 static struct cls_subtable *
1279 insert_subtable(struct cls_classifier *cls, const struct minimask *mask)
1281 uint32_t hash = minimask_hash(mask, 0);
1282 struct cls_subtable *subtable;
1284 struct flow_wildcards old, new;
1286 struct cls_subtable_entry elem;
1288 subtable = xzalloc(sizeof *subtable);
1289 hmap_init(&subtable->rules);
1290 minimask_clone(&subtable->mask, mask);
1292 /* Init indices for segmented lookup, if any. */
1293 flow_wildcards_init_catchall(&new);
1296 for (i = 0; i < cls->n_flow_segments; i++) {
1297 flow_wildcards_fold_minimask_range(&new, mask, prev,
1298 cls->flow_segments[i]);
1299 /* Add an index if it adds mask bits. */
1300 if (!flow_wildcards_equal(&new, &old)) {
1301 hindex_init(&subtable->indices[index]);
1302 subtable->index_ofs[index] = cls->flow_segments[i];
1306 prev = cls->flow_segments[i];
1308 /* Check if the rest of the subtable's mask adds any bits,
1309 * and remove the last index if it doesn't. */
1311 flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U32S);
1312 if (flow_wildcards_equal(&new, &old)) {
1314 subtable->index_ofs[index] = 0;
1315 hindex_destroy(&subtable->indices[index]);
1318 subtable->n_indices = index;
1320 subtable->tag = (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1321 ? tag_create_deterministic(hash)
1324 for (i = 0; i < cls->n_tries; i++) {
1325 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1326 cls->tries[i].field);
1329 hmap_insert(&cls->subtables, &subtable->hmap_node, hash);
1330 elem.subtable = subtable;
1331 elem.mask_values = miniflow_get_values(&subtable->mask.masks);
1332 elem.tag = subtable->tag;
1333 elem.max_priority = subtable->max_priority;
1334 cls_subtable_cache_push_back(&cls->subtables_priority, elem);
1340 destroy_subtable(struct cls_classifier *cls, struct cls_subtable *subtable)
1343 struct cls_subtable *table = NULL;
1344 struct cls_subtable_entry *iter;
1346 CLS_SUBTABLE_CACHE_FOR_EACH (table, iter, &cls->subtables_priority) {
1347 if (table == subtable) {
1348 cls_subtable_cache_remove(&cls->subtables_priority, iter);
1353 for (i = 0; i < subtable->n_indices; i++) {
1354 hindex_destroy(&subtable->indices[i]);
1356 minimask_destroy(&subtable->mask);
1357 hmap_remove(&cls->subtables, &subtable->hmap_node);
1358 hmap_destroy(&subtable->rules);
1362 /* This function performs the following updates for 'subtable' in 'cls'
1363 * following the addition of a new rule with priority 'new_priority' to
1366 * - Update 'subtable->max_priority' and 'subtable->max_count' if necessary.
1368 * - Update 'subtable''s position in 'cls->subtables_priority' if necessary.
1370 * This function should only be called after adding a new rule, not after
1371 * replacing a rule by an identical one or modifying a rule in-place. */
1373 update_subtables_after_insertion(struct cls_classifier *cls,
1374 struct cls_subtable *subtable,
1375 unsigned int new_priority)
1377 if (new_priority == subtable->max_priority) {
1378 ++subtable->max_count;
1379 } else if (new_priority > subtable->max_priority) {
1380 struct cls_subtable *table;
1381 struct cls_subtable_entry *iter, *subtable_iter = NULL;
1383 subtable->max_priority = new_priority;
1384 subtable->max_count = 1;
1386 /* Possibly move 'subtable' earlier in the priority list. If we break
1387 * out of the loop, then 'subtable_iter' should be moved just before
1388 * 'iter'. If the loop terminates normally, then 'iter' will be the
1389 * first list element and we'll move subtable just before that
1390 * (e.g. to the front of the list). */
1391 CLS_SUBTABLE_CACHE_FOR_EACH_REVERSE (table, iter, &cls->subtables_priority) {
1392 if (table == subtable) {
1393 subtable_iter = iter; /* Locate the subtable as we go. */
1394 iter->max_priority = new_priority;
1395 } else if (table->max_priority >= new_priority) {
1396 ovs_assert(subtable_iter != NULL);
1402 /* Move 'subtable' just before 'iter' (unless it's already there). */
1403 if (iter != subtable_iter) {
1404 cls_subtable_cache_splice(iter, subtable_iter, subtable_iter + 1);
1409 /* This function performs the following updates for 'subtable' in 'cls'
1410 * following the deletion of a rule with priority 'del_priority' from
1413 * - Update 'subtable->max_priority' and 'subtable->max_count' if necessary.
1415 * - Update 'subtable''s position in 'cls->subtables_priority' if necessary.
1417 * This function should only be called after removing a rule, not after
1418 * replacing a rule by an identical one or modifying a rule in-place. */
1420 update_subtables_after_removal(struct cls_classifier *cls,
1421 struct cls_subtable *subtable,
1422 unsigned int del_priority)
1424 if (del_priority == subtable->max_priority && --subtable->max_count == 0) {
1425 struct cls_match *head;
1426 struct cls_subtable *table;
1427 struct cls_subtable_entry *iter, *subtable_iter = NULL;
1429 subtable->max_priority = 0;
1430 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
1431 if (head->priority > subtable->max_priority) {
1432 subtable->max_priority = head->priority;
1433 subtable->max_count = 1;
1434 } else if (head->priority == subtable->max_priority) {
1435 ++subtable->max_count;
1439 /* Possibly move 'subtable' later in the priority list. If we break
1440 * out of the loop, then 'subtable' should be moved just before that
1441 * 'iter'. If the loop terminates normally, then 'iter' will be the
1442 * list head and we'll move subtable just before that (e.g. to the back
1444 CLS_SUBTABLE_CACHE_FOR_EACH (table, iter, &cls->subtables_priority) {
1445 if (table == subtable) {
1446 subtable_iter = iter; /* Locate the subtable as we go. */
1447 iter->max_priority = subtable->max_priority;
1448 } else if (table->max_priority <= subtable->max_priority) {
1449 ovs_assert(subtable_iter != NULL);
1454 /* Move 'subtable' just before 'iter' (unless it's already there). */
1455 if (iter != subtable_iter) {
1456 cls_subtable_cache_splice(iter, subtable_iter, subtable_iter + 1);
1466 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1467 * lookup results. */
1469 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1470 const unsigned int field_plen[CLS_MAX_TRIES],
1471 const struct range ofs, const struct flow *flow,
1472 struct flow_wildcards *wc)
1476 /* Check if we could avoid fully unwildcarding the next level of
1477 * fields using the prefix tries. The trie checks are done only as
1478 * needed to avoid folding in additional bits to the wildcards mask. */
1479 for (j = 0; j < n_tries; j++) {
1480 /* Is the trie field relevant for this subtable? */
1481 if (field_plen[j]) {
1482 struct trie_ctx *ctx = &trie_ctx[j];
1483 uint8_t be32ofs = ctx->be32ofs;
1485 /* Is the trie field within the current range of fields? */
1486 if (be32ofs >= ofs.start && be32ofs < ofs.end) {
1487 /* On-demand trie lookup. */
1488 if (!ctx->lookup_done) {
1489 ctx->match_plen = trie_lookup(ctx->trie, flow,
1491 ctx->lookup_done = true;
1493 /* Possible to skip the rest of the subtable if subtable's
1494 * prefix on the field is longer than what is known to match
1495 * based on the trie lookup. */
1496 if (field_plen[j] > ctx->match_plen) {
1497 /* RFC: We want the trie lookup to never result in
1498 * unwildcarding any bits that would not be unwildcarded
1499 * otherwise. Since the trie is shared by the whole
1500 * classifier, it is possible that the 'maskbits' contain
1501 * bits that are irrelevant for the partition of the
1502 * classifier relevant for the current flow. */
1504 /* Can skip if the field is already unwildcarded. */
1505 if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1508 /* Check that the trie result will not unwildcard more bits
1509 * than this stage will. */
1510 if (ctx->maskbits <= field_plen[j]) {
1511 /* Unwildcard the bits and skip the rest. */
1512 mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1513 /* Note: Prerequisite already unwildcarded, as the only
1514 * prerequisite of the supported trie lookup fields is
1515 * the ethertype, which is currently always
1527 static inline struct cls_match *
1528 find_match(const struct cls_subtable *subtable, const struct flow *flow,
1531 struct cls_match *rule;
1533 HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &subtable->rules) {
1534 if (minimatch_matches_flow(&rule->match, flow)) {
1542 static struct cls_match *
1543 find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
1544 struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1545 struct flow_wildcards *wc)
1547 uint32_t basis = 0, hash;
1548 struct cls_match *rule = NULL;
1552 if (OVS_UNLIKELY(!wc)) {
1553 return find_match(subtable, flow,
1554 flow_hash_in_minimask(flow, &subtable->mask, 0));
1558 /* Try to finish early by checking fields in segments. */
1559 for (i = 0; i < subtable->n_indices; i++) {
1560 struct hindex_node *inode;
1561 ofs.end = subtable->index_ofs[i];
1563 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1567 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1569 ofs.start = ofs.end;
1570 inode = hindex_node_with_hash(&subtable->indices[i], hash);
1572 /* No match, can stop immediately, but must fold in the mask
1573 * covered so far. */
1577 /* If we have narrowed down to a single rule already, check whether
1578 * that rule matches. If it does match, then we're done. If it does
1579 * not match, then we know that we will never get a match, but we do
1580 * not yet know how many wildcards we need to fold into 'wc' so we
1581 * continue iterating through indices to find that out. (We won't
1582 * waste time calling minimatch_matches_flow() again because we've set
1585 * This check shows a measurable benefit with non-trivial flow tables.
1587 * (Rare) hash collisions may cause us to miss the opportunity for this
1589 if (!inode->s && !rule) {
1590 ASSIGN_CONTAINER(rule, inode - i, index_nodes);
1591 if (minimatch_matches_flow(&rule->match, flow)) {
1596 ofs.end = FLOW_U32S;
1597 /* Trie check for the final range. */
1598 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1602 /* Multiple potential matches exist, look for one. */
1603 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1605 rule = find_match(subtable, flow, hash);
1607 /* We already narrowed the matching candidates down to just 'rule',
1608 * but it didn't match. */
1612 /* Must unwildcard all the fields, as they were looked at. */
1613 flow_wildcards_fold_minimask(wc, &subtable->mask);
1617 /* Must unwildcard the fields looked up so far, if any. */
1619 flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, ofs.start);
1624 static struct cls_match *
1625 find_equal(struct cls_subtable *subtable, const struct miniflow *flow,
1628 struct cls_match *head;
1630 HMAP_FOR_EACH_WITH_HASH (head, hmap_node, hash, &subtable->rules) {
1631 if (miniflow_equal(&head->match.flow, flow)) {
1638 static struct cls_match *
1639 insert_rule(struct cls_classifier *cls, struct cls_subtable *subtable,
1640 struct cls_rule *new)
1642 struct cls_match *cls_match = cls_match_alloc(new);
1643 struct cls_match *head;
1644 struct cls_match *old = NULL;
1646 uint32_t basis = 0, hash;
1647 uint8_t prev_be32ofs = 0;
1649 /* Add new node to segment indices. */
1650 for (i = 0; i < subtable->n_indices; i++) {
1651 hash = minimatch_hash_range(&new->match, prev_be32ofs,
1652 subtable->index_ofs[i], &basis);
1653 hindex_insert(&subtable->indices[i], &cls_match->index_nodes[i], hash);
1654 prev_be32ofs = subtable->index_ofs[i];
1656 hash = minimatch_hash_range(&new->match, prev_be32ofs, FLOW_U32S, &basis);
1657 head = find_equal(subtable, &new->match.flow, hash);
1659 hmap_insert(&subtable->rules, &cls_match->hmap_node, hash);
1660 list_init(&cls_match->list);
1663 /* Scan the list for the insertion point that will keep the list in
1664 * order of decreasing priority. */
1665 struct cls_match *rule;
1667 cls_match->hmap_node.hash = hash; /* Otherwise done by hmap_insert. */
1669 FOR_EACH_RULE_IN_LIST (rule, head) {
1670 if (cls_match->priority >= rule->priority) {
1672 /* 'new' is the new highest-priority flow in the list. */
1673 hmap_replace(&subtable->rules,
1674 &rule->hmap_node, &cls_match->hmap_node);
1677 if (cls_match->priority == rule->priority) {
1678 list_replace(&cls_match->list, &rule->list);
1682 list_insert(&rule->list, &cls_match->list);
1688 /* Insert 'new' at the end of the list. */
1689 list_push_back(&head->list, &cls_match->list);
1694 update_subtables_after_insertion(cls, subtable, cls_match->priority);
1696 /* Remove old node from indices. */
1697 for (i = 0; i < subtable->n_indices; i++) {
1698 hindex_remove(&subtable->indices[i], &old->index_nodes[i]);
1704 static struct cls_match *
1705 next_rule_in_list__(struct cls_match *rule)
1707 struct cls_match *next = OBJECT_CONTAINING(rule->list.next, next, list);
1711 static struct cls_match *
1712 next_rule_in_list(struct cls_match *rule)
1714 struct cls_match *next = next_rule_in_list__(rule);
1715 return next->priority < rule->priority ? next : NULL;
1718 /* A longest-prefix match tree. */
1720 uint32_t prefix; /* Prefix bits for this node, MSB first. */
1721 uint8_t nbits; /* Never zero, except for the root node. */
1722 unsigned int n_rules; /* Number of rules that have this prefix. */
1723 struct trie_node *edges[2]; /* Both NULL if leaf. */
1726 /* Max bits per node. Must fit in struct trie_node's 'prefix'.
1727 * Also tested with 16, 8, and 5 to stress the implementation. */
1728 #define TRIE_PREFIX_BITS 32
1730 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1731 * Prefixes are in the network byte order, and the offset 0 corresponds to
1732 * the most significant bit of the first byte. The offset can be read as
1733 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1735 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1739 pr += ofs / 32; /* Where to start. */
1740 ofs %= 32; /* How many bits to skip at 'pr'. */
1742 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1743 if (plen > 32 - ofs) { /* Need more than we have already? */
1744 prefix |= ntohl(*++pr) >> (32 - ofs);
1746 /* Return with possible unwanted bits at the end. */
1750 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1751 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1752 * corresponds to the most significant bit of the first byte. The offset can
1753 * be read as "how many bits to skip from the start of the prefix starting at
1756 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1761 if (plen > TRIE_PREFIX_BITS) {
1762 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1764 /* Return with unwanted bits cleared. */
1765 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1768 /* Return the number of equal bits in 'nbits' of 'prefix's MSBs and a 'value'
1769 * starting at "MSB 0"-based offset 'ofs'. */
1771 prefix_equal_bits(uint32_t prefix, unsigned int nbits, const ovs_be32 value[],
1774 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, nbits);
1775 /* Set the bit after the relevant bits to limit the result. */
1776 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - nbits));
1779 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1780 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1782 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1783 unsigned int ofs, unsigned int plen)
1785 return prefix_equal_bits(node->prefix, MIN(node->nbits, plen - ofs),
1789 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1790 * be greater than 31. */
1792 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1794 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1797 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1798 * be between 0 and 31, inclusive. */
1800 get_bit_at(const uint32_t prefix, unsigned int ofs)
1802 return (prefix >> (31 - ofs)) & 1u;
1805 /* Create new branch. */
1806 static struct trie_node *
1807 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1808 unsigned int n_rules)
1810 struct trie_node *node = xmalloc(sizeof *node);
1812 node->prefix = trie_get_prefix(prefix, ofs, plen);
1814 if (plen <= TRIE_PREFIX_BITS) {
1816 node->edges[0] = NULL;
1817 node->edges[1] = NULL;
1818 node->n_rules = n_rules;
1819 } else { /* Need intermediate nodes. */
1820 struct trie_node *subnode = trie_branch_create(prefix,
1821 ofs + TRIE_PREFIX_BITS,
1822 plen - TRIE_PREFIX_BITS,
1824 int bit = get_bit_at(subnode->prefix, 0);
1825 node->nbits = TRIE_PREFIX_BITS;
1826 node->edges[bit] = subnode;
1827 node->edges[!bit] = NULL;
1834 trie_node_destroy(struct trie_node *node)
1840 trie_destroy(struct trie_node *node)
1843 trie_destroy(node->edges[0]);
1844 trie_destroy(node->edges[1]);
1850 trie_is_leaf(const struct trie_node *trie)
1852 return !trie->edges[0] && !trie->edges[1]; /* No children. */
1856 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1859 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1862 for (i = 0; i < nbits / 32; i++) {
1863 mask[i] = OVS_BE32_MAX;
1866 mask[i] |= htonl(~0u << (32 - nbits % 32));
1871 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
1874 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1876 ovs_be32 zeroes = 0;
1878 for (i = 0; i < nbits / 32; i++) {
1882 zeroes |= ~mask[i] & htonl(~0u << (32 - nbits % 32));
1885 return !zeroes; /* All 'nbits' bits set. */
1888 static struct trie_node **
1889 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
1892 return node->edges + be_get_bit_at(value, ofs);
1895 static const struct trie_node *
1896 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
1899 return node->edges[be_get_bit_at(value, ofs)];
1902 /* Return the prefix mask length necessary to find the longest-prefix match for
1903 * the '*value' in the prefix tree 'node'.
1904 * '*checkbits' is set to the number of bits in the prefix mask necessary to
1905 * determine a mismatch, in case there are longer prefixes in the tree below
1906 * the one that matched.
1909 trie_lookup_value(const struct trie_node *node, const ovs_be32 value[],
1910 unsigned int *checkbits)
1912 unsigned int plen = 0, match_len = 0;
1913 const struct trie_node *prev = NULL;
1915 for (; node; prev = node, node = trie_next_node(node, value, plen)) {
1916 unsigned int eqbits;
1917 /* Check if this edge can be followed. */
1918 eqbits = prefix_equal_bits(node->prefix, node->nbits, value, plen);
1920 if (eqbits < node->nbits) { /* Mismatch, nothing more to be found. */
1921 /* Bit at offset 'plen' differed. */
1922 *checkbits = plen + 1; /* Includes the first mismatching bit. */
1925 /* Full match, check if rules exist at this prefix length. */
1926 if (node->n_rules > 0) {
1930 /* Dead end, exclude the other branch if it exists. */
1931 *checkbits = !prev || trie_is_leaf(prev) ? plen : plen + 1;
1936 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
1937 unsigned int *checkbits)
1939 const struct mf_field *mf = trie->field;
1941 /* Check that current flow matches the prerequisites for the trie
1942 * field. Some match fields are used for multiple purposes, so we
1943 * must check that the trie is relevant for this flow. */
1944 if (mf_are_prereqs_ok(mf, flow)) {
1945 return trie_lookup_value(trie->root,
1946 &((ovs_be32 *)flow)[mf->flow_be32ofs],
1949 *checkbits = 0; /* Value not used in this case. */
1953 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
1954 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
1955 * 'miniflow_index' is not NULL. */
1957 minimask_get_prefix_len(const struct minimask *minimask,
1958 const struct mf_field *mf)
1960 unsigned int nbits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
1961 uint8_t u32_ofs = mf->flow_be32ofs;
1962 uint8_t u32_end = u32_ofs + mf->n_bytes / 4;
1964 for (; u32_ofs < u32_end; ++u32_ofs) {
1966 mask = ntohl((OVS_FORCE ovs_be32)minimask_get(minimask, u32_ofs));
1968 /* Validate mask, count the mask length. */
1971 return 0; /* No bits allowed after mask ended. */
1974 if (~mask & (~mask + 1)) {
1975 return 0; /* Mask not contiguous. */
1977 mask_tz = ctz32(mask);
1978 nbits += 32 - mask_tz;
1986 * This is called only when mask prefix is known to be CIDR and non-zero.
1987 * Relies on the fact that the flow and mask have the same map, and since
1988 * the mask is CIDR, the storage for the flow field exists even if it
1989 * happened to be zeros.
1991 static const ovs_be32 *
1992 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
1994 return miniflow_get_be32_values(&match->flow) +
1995 count_1bits(match->flow.map & ((UINT64_C(1) << mf->flow_be32ofs) - 1));
1998 /* Insert rule in to the prefix tree.
1999 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2002 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2004 const ovs_be32 *prefix = minimatch_get_prefix(&rule->match, trie->field);
2005 struct trie_node *node;
2006 struct trie_node **edge;
2009 /* Walk the tree. */
2010 for (edge = &trie->root;
2011 (node = *edge) != NULL;
2012 edge = trie_next_edge(node, prefix, ofs)) {
2013 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2015 if (eqbits < node->nbits) {
2016 /* Mismatch, new node needs to be inserted above. */
2017 int old_branch = get_bit_at(node->prefix, eqbits);
2019 /* New parent node. */
2020 *edge = trie_branch_create(prefix, ofs - eqbits, eqbits,
2021 ofs == mlen ? 1 : 0);
2023 /* Adjust old node for its new position in the tree. */
2024 node->prefix <<= eqbits;
2025 node->nbits -= eqbits;
2026 (*edge)->edges[old_branch] = node;
2028 /* Check if need a new branch for the new rule. */
2030 (*edge)->edges[!old_branch]
2031 = trie_branch_create(prefix, ofs, mlen - ofs, 1);
2035 /* Full match so far. */
2038 /* Full match at the current node, rule needs to be added here. */
2043 /* Must insert a new tree branch for the new rule. */
2044 *edge = trie_branch_create(prefix, ofs, mlen - ofs, 1);
2047 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2050 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2052 const ovs_be32 *prefix = minimatch_get_prefix(&rule->match, trie->field);
2053 struct trie_node *node;
2054 struct trie_node **edges[sizeof(union mf_value) * 8];
2055 int depth = 0, ofs = 0;
2057 /* Walk the tree. */
2058 for (edges[depth] = &trie->root;
2059 (node = *edges[depth]) != NULL;
2060 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
2061 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2062 if (eqbits < node->nbits) {
2063 /* Mismatch, nothing to be removed. This should never happen, as
2064 * only rules in the classifier are ever removed. */
2065 break; /* Log a warning. */
2067 /* Full match so far. */
2071 /* Full prefix match at the current node, remove rule here. */
2072 if (!node->n_rules) {
2073 break; /* Log a warning. */
2077 /* Check if can prune the tree. */
2078 while (!node->n_rules && !(node->edges[0] && node->edges[1])) {
2079 /* No rules and at most one child node, remove this node. */
2080 struct trie_node *next;
2081 next = node->edges[0] ? node->edges[0] : node->edges[1];
2084 if (node->nbits + next->nbits > TRIE_PREFIX_BITS) {
2085 break; /* Cannot combine. */
2087 /* Combine node with next. */
2088 next->prefix = node->prefix | next->prefix >> node->nbits;
2089 next->nbits += node->nbits;
2091 trie_node_destroy(node);
2092 /* Update the parent's edge. */
2093 *edges[depth] = next;
2094 if (next || !depth) {
2095 /* Branch not pruned or at root, nothing more to do. */
2098 node = *edges[--depth];
2103 /* Cannot go deeper. This should never happen, since only rules
2104 * that actually exist in the classifier are ever removed. */
2105 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");