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 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. */
54 struct cls_classifier {
55 int n_rules; /* Total number of rules. */
56 uint8_t n_flow_segments;
57 uint8_t flow_segments[CLS_MAX_INDICES]; /* Flow segment boundaries to use
58 * for staged lookup. */
59 struct hmap subtables; /* Contains "struct cls_subtable"s. */
60 struct cls_subtable_cache subtables_priority;
61 struct hmap partitions; /* Contains "struct cls_partition"s. */
62 struct cls_trie tries[CLS_MAX_TRIES]; /* Prefix tries. */
66 /* A set of rules that all have the same fields wildcarded. */
68 struct hmap_node hmap_node; /* Within struct cls_classifier 'subtables'
70 struct hmap rules; /* Contains "struct cls_rule"s. */
71 struct minimask mask; /* Wildcards for fields. */
72 int n_rules; /* Number of rules, including duplicates. */
73 unsigned int max_priority; /* Max priority of any rule in the subtable. */
74 unsigned int max_count; /* Count of max_priority rules. */
75 tag_type tag; /* Tag generated from mask for partitioning. */
76 uint8_t n_indices; /* How many indices to use. */
77 uint8_t index_ofs[CLS_MAX_INDICES]; /* u32 flow segment boundaries. */
78 struct hindex indices[CLS_MAX_INDICES]; /* Staged lookup indices. */
79 unsigned int trie_plen[CLS_MAX_TRIES]; /* Trie prefix length in 'mask'. */
82 /* Associates a metadata value (that is, a value of the OpenFlow 1.1+ metadata
83 * field) with tags for the "cls_subtable"s that contain rules that match that
85 struct cls_partition {
86 struct hmap_node hmap_node; /* In struct cls_classifier's 'partitions'
88 ovs_be64 metadata; /* metadata value for this partition. */
89 tag_type tags; /* OR of each flow's cls_subtable tag. */
90 struct tag_tracker tracker; /* Tracks the bits in 'tags'. */
96 static struct cls_subtable *find_subtable(const struct cls_classifier *,
97 const struct minimask *);
98 static struct cls_subtable *insert_subtable(struct cls_classifier *,
99 const struct minimask *);
101 static void destroy_subtable(struct cls_classifier *, struct cls_subtable *);
103 static void update_subtables_after_insertion(struct cls_classifier *,
104 struct cls_subtable *,
105 unsigned int new_priority);
106 static void update_subtables_after_removal(struct cls_classifier *,
107 struct cls_subtable *,
108 unsigned int del_priority);
110 static struct cls_rule *find_match_wc(const struct cls_subtable *,
111 const struct flow *, struct trie_ctx *,
112 unsigned int n_tries,
113 struct flow_wildcards *);
114 static struct cls_rule *find_equal(struct cls_subtable *,
115 const struct miniflow *, uint32_t hash);
116 static struct cls_rule *insert_rule(struct cls_classifier *,
117 struct cls_subtable *, struct cls_rule *);
119 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list. */
120 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD) \
121 for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
122 #define FOR_EACH_RULE_IN_LIST_SAFE(RULE, NEXT, HEAD) \
123 for ((RULE) = (HEAD); \
124 (RULE) != NULL && ((NEXT) = next_rule_in_list(RULE), true); \
127 static struct cls_rule *next_rule_in_list__(struct cls_rule *);
128 static struct cls_rule *next_rule_in_list(struct cls_rule *);
130 static unsigned int minimask_get_prefix_len(const struct minimask *,
131 const struct mf_field *);
132 static void trie_init(struct cls_classifier *, int trie_idx,
133 const struct mf_field *);
134 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
135 unsigned int *checkbits);
137 static void trie_destroy(struct trie_node *);
138 static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
139 static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
140 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
142 static bool mask_prefix_bits_set(const struct flow_wildcards *,
143 uint8_t be32ofs, unsigned int nbits);
146 cls_subtable_cache_init(struct cls_subtable_cache *array)
148 memset(array, 0, sizeof *array);
152 cls_subtable_cache_destroy(struct cls_subtable_cache *array)
154 free(array->subtables);
155 memset(array, 0, sizeof *array);
158 /* Array insertion. */
160 cls_subtable_cache_push_back(struct cls_subtable_cache *array,
161 struct cls_subtable_entry a)
163 if (array->size == array->alloc_size) {
164 array->subtables = x2nrealloc(array->subtables, &array->alloc_size,
168 array->subtables[array->size++] = a;
171 /* Only for rearranging entries in the same cache. */
173 cls_subtable_cache_splice(struct cls_subtable_entry *to,
174 struct cls_subtable_entry *start,
175 struct cls_subtable_entry *end)
178 /* Same as splicing entries to (start) from [end, to). */
179 struct cls_subtable_entry *temp = to;
180 to = start; start = end; end = temp;
183 while (start != end) {
184 struct cls_subtable_entry temp = *start;
186 memmove(to + 1, to, (start - to) * sizeof *to);
190 } /* Else nothing to be done. */
195 cls_subtable_cache_remove(struct cls_subtable_cache *array,
196 struct cls_subtable_entry *elem)
198 ssize_t size = (&array->subtables[array->size]
199 - (elem + 1)) * sizeof *elem;
201 memmove(elem, elem + 1, size);
206 #define CLS_SUBTABLE_CACHE_FOR_EACH(SUBTABLE, ITER, ARRAY) \
207 for (ITER = (ARRAY)->subtables; \
208 ITER < &(ARRAY)->subtables[(ARRAY)->size] \
209 && OVS_LIKELY(SUBTABLE = ITER->subtable); \
211 #define CLS_SUBTABLE_CACHE_FOR_EACH_CONTINUE(SUBTABLE, ITER, ARRAY) \
213 ITER < &(ARRAY)->subtables[(ARRAY)->size] \
214 && OVS_LIKELY(SUBTABLE = ITER->subtable); \
216 #define CLS_SUBTABLE_CACHE_FOR_EACH_REVERSE(SUBTABLE, ITER, ARRAY) \
217 for (ITER = &(ARRAY)->subtables[(ARRAY)->size]; \
218 ITER > (ARRAY)->subtables \
219 && OVS_LIKELY(SUBTABLE = (--ITER)->subtable);)
222 /* flow/miniflow/minimask/minimatch utilities.
223 * These are only used by the classifier, so place them here to allow
224 * for better optimization. */
226 static inline uint64_t
227 miniflow_get_map_in_range(const struct miniflow *miniflow,
228 uint8_t start, uint8_t end, unsigned int *offset)
230 uint64_t map = miniflow->map;
234 uint64_t msk = (UINT64_C(1) << start) - 1; /* 'start' LSBs set */
235 *offset = count_1bits(map & msk);
238 if (end < FLOW_U32S) {
239 uint64_t msk = (UINT64_C(1) << end) - 1; /* 'end' LSBs set */
245 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
246 * 'mask', given 'basis'.
248 * The hash values returned by this function are the same as those returned by
249 * miniflow_hash_in_minimask(), only the form of the arguments differ. */
250 static inline uint32_t
251 flow_hash_in_minimask(const struct flow *flow, const struct minimask *mask,
254 const uint32_t *flow_u32 = (const uint32_t *)flow;
255 const uint32_t *p = mask->masks.values;
260 for (map = mask->masks.map; map; map = zero_rightmost_1bit(map)) {
261 hash = mhash_add(hash, flow_u32[raw_ctz(map)] & *p++);
264 return mhash_finish(hash, (p - mask->masks.values) * 4);
267 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
268 * 'mask', given 'basis'.
270 * The hash values returned by this function are the same as those returned by
271 * flow_hash_in_minimask(), only the form of the arguments differ. */
272 static inline uint32_t
273 miniflow_hash_in_minimask(const struct miniflow *flow,
274 const struct minimask *mask, uint32_t basis)
276 const uint32_t *p = mask->masks.values;
277 uint32_t hash = basis;
280 MINIFLOW_FOR_EACH_IN_MAP(flow_u32, flow, mask->masks.map) {
281 hash = mhash_add(hash, flow_u32 & *p++);
284 return mhash_finish(hash, (p - mask->masks.values) * 4);
287 /* Returns a hash value for the bits of range [start, end) in 'flow',
288 * where there are 1-bits in 'mask', given 'hash'.
290 * The hash values returned by this function are the same as those returned by
291 * minimatch_hash_range(), only the form of the arguments differ. */
292 static inline uint32_t
293 flow_hash_in_minimask_range(const struct flow *flow,
294 const struct minimask *mask,
295 uint8_t start, uint8_t end, uint32_t *basis)
297 const uint32_t *flow_u32 = (const uint32_t *)flow;
299 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
301 const uint32_t *p = mask->masks.values + offset;
302 uint32_t hash = *basis;
304 for (; map; map = zero_rightmost_1bit(map)) {
305 hash = mhash_add(hash, flow_u32[raw_ctz(map)] & *p++);
308 *basis = hash; /* Allow continuation from the unfinished value. */
309 return mhash_finish(hash, (p - mask->masks.values) * 4);
312 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask. */
314 flow_wildcards_fold_minimask(struct flow_wildcards *wc,
315 const struct minimask *mask)
317 flow_union_with_miniflow(&wc->masks, &mask->masks);
320 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask
321 * in range [start, end). */
323 flow_wildcards_fold_minimask_range(struct flow_wildcards *wc,
324 const struct minimask *mask,
325 uint8_t start, uint8_t end)
327 uint32_t *dst_u32 = (uint32_t *)&wc->masks;
329 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
331 const uint32_t *p = mask->masks.values + offset;
333 for (; map; map = zero_rightmost_1bit(map)) {
334 dst_u32[raw_ctz(map)] |= *p++;
338 /* Returns a hash value for 'flow', given 'basis'. */
339 static inline uint32_t
340 miniflow_hash(const struct miniflow *flow, uint32_t basis)
342 const uint32_t *p = flow->values;
343 uint32_t hash = basis;
344 uint64_t hash_map = 0;
347 for (map = flow->map; map; map = zero_rightmost_1bit(map)) {
349 hash = mhash_add(hash, *p);
350 hash_map |= rightmost_1bit(map);
354 hash = mhash_add(hash, hash_map);
355 hash = mhash_add(hash, hash_map >> 32);
357 return mhash_finish(hash, p - flow->values);
360 /* Returns a hash value for 'mask', given 'basis'. */
361 static inline uint32_t
362 minimask_hash(const struct minimask *mask, uint32_t basis)
364 return miniflow_hash(&mask->masks, basis);
367 /* Returns a hash value for 'match', given 'basis'. */
368 static inline uint32_t
369 minimatch_hash(const struct minimatch *match, uint32_t basis)
371 return miniflow_hash(&match->flow, minimask_hash(&match->mask, basis));
374 /* Returns a hash value for the bits of range [start, end) in 'minimatch',
377 * The hash values returned by this function are the same as those returned by
378 * flow_hash_in_minimask_range(), only the form of the arguments differ. */
379 static inline uint32_t
380 minimatch_hash_range(const struct minimatch *match, uint8_t start, uint8_t end,
384 const uint32_t *p, *q;
385 uint32_t hash = *basis;
388 n = count_1bits(miniflow_get_map_in_range(&match->mask.masks, start, end,
390 q = match->mask.masks.values + offset;
391 p = match->flow.values + offset;
393 for (i = 0; i < n; i++) {
394 hash = mhash_add(hash, p[i] & q[i]);
396 *basis = hash; /* Allow continuation from the unfinished value. */
397 return mhash_finish(hash, (offset + n) * 4);
403 /* Initializes 'rule' to match packets specified by 'match' at the given
404 * 'priority'. 'match' must satisfy the invariant described in the comment at
405 * the definition of struct match.
407 * The caller must eventually destroy 'rule' with cls_rule_destroy().
409 * (OpenFlow uses priorities between 0 and UINT16_MAX, inclusive, but
410 * internally Open vSwitch supports a wider range.) */
412 cls_rule_init(struct cls_rule *rule,
413 const struct match *match, unsigned int priority)
415 minimatch_init(&rule->match, match);
416 rule->priority = priority;
419 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
421 cls_rule_init_from_minimatch(struct cls_rule *rule,
422 const struct minimatch *match,
423 unsigned int priority)
425 minimatch_clone(&rule->match, match);
426 rule->priority = priority;
429 /* Initializes 'dst' as a copy of 'src'.
431 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
433 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
435 minimatch_clone(&dst->match, &src->match);
436 dst->priority = src->priority;
439 /* Initializes 'dst' with the data in 'src', destroying 'src'.
441 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
443 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
445 minimatch_move(&dst->match, &src->match);
446 dst->priority = src->priority;
449 /* Frees memory referenced by 'rule'. Doesn't free 'rule' itself (it's
450 * normally embedded into a larger structure).
452 * ('rule' must not currently be in a classifier.) */
454 cls_rule_destroy(struct cls_rule *rule)
456 minimatch_destroy(&rule->match);
459 /* Returns true if 'a' and 'b' match the same packets at the same priority,
460 * false if they differ in some way. */
462 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
464 return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
467 /* Returns a hash value for 'rule', folding in 'basis'. */
469 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
471 return minimatch_hash(&rule->match, hash_int(rule->priority, basis));
474 /* Appends a string describing 'rule' to 's'. */
476 cls_rule_format(const struct cls_rule *rule, struct ds *s)
478 minimatch_format(&rule->match, s, rule->priority);
481 /* Returns true if 'rule' matches every packet, false otherwise. */
483 cls_rule_is_catchall(const struct cls_rule *rule)
485 return minimask_is_catchall(&rule->match.mask);
488 /* Initializes 'cls' as a classifier that initially contains no classification
491 classifier_init(struct classifier *cls_, const uint8_t *flow_segments)
493 struct cls_classifier *cls = xmalloc(sizeof *cls);
495 fat_rwlock_init(&cls_->rwlock);
500 hmap_init(&cls->subtables);
501 cls_subtable_cache_init(&cls->subtables_priority);
502 hmap_init(&cls->partitions);
503 cls->n_flow_segments = 0;
505 while (cls->n_flow_segments < CLS_MAX_INDICES
506 && *flow_segments < FLOW_U32S) {
507 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
513 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
514 * caller's responsibility. */
516 classifier_destroy(struct classifier *cls_)
519 struct cls_classifier *cls = cls_->cls;
520 struct cls_subtable *partition, *next_partition;
521 struct cls_subtable *subtable, *next_subtable;
524 fat_rwlock_destroy(&cls_->rwlock);
529 for (i = 0; i < cls->n_tries; i++) {
530 trie_destroy(cls->tries[i].root);
533 HMAP_FOR_EACH_SAFE (subtable, next_subtable, hmap_node,
535 destroy_subtable(cls, subtable);
537 hmap_destroy(&cls->subtables);
539 HMAP_FOR_EACH_SAFE (partition, next_partition, hmap_node,
541 hmap_remove(&cls->partitions, &partition->hmap_node);
544 hmap_destroy(&cls->partitions);
546 cls_subtable_cache_destroy(&cls->subtables_priority);
551 /* We use uint64_t as a set for the fields below. */
552 BUILD_ASSERT_DECL(MFF_N_IDS <= 64);
554 /* Set the fields for which prefix lookup should be performed. */
556 classifier_set_prefix_fields(struct classifier *cls_,
557 const enum mf_field_id *trie_fields,
558 unsigned int n_fields)
560 struct cls_classifier *cls = cls_->cls;
564 for (i = 0, trie = 0; i < n_fields && trie < CLS_MAX_TRIES; i++) {
565 const struct mf_field *field = mf_from_id(trie_fields[i]);
566 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
567 /* Incompatible field. This is the only place where we
568 * enforce these requirements, but the rest of the trie code
569 * depends on the flow_be32ofs to be non-negative and the
570 * field length to be a multiple of 32 bits. */
574 if (fields & (UINT64_C(1) << trie_fields[i])) {
575 /* Duplicate field, there is no need to build more than
576 * one index for any one field. */
579 fields |= UINT64_C(1) << trie_fields[i];
581 if (trie >= cls->n_tries || field != cls->tries[trie].field) {
582 trie_init(cls, trie, field);
587 /* Destroy the rest. */
588 for (i = trie; i < cls->n_tries; i++) {
589 trie_init(cls, i, NULL);
595 trie_init(struct cls_classifier *cls, int trie_idx,
596 const struct mf_field *field)
598 struct cls_trie *trie = &cls->tries[trie_idx];
599 struct cls_subtable *subtable;
600 struct cls_subtable_entry *iter;
602 if (trie_idx < cls->n_tries) {
603 trie_destroy(trie->root);
608 /* Add existing rules to the trie. */
609 CLS_SUBTABLE_CACHE_FOR_EACH (subtable, iter, &cls->subtables_priority) {
612 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
613 /* Initialize subtable's prefix length on this field. */
614 subtable->trie_plen[trie_idx] = plen;
617 struct cls_rule *head;
619 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
620 struct cls_rule *rule;
622 FOR_EACH_RULE_IN_LIST (rule, head) {
623 trie_insert(trie, rule, plen);
630 /* Returns true if 'cls' contains no classification rules, false otherwise. */
632 classifier_is_empty(const struct classifier *cls)
634 return cls->cls->n_rules == 0;
637 /* Returns the number of rules in 'cls'. */
639 classifier_count(const struct classifier *cls)
641 return cls->cls->n_rules;
645 hash_metadata(ovs_be64 metadata_)
647 uint64_t metadata = (OVS_FORCE uint64_t) metadata_;
648 return hash_uint64(metadata);
651 static struct cls_partition *
652 find_partition(const struct cls_classifier *cls, ovs_be64 metadata,
655 struct cls_partition *partition;
657 HMAP_FOR_EACH_IN_BUCKET (partition, hmap_node, hash, &cls->partitions) {
658 if (partition->metadata == metadata) {
666 static struct cls_partition *
667 create_partition(struct cls_classifier *cls, struct cls_subtable *subtable,
670 uint32_t hash = hash_metadata(metadata);
671 struct cls_partition *partition = find_partition(cls, metadata, hash);
673 partition = xmalloc(sizeof *partition);
674 partition->metadata = metadata;
676 tag_tracker_init(&partition->tracker);
677 hmap_insert(&cls->partitions, &partition->hmap_node, hash);
679 tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
683 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
684 * must not modify or free it.
686 * If 'cls' already contains an identical rule (including wildcards, values of
687 * fixed fields, and priority), replaces the old rule by 'rule' and returns the
688 * rule that was replaced. The caller takes ownership of the returned rule and
689 * is thus responsible for destroying it with cls_rule_destroy(), freeing the
690 * memory block in which it resides, etc., as necessary.
692 * Returns NULL if 'cls' does not contain a rule with an identical key, after
693 * inserting the new rule. In this case, no rules are displaced by the new
694 * rule, even rules that cannot have any effect because the new rule matches a
695 * superset of their flows and has higher priority. */
697 classifier_replace(struct classifier *cls_, struct cls_rule *rule)
699 struct cls_classifier *cls = cls_->cls;
700 struct cls_rule *old_rule;
701 struct cls_subtable *subtable;
703 subtable = find_subtable(cls, &rule->match.mask);
705 subtable = insert_subtable(cls, &rule->match.mask);
708 old_rule = insert_rule(cls, subtable, rule);
712 if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
713 ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
714 rule->partition = create_partition(cls, subtable, metadata);
716 rule->partition = NULL;
722 for (i = 0; i < cls->n_tries; i++) {
723 if (subtable->trie_plen[i]) {
724 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
728 rule->partition = old_rule->partition;
733 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
734 * must not modify or free it.
736 * 'cls' must not contain an identical rule (including wildcards, values of
737 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
740 classifier_insert(struct classifier *cls, struct cls_rule *rule)
742 struct cls_rule *displaced_rule = classifier_replace(cls, rule);
743 ovs_assert(!displaced_rule);
746 /* Removes 'rule' from 'cls'. It is the caller's responsibility to destroy
747 * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
748 * resides, etc., as necessary. */
750 classifier_remove(struct classifier *cls_, struct cls_rule *rule)
752 struct cls_classifier *cls = cls_->cls;
753 struct cls_partition *partition;
754 struct cls_rule *head;
755 struct cls_subtable *subtable;
758 subtable = find_subtable(cls, &rule->match.mask);
760 for (i = 0; i < cls->n_tries; i++) {
761 if (subtable->trie_plen[i]) {
762 trie_remove(&cls->tries[i], rule, subtable->trie_plen[i]);
766 /* Remove rule node from indices. */
767 for (i = 0; i < subtable->n_indices; i++) {
768 hindex_remove(&subtable->indices[i], &rule->index_nodes[i]);
771 head = find_equal(subtable, &rule->match.flow, rule->hmap_node.hash);
773 list_remove(&rule->list);
774 } else if (list_is_empty(&rule->list)) {
775 hmap_remove(&subtable->rules, &rule->hmap_node);
777 struct cls_rule *next = CONTAINER_OF(rule->list.next,
778 struct cls_rule, list);
780 list_remove(&rule->list);
781 hmap_replace(&subtable->rules, &rule->hmap_node, &next->hmap_node);
784 partition = rule->partition;
786 tag_tracker_subtract(&partition->tracker, &partition->tags,
788 if (!partition->tags) {
789 hmap_remove(&cls->partitions, &partition->hmap_node);
794 if (--subtable->n_rules == 0) {
795 destroy_subtable(cls, subtable);
797 update_subtables_after_removal(cls, subtable, rule->priority);
803 /* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
804 * subtables which have more than 'match_plen' bits in their corresponding
805 * field at offset 'be32ofs'. If skipped, 'maskbits' prefix bits should be
806 * unwildcarded to quarantee datapath flow matches only packets it should. */
808 const struct cls_trie *trie;
809 bool lookup_done; /* Status of the lookup. */
810 uint8_t be32ofs; /* U32 offset of the field in question. */
811 unsigned int match_plen; /* Longest prefix than could possibly match. */
812 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
816 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
819 ctx->be32ofs = trie->field->flow_be32ofs;
820 ctx->lookup_done = false;
824 lookahead_subtable(const struct cls_subtable_entry *subtables)
826 ovs_prefetch_range(subtables->subtable, sizeof *subtables->subtable);
827 ovs_prefetch_range(subtables->mask_values, 1);
830 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
831 * Returns a null pointer if no rules in 'cls' match 'flow'. If multiple rules
832 * of equal priority match 'flow', returns one arbitrarily.
834 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
835 * set of bits that were significant in the lookup. At some point
836 * earlier, 'wc' should have been initialized (e.g., by
837 * flow_wildcards_init_catchall()). */
839 classifier_lookup(const struct classifier *cls_, const struct flow *flow,
840 struct flow_wildcards *wc)
842 struct cls_classifier *cls = cls_->cls;
843 const struct cls_partition *partition;
845 struct cls_rule *best;
846 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
848 struct cls_subtable_entry *subtables = cls->subtables_priority.subtables;
849 int n_subtables = cls->subtables_priority.size;
850 int64_t best_priority = -1;
852 /* Prefetch the subtables array. */
853 ovs_prefetch_range(subtables, n_subtables * sizeof *subtables);
855 /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
856 * then 'flow' cannot possibly match in 'subtable':
858 * - If flow->metadata maps to a given 'partition', then we can use
859 * 'tags' for 'partition->tags'.
861 * - If flow->metadata has no partition, then no rule in 'cls' has an
862 * exact-match for flow->metadata. That means that we don't need to
863 * search any subtable that includes flow->metadata in its mask.
865 * In either case, we always need to search any cls_subtables that do not
866 * include flow->metadata in its mask. One way to do that would be to
867 * check the "cls_subtable"s explicitly for that, but that would require an
868 * extra branch per subtable. Instead, we mark such a cls_subtable's
869 * 'tags' as TAG_ALL and make sure that 'tags' is never empty. This means
870 * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
871 * need a special case.
873 partition = (hmap_is_empty(&cls->partitions)
875 : find_partition(cls, flow->metadata,
876 hash_metadata(flow->metadata)));
877 tags = partition ? partition->tags : TAG_ARBITRARY;
879 /* Initialize trie contexts for match_find_wc(). */
880 for (i = 0; i < cls->n_tries; i++) {
881 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
884 /* Prefetch the first subtables. */
885 if (n_subtables > 1) {
886 lookahead_subtable(subtables);
887 lookahead_subtable(subtables + 1);
891 for (i = 0; OVS_LIKELY(i < n_subtables); i++) {
892 struct cls_rule *rule;
894 if ((int64_t)subtables[i].max_priority <= best_priority) {
895 /* Subtables are in descending priority order,
896 * can not find anything better. */
900 /* Prefetch a forthcoming subtable. */
901 if (i + 2 < n_subtables) {
902 lookahead_subtable(&subtables[i + 2]);
905 if (!tag_intersects(tags, subtables[i].tag)) {
909 rule = find_match_wc(subtables[i].subtable, flow, trie_ctx,
911 if (rule && (int64_t)rule->priority > best_priority) {
912 best_priority = (int64_t)rule->priority;
920 /* Returns true if 'target' satisifies 'match', that is, if each bit for which
921 * 'match' specifies a particular value has the correct value in 'target'. */
923 minimatch_matches_miniflow(const struct minimatch *match,
924 const struct miniflow *target)
926 const uint32_t *flowp = (const uint32_t *)match->flow.values;
927 const uint32_t *maskp = (const uint32_t *)match->mask.masks.values;
930 MINIFLOW_FOR_EACH_IN_MAP(target_u32, target, match->mask.masks.map) {
931 if ((*flowp++ ^ target_u32) & *maskp++) {
939 static inline struct cls_rule *
940 find_match_miniflow(const struct cls_subtable *subtable,
941 const struct miniflow *flow,
944 struct cls_rule *rule;
946 HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &subtable->rules) {
947 if (minimatch_matches_miniflow(&rule->match, flow)) {
955 /* Finds and returns the highest-priority rule in 'cls' that matches
956 * 'miniflow'. Returns a null pointer if no rules in 'cls' match 'flow'.
957 * If multiple rules of equal priority match 'flow', returns one arbitrarily.
959 * This function is optimized for the userspace datapath, which only ever has
960 * one priority value for it's flows!
962 struct cls_rule *classifier_lookup_miniflow_first(const struct classifier *cls_,
963 const struct miniflow *flow)
965 struct cls_classifier *cls = cls_->cls;
966 struct cls_subtable *subtable;
967 struct cls_subtable_entry *iter;
969 CLS_SUBTABLE_CACHE_FOR_EACH (subtable, iter, &cls->subtables_priority) {
970 struct cls_rule *rule;
972 rule = find_match_miniflow(subtable, flow,
973 miniflow_hash_in_minimask(flow,
984 /* Finds and returns a rule in 'cls' with exactly the same priority and
985 * matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
986 * contain an exact match. */
988 classifier_find_rule_exactly(const struct classifier *cls_,
989 const struct cls_rule *target)
991 struct cls_classifier *cls = cls_->cls;
992 struct cls_rule *head, *rule;
993 struct cls_subtable *subtable;
995 subtable = find_subtable(cls, &target->match.mask);
1000 /* Skip if there is no hope. */
1001 if (target->priority > subtable->max_priority) {
1005 head = find_equal(subtable, &target->match.flow,
1006 miniflow_hash_in_minimask(&target->match.flow,
1007 &target->match.mask, 0));
1008 FOR_EACH_RULE_IN_LIST (rule, head) {
1009 if (target->priority >= rule->priority) {
1010 return target->priority == rule->priority ? rule : NULL;
1016 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
1017 * same matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
1018 * contain an exact match. */
1020 classifier_find_match_exactly(const struct classifier *cls,
1021 const struct match *target,
1022 unsigned int priority)
1024 struct cls_rule *retval;
1027 cls_rule_init(&cr, target, priority);
1028 retval = classifier_find_rule_exactly(cls, &cr);
1029 cls_rule_destroy(&cr);
1034 /* Checks if 'target' would overlap any other rule in 'cls'. Two rules are
1035 * considered to overlap if both rules have the same priority and a packet
1036 * could match both. */
1038 classifier_rule_overlaps(const struct classifier *cls_,
1039 const struct cls_rule *target)
1041 struct cls_classifier *cls = cls_->cls;
1042 struct cls_subtable *subtable;
1043 struct cls_subtable_entry *iter;
1045 /* Iterate subtables in the descending max priority order. */
1046 CLS_SUBTABLE_CACHE_FOR_EACH (subtable, iter, &cls->subtables_priority) {
1047 uint32_t storage[FLOW_U32S];
1048 struct minimask mask;
1049 struct cls_rule *head;
1051 if (target->priority > iter->max_priority) {
1052 break; /* Can skip this and the rest of the subtables. */
1055 minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
1056 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
1057 struct cls_rule *rule;
1059 FOR_EACH_RULE_IN_LIST (rule, head) {
1060 if (rule->priority < target->priority) {
1061 break; /* Rules in descending priority order. */
1063 if (rule->priority == target->priority
1064 && miniflow_equal_in_minimask(&target->match.flow,
1065 &rule->match.flow, &mask)) {
1075 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
1076 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
1077 * function returns true if, for every field:
1079 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
1082 * - 'criteria' wildcards the field,
1084 * Conversely, 'rule' does not match 'criteria' and this function returns false
1085 * if, for at least one field:
1087 * - 'criteria' and 'rule' specify different values for the field, or
1089 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
1091 * Equivalently, the truth table for whether a field matches is:
1096 * r +---------+---------+
1097 * i wild | yes | yes |
1099 * e +---------+---------+
1100 * r exact | no |if values|
1102 * a +---------+---------+
1104 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
1105 * commands and by OpenFlow 1.0 aggregate and flow stats.
1107 * Ignores rule->priority. */
1109 cls_rule_is_loose_match(const struct cls_rule *rule,
1110 const struct minimatch *criteria)
1112 return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
1113 && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
1120 rule_matches(const struct cls_rule *rule, const struct cls_rule *target)
1123 || miniflow_equal_in_minimask(&rule->match.flow,
1124 &target->match.flow,
1125 &target->match.mask));
1128 static struct cls_rule *
1129 search_subtable(const struct cls_subtable *subtable,
1130 const struct cls_rule *target)
1132 if (!target || !minimask_has_extra(&subtable->mask, &target->match.mask)) {
1133 struct cls_rule *rule;
1135 HMAP_FOR_EACH (rule, hmap_node, &subtable->rules) {
1136 if (rule_matches(rule, target)) {
1144 /* Initializes 'cursor' for iterating through rules in 'cls':
1146 * - If 'target' is null, the cursor will visit every rule in 'cls'.
1148 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1149 * such that cls_rule_is_loose_match(rule, target) returns true.
1151 * Ignores target->priority. */
1153 cls_cursor_init(struct cls_cursor *cursor, const struct classifier *cls,
1154 const struct cls_rule *target)
1156 cursor->cls = cls->cls;
1157 cursor->target = target && !cls_rule_is_catchall(target) ? target : NULL;
1160 /* Returns the first matching cls_rule in 'cursor''s iteration, or a null
1161 * pointer if there are no matches. */
1163 cls_cursor_first(struct cls_cursor *cursor)
1165 struct cls_subtable *subtable;
1167 HMAP_FOR_EACH (subtable, hmap_node, &cursor->cls->subtables) {
1168 struct cls_rule *rule = search_subtable(subtable, cursor->target);
1170 cursor->subtable = subtable;
1178 /* Returns the next matching cls_rule in 'cursor''s iteration, or a null
1179 * pointer if there are no more matches. */
1181 cls_cursor_next(struct cls_cursor *cursor, const struct cls_rule *rule_)
1183 struct cls_rule *rule = CONST_CAST(struct cls_rule *, rule_);
1184 const struct cls_subtable *subtable;
1185 struct cls_rule *next;
1187 next = next_rule_in_list__(rule);
1188 if (next->priority < rule->priority) {
1192 /* 'next' is the head of the list, that is, the rule that is included in
1193 * the subtable's hmap. (This is important when the classifier contains
1194 * rules that differ only in priority.) */
1196 HMAP_FOR_EACH_CONTINUE (rule, hmap_node, &cursor->subtable->rules) {
1197 if (rule_matches(rule, cursor->target)) {
1202 subtable = cursor->subtable;
1203 HMAP_FOR_EACH_CONTINUE (subtable, hmap_node, &cursor->cls->subtables) {
1204 rule = search_subtable(subtable, cursor->target);
1206 cursor->subtable = subtable;
1214 static struct cls_subtable *
1215 find_subtable(const struct cls_classifier *cls, const struct minimask *mask)
1217 struct cls_subtable *subtable;
1219 HMAP_FOR_EACH_IN_BUCKET (subtable, hmap_node, minimask_hash(mask, 0),
1221 if (minimask_equal(mask, &subtable->mask)) {
1228 static struct cls_subtable *
1229 insert_subtable(struct cls_classifier *cls, const struct minimask *mask)
1231 uint32_t hash = minimask_hash(mask, 0);
1232 struct cls_subtable *subtable;
1234 struct flow_wildcards old, new;
1236 struct cls_subtable_entry elem;
1238 subtable = xzalloc(sizeof *subtable);
1239 hmap_init(&subtable->rules);
1240 minimask_clone(&subtable->mask, mask);
1242 /* Init indices for segmented lookup, if any. */
1243 flow_wildcards_init_catchall(&new);
1246 for (i = 0; i < cls->n_flow_segments; i++) {
1247 flow_wildcards_fold_minimask_range(&new, mask, prev,
1248 cls->flow_segments[i]);
1249 /* Add an index if it adds mask bits. */
1250 if (!flow_wildcards_equal(&new, &old)) {
1251 hindex_init(&subtable->indices[index]);
1252 subtable->index_ofs[index] = cls->flow_segments[i];
1256 prev = cls->flow_segments[i];
1258 /* Check if the rest of the subtable's mask adds any bits,
1259 * and remove the last index if it doesn't. */
1261 flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U32S);
1262 if (flow_wildcards_equal(&new, &old)) {
1264 subtable->index_ofs[index] = 0;
1265 hindex_destroy(&subtable->indices[index]);
1268 subtable->n_indices = index;
1270 subtable->tag = (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1271 ? tag_create_deterministic(hash)
1274 for (i = 0; i < cls->n_tries; i++) {
1275 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1276 cls->tries[i].field);
1279 hmap_insert(&cls->subtables, &subtable->hmap_node, hash);
1280 elem.subtable = subtable;
1281 elem.mask_values = subtable->mask.masks.values;
1282 elem.tag = subtable->tag;
1283 elem.max_priority = subtable->max_priority;
1284 cls_subtable_cache_push_back(&cls->subtables_priority, elem);
1290 destroy_subtable(struct cls_classifier *cls, struct cls_subtable *subtable)
1293 struct cls_subtable *table = NULL;
1294 struct cls_subtable_entry *iter;
1296 CLS_SUBTABLE_CACHE_FOR_EACH (table, iter, &cls->subtables_priority) {
1297 if (table == subtable) {
1298 cls_subtable_cache_remove(&cls->subtables_priority, iter);
1303 for (i = 0; i < subtable->n_indices; i++) {
1304 hindex_destroy(&subtable->indices[i]);
1306 minimask_destroy(&subtable->mask);
1307 hmap_remove(&cls->subtables, &subtable->hmap_node);
1308 hmap_destroy(&subtable->rules);
1312 /* This function performs the following updates for 'subtable' in 'cls'
1313 * following the addition of a new rule with priority 'new_priority' to
1316 * - Update 'subtable->max_priority' and 'subtable->max_count' if necessary.
1318 * - Update 'subtable''s position in 'cls->subtables_priority' if necessary.
1320 * This function should only be called after adding a new rule, not after
1321 * replacing a rule by an identical one or modifying a rule in-place. */
1323 update_subtables_after_insertion(struct cls_classifier *cls,
1324 struct cls_subtable *subtable,
1325 unsigned int new_priority)
1327 if (new_priority == subtable->max_priority) {
1328 ++subtable->max_count;
1329 } else if (new_priority > subtable->max_priority) {
1330 struct cls_subtable *table;
1331 struct cls_subtable_entry *iter, *subtable_iter = NULL;
1333 subtable->max_priority = new_priority;
1334 subtable->max_count = 1;
1336 /* Possibly move 'subtable' earlier in the priority list. If we break
1337 * out of the loop, then 'subtable_iter' should be moved just before
1338 * 'iter'. If the loop terminates normally, then 'iter' will be the
1339 * first list element and we'll move subtable just before that
1340 * (e.g. to the front of the list). */
1341 CLS_SUBTABLE_CACHE_FOR_EACH_REVERSE (table, iter, &cls->subtables_priority) {
1342 if (table == subtable) {
1343 subtable_iter = iter; /* Locate the subtable as we go. */
1344 iter->max_priority = new_priority;
1345 } else if (table->max_priority >= new_priority) {
1346 ovs_assert(subtable_iter != NULL);
1352 /* Move 'subtable' just before 'iter' (unless it's already there). */
1353 if (iter != subtable_iter) {
1354 cls_subtable_cache_splice(iter, subtable_iter, subtable_iter + 1);
1359 /* This function performs the following updates for 'subtable' in 'cls'
1360 * following the deletion of a rule with priority 'del_priority' from
1363 * - Update 'subtable->max_priority' and 'subtable->max_count' if necessary.
1365 * - Update 'subtable''s position in 'cls->subtables_priority' if necessary.
1367 * This function should only be called after removing a rule, not after
1368 * replacing a rule by an identical one or modifying a rule in-place. */
1370 update_subtables_after_removal(struct cls_classifier *cls,
1371 struct cls_subtable *subtable,
1372 unsigned int del_priority)
1374 if (del_priority == subtable->max_priority && --subtable->max_count == 0) {
1375 struct cls_rule *head;
1376 struct cls_subtable *table;
1377 struct cls_subtable_entry *iter, *subtable_iter = NULL;
1379 subtable->max_priority = 0;
1380 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
1381 if (head->priority > subtable->max_priority) {
1382 subtable->max_priority = head->priority;
1383 subtable->max_count = 1;
1384 } else if (head->priority == subtable->max_priority) {
1385 ++subtable->max_count;
1389 /* Possibly move 'subtable' later in the priority list. If we break
1390 * out of the loop, then 'subtable' should be moved just before that
1391 * 'iter'. If the loop terminates normally, then 'iter' will be the
1392 * list head and we'll move subtable just before that (e.g. to the back
1394 CLS_SUBTABLE_CACHE_FOR_EACH (table, iter, &cls->subtables_priority) {
1395 if (table == subtable) {
1396 subtable_iter = iter; /* Locate the subtable as we go. */
1397 iter->max_priority = subtable->max_priority;
1398 } else if (table->max_priority <= subtable->max_priority) {
1399 ovs_assert(subtable_iter != NULL);
1404 /* Move 'subtable' just before 'iter' (unless it's already there). */
1405 if (iter != subtable_iter) {
1406 cls_subtable_cache_splice(iter, subtable_iter, subtable_iter + 1);
1416 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1417 * lookup results. */
1419 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1420 const unsigned int field_plen[CLS_MAX_TRIES],
1421 const struct range ofs, const struct flow *flow,
1422 struct flow_wildcards *wc)
1426 /* Check if we could avoid fully unwildcarding the next level of
1427 * fields using the prefix tries. The trie checks are done only as
1428 * needed to avoid folding in additional bits to the wildcards mask. */
1429 for (j = 0; j < n_tries; j++) {
1430 /* Is the trie field relevant for this subtable? */
1431 if (field_plen[j]) {
1432 struct trie_ctx *ctx = &trie_ctx[j];
1433 uint8_t be32ofs = ctx->be32ofs;
1435 /* Is the trie field within the current range of fields? */
1436 if (be32ofs >= ofs.start && be32ofs < ofs.end) {
1437 /* On-demand trie lookup. */
1438 if (!ctx->lookup_done) {
1439 ctx->match_plen = trie_lookup(ctx->trie, flow,
1441 ctx->lookup_done = true;
1443 /* Possible to skip the rest of the subtable if subtable's
1444 * prefix on the field is longer than what is known to match
1445 * based on the trie lookup. */
1446 if (field_plen[j] > ctx->match_plen) {
1447 /* RFC: We want the trie lookup to never result in
1448 * unwildcarding any bits that would not be unwildcarded
1449 * otherwise. Since the trie is shared by the whole
1450 * classifier, it is possible that the 'maskbits' contain
1451 * bits that are irrelevant for the partition of the
1452 * classifier relevant for the current flow. */
1454 /* Can skip if the field is already unwildcarded. */
1455 if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1458 /* Check that the trie result will not unwildcard more bits
1459 * than this stage will. */
1460 if (ctx->maskbits <= field_plen[j]) {
1461 /* Unwildcard the bits and skip the rest. */
1462 mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1463 /* Note: Prerequisite already unwildcarded, as the only
1464 * prerequisite of the supported trie lookup fields is
1465 * the ethertype, which is currently always
1477 static inline struct cls_rule *
1478 find_match(const struct cls_subtable *subtable, const struct flow *flow,
1481 struct cls_rule *rule;
1483 HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &subtable->rules) {
1484 if (minimatch_matches_flow(&rule->match, flow)) {
1492 static struct cls_rule *
1493 find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
1494 struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1495 struct flow_wildcards *wc)
1497 uint32_t basis = 0, hash;
1498 struct cls_rule *rule = NULL;
1502 if (OVS_UNLIKELY(!wc)) {
1503 return find_match(subtable, flow,
1504 flow_hash_in_minimask(flow, &subtable->mask, 0));
1508 /* Try to finish early by checking fields in segments. */
1509 for (i = 0; i < subtable->n_indices; i++) {
1510 struct hindex_node *inode;
1511 ofs.end = subtable->index_ofs[i];
1513 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1517 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1519 ofs.start = ofs.end;
1520 inode = hindex_node_with_hash(&subtable->indices[i], hash);
1522 /* No match, can stop immediately, but must fold in the mask
1523 * covered so far. */
1527 /* If we have narrowed down to a single rule already, check whether
1528 * that rule matches. If it does match, then we're done. If it does
1529 * not match, then we know that we will never get a match, but we do
1530 * not yet know how many wildcards we need to fold into 'wc' so we
1531 * continue iterating through indices to find that out. (We won't
1532 * waste time calling minimatch_matches_flow() again because we've set
1535 * This check shows a measurable benefit with non-trivial flow tables.
1537 * (Rare) hash collisions may cause us to miss the opportunity for this
1539 if (!inode->s && !rule) {
1540 ASSIGN_CONTAINER(rule, inode - i, index_nodes);
1541 if (minimatch_matches_flow(&rule->match, flow)) {
1546 ofs.end = FLOW_U32S;
1547 /* Trie check for the final range. */
1548 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1552 /* Multiple potential matches exist, look for one. */
1553 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1555 rule = find_match(subtable, flow, hash);
1557 /* We already narrowed the matching candidates down to just 'rule',
1558 * but it didn't match. */
1562 /* Must unwildcard all the fields, as they were looked at. */
1563 flow_wildcards_fold_minimask(wc, &subtable->mask);
1567 /* Must unwildcard the fields looked up so far, if any. */
1569 flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, ofs.start);
1574 static struct cls_rule *
1575 find_equal(struct cls_subtable *subtable, const struct miniflow *flow,
1578 struct cls_rule *head;
1580 HMAP_FOR_EACH_WITH_HASH (head, hmap_node, hash, &subtable->rules) {
1581 if (miniflow_equal(&head->match.flow, flow)) {
1588 static struct cls_rule *
1589 insert_rule(struct cls_classifier *cls, struct cls_subtable *subtable,
1590 struct cls_rule *new)
1592 struct cls_rule *head;
1593 struct cls_rule *old = NULL;
1595 uint32_t basis = 0, hash;
1596 uint8_t prev_be32ofs = 0;
1598 /* Add new node to segment indices. */
1599 for (i = 0; i < subtable->n_indices; i++) {
1600 hash = minimatch_hash_range(&new->match, prev_be32ofs,
1601 subtable->index_ofs[i], &basis);
1602 hindex_insert(&subtable->indices[i], &new->index_nodes[i], hash);
1603 prev_be32ofs = subtable->index_ofs[i];
1605 hash = minimatch_hash_range(&new->match, prev_be32ofs, FLOW_U32S, &basis);
1606 head = find_equal(subtable, &new->match.flow, hash);
1608 hmap_insert(&subtable->rules, &new->hmap_node, hash);
1609 list_init(&new->list);
1612 /* Scan the list for the insertion point that will keep the list in
1613 * order of decreasing priority. */
1614 struct cls_rule *rule;
1616 new->hmap_node.hash = hash; /* Otherwise done by hmap_insert. */
1618 FOR_EACH_RULE_IN_LIST (rule, head) {
1619 if (new->priority >= rule->priority) {
1621 /* 'new' is the new highest-priority flow in the list. */
1622 hmap_replace(&subtable->rules,
1623 &rule->hmap_node, &new->hmap_node);
1626 if (new->priority == rule->priority) {
1627 list_replace(&new->list, &rule->list);
1631 list_insert(&rule->list, &new->list);
1637 /* Insert 'new' at the end of the list. */
1638 list_push_back(&head->list, &new->list);
1643 update_subtables_after_insertion(cls, subtable, new->priority);
1645 /* Remove old node from indices. */
1646 for (i = 0; i < subtable->n_indices; i++) {
1647 hindex_remove(&subtable->indices[i], &old->index_nodes[i]);
1653 static struct cls_rule *
1654 next_rule_in_list__(struct cls_rule *rule)
1656 struct cls_rule *next = OBJECT_CONTAINING(rule->list.next, next, list);
1660 static struct cls_rule *
1661 next_rule_in_list(struct cls_rule *rule)
1663 struct cls_rule *next = next_rule_in_list__(rule);
1664 return next->priority < rule->priority ? next : NULL;
1667 /* A longest-prefix match tree. */
1669 uint32_t prefix; /* Prefix bits for this node, MSB first. */
1670 uint8_t nbits; /* Never zero, except for the root node. */
1671 unsigned int n_rules; /* Number of rules that have this prefix. */
1672 struct trie_node *edges[2]; /* Both NULL if leaf. */
1675 /* Max bits per node. Must fit in struct trie_node's 'prefix'.
1676 * Also tested with 16, 8, and 5 to stress the implementation. */
1677 #define TRIE_PREFIX_BITS 32
1679 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1680 * Prefixes are in the network byte order, and the offset 0 corresponds to
1681 * the most significant bit of the first byte. The offset can be read as
1682 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1684 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1688 pr += ofs / 32; /* Where to start. */
1689 ofs %= 32; /* How many bits to skip at 'pr'. */
1691 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1692 if (plen > 32 - ofs) { /* Need more than we have already? */
1693 prefix |= ntohl(*++pr) >> (32 - ofs);
1695 /* Return with possible unwanted bits at the end. */
1699 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1700 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1701 * corresponds to the most significant bit of the first byte. The offset can
1702 * be read as "how many bits to skip from the start of the prefix starting at
1705 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1710 if (plen > TRIE_PREFIX_BITS) {
1711 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1713 /* Return with unwanted bits cleared. */
1714 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1717 /* Return the number of equal bits in 'nbits' of 'prefix's MSBs and a 'value'
1718 * starting at "MSB 0"-based offset 'ofs'. */
1720 prefix_equal_bits(uint32_t prefix, unsigned int nbits, const ovs_be32 value[],
1723 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, nbits);
1724 /* Set the bit after the relevant bits to limit the result. */
1725 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - nbits));
1728 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1729 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1731 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1732 unsigned int ofs, unsigned int plen)
1734 return prefix_equal_bits(node->prefix, MIN(node->nbits, plen - ofs),
1738 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1739 * be greater than 31. */
1741 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1743 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1746 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1747 * be between 0 and 31, inclusive. */
1749 get_bit_at(const uint32_t prefix, unsigned int ofs)
1751 return (prefix >> (31 - ofs)) & 1u;
1754 /* Create new branch. */
1755 static struct trie_node *
1756 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1757 unsigned int n_rules)
1759 struct trie_node *node = xmalloc(sizeof *node);
1761 node->prefix = trie_get_prefix(prefix, ofs, plen);
1763 if (plen <= TRIE_PREFIX_BITS) {
1765 node->edges[0] = NULL;
1766 node->edges[1] = NULL;
1767 node->n_rules = n_rules;
1768 } else { /* Need intermediate nodes. */
1769 struct trie_node *subnode = trie_branch_create(prefix,
1770 ofs + TRIE_PREFIX_BITS,
1771 plen - TRIE_PREFIX_BITS,
1773 int bit = get_bit_at(subnode->prefix, 0);
1774 node->nbits = TRIE_PREFIX_BITS;
1775 node->edges[bit] = subnode;
1776 node->edges[!bit] = NULL;
1783 trie_node_destroy(struct trie_node *node)
1789 trie_destroy(struct trie_node *node)
1792 trie_destroy(node->edges[0]);
1793 trie_destroy(node->edges[1]);
1799 trie_is_leaf(const struct trie_node *trie)
1801 return !trie->edges[0] && !trie->edges[1]; /* No children. */
1805 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1808 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1811 for (i = 0; i < nbits / 32; i++) {
1812 mask[i] = OVS_BE32_MAX;
1815 mask[i] |= htonl(~0u << (32 - nbits % 32));
1820 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
1823 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1825 ovs_be32 zeroes = 0;
1827 for (i = 0; i < nbits / 32; i++) {
1831 zeroes |= ~mask[i] & htonl(~0u << (32 - nbits % 32));
1834 return !zeroes; /* All 'nbits' bits set. */
1837 static struct trie_node **
1838 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
1841 return node->edges + be_get_bit_at(value, ofs);
1844 static const struct trie_node *
1845 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
1848 return node->edges[be_get_bit_at(value, ofs)];
1851 /* Return the prefix mask length necessary to find the longest-prefix match for
1852 * the '*value' in the prefix tree 'node'.
1853 * '*checkbits' is set to the number of bits in the prefix mask necessary to
1854 * determine a mismatch, in case there are longer prefixes in the tree below
1855 * the one that matched.
1858 trie_lookup_value(const struct trie_node *node, const ovs_be32 value[],
1859 unsigned int *checkbits)
1861 unsigned int plen = 0, match_len = 0;
1862 const struct trie_node *prev = NULL;
1864 for (; node; prev = node, node = trie_next_node(node, value, plen)) {
1865 unsigned int eqbits;
1866 /* Check if this edge can be followed. */
1867 eqbits = prefix_equal_bits(node->prefix, node->nbits, value, plen);
1869 if (eqbits < node->nbits) { /* Mismatch, nothing more to be found. */
1870 /* Bit at offset 'plen' differed. */
1871 *checkbits = plen + 1; /* Includes the first mismatching bit. */
1874 /* Full match, check if rules exist at this prefix length. */
1875 if (node->n_rules > 0) {
1879 /* Dead end, exclude the other branch if it exists. */
1880 *checkbits = !prev || trie_is_leaf(prev) ? plen : plen + 1;
1885 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
1886 unsigned int *checkbits)
1888 const struct mf_field *mf = trie->field;
1890 /* Check that current flow matches the prerequisites for the trie
1891 * field. Some match fields are used for multiple purposes, so we
1892 * must check that the trie is relevant for this flow. */
1893 if (mf_are_prereqs_ok(mf, flow)) {
1894 return trie_lookup_value(trie->root,
1895 &((ovs_be32 *)flow)[mf->flow_be32ofs],
1898 *checkbits = 0; /* Value not used in this case. */
1902 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
1903 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
1904 * 'miniflow_index' is not NULL. */
1906 minimask_get_prefix_len(const struct minimask *minimask,
1907 const struct mf_field *mf)
1909 unsigned int nbits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
1910 uint8_t u32_ofs = mf->flow_be32ofs;
1911 uint8_t u32_end = u32_ofs + mf->n_bytes / 4;
1913 for (; u32_ofs < u32_end; ++u32_ofs) {
1915 mask = ntohl((OVS_FORCE ovs_be32)minimask_get(minimask, u32_ofs));
1917 /* Validate mask, count the mask length. */
1920 return 0; /* No bits allowed after mask ended. */
1923 if (~mask & (~mask + 1)) {
1924 return 0; /* Mask not contiguous. */
1926 mask_tz = ctz32(mask);
1927 nbits += 32 - mask_tz;
1935 * This is called only when mask prefix is known to be CIDR and non-zero.
1936 * Relies on the fact that the flow and mask have the same map, and since
1937 * the mask is CIDR, the storage for the flow field exists even if it
1938 * happened to be zeros.
1940 static const ovs_be32 *
1941 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
1943 return match->flow.values +
1944 count_1bits(match->flow.map & ((UINT64_C(1) << mf->flow_be32ofs) - 1));
1947 /* Insert rule in to the prefix tree.
1948 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1951 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1953 const ovs_be32 *prefix = minimatch_get_prefix(&rule->match, trie->field);
1954 struct trie_node *node;
1955 struct trie_node **edge;
1958 /* Walk the tree. */
1959 for (edge = &trie->root;
1960 (node = *edge) != NULL;
1961 edge = trie_next_edge(node, prefix, ofs)) {
1962 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1964 if (eqbits < node->nbits) {
1965 /* Mismatch, new node needs to be inserted above. */
1966 int old_branch = get_bit_at(node->prefix, eqbits);
1968 /* New parent node. */
1969 *edge = trie_branch_create(prefix, ofs - eqbits, eqbits,
1970 ofs == mlen ? 1 : 0);
1972 /* Adjust old node for its new position in the tree. */
1973 node->prefix <<= eqbits;
1974 node->nbits -= eqbits;
1975 (*edge)->edges[old_branch] = node;
1977 /* Check if need a new branch for the new rule. */
1979 (*edge)->edges[!old_branch]
1980 = trie_branch_create(prefix, ofs, mlen - ofs, 1);
1984 /* Full match so far. */
1987 /* Full match at the current node, rule needs to be added here. */
1992 /* Must insert a new tree branch for the new rule. */
1993 *edge = trie_branch_create(prefix, ofs, mlen - ofs, 1);
1996 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1999 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2001 const ovs_be32 *prefix = minimatch_get_prefix(&rule->match, trie->field);
2002 struct trie_node *node;
2003 struct trie_node **edges[sizeof(union mf_value) * 8];
2004 int depth = 0, ofs = 0;
2006 /* Walk the tree. */
2007 for (edges[depth] = &trie->root;
2008 (node = *edges[depth]) != NULL;
2009 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
2010 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2011 if (eqbits < node->nbits) {
2012 /* Mismatch, nothing to be removed. This should never happen, as
2013 * only rules in the classifier are ever removed. */
2014 break; /* Log a warning. */
2016 /* Full match so far. */
2020 /* Full prefix match at the current node, remove rule here. */
2021 if (!node->n_rules) {
2022 break; /* Log a warning. */
2026 /* Check if can prune the tree. */
2027 while (!node->n_rules && !(node->edges[0] && node->edges[1])) {
2028 /* No rules and at most one child node, remove this node. */
2029 struct trie_node *next;
2030 next = node->edges[0] ? node->edges[0] : node->edges[1];
2033 if (node->nbits + next->nbits > TRIE_PREFIX_BITS) {
2034 break; /* Cannot combine. */
2036 /* Combine node with next. */
2037 next->prefix = node->prefix | next->prefix >> node->nbits;
2038 next->nbits += node->nbits;
2040 trie_node_destroy(node);
2041 /* Update the parent's edge. */
2042 *edges[depth] = next;
2043 if (next || !depth) {
2044 /* Branch not pruned or at root, nothing more to do. */
2047 node = *edges[--depth];
2052 /* Cannot go deeper. This should never happen, since only rules
2053 * that actually exist in the classifier are ever removed. */
2054 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");