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;
44 unsigned int max_priority;
47 struct cls_subtable_cache {
48 struct cls_subtable_entry *subtables;
49 size_t alloc_size; /* Number of allocated elements. */
50 size_t size; /* One past last valid array element. */
54 CLS_MAX_INDICES = 3 /* Maximum number of lookup indices per subtable. */
57 struct cls_classifier {
58 int n_rules; /* Total number of rules. */
59 uint8_t n_flow_segments;
60 uint8_t flow_segments[CLS_MAX_INDICES]; /* Flow segment boundaries to use
61 * for staged lookup. */
62 struct hmap subtables; /* Contains "struct cls_subtable"s. */
63 struct cls_subtable_cache subtables_priority;
64 struct hmap partitions; /* Contains "struct cls_partition"s. */
65 struct cls_trie tries[CLS_MAX_TRIES]; /* Prefix tries. */
69 /* A set of rules that all have the same fields wildcarded. */
71 struct hmap_node hmap_node; /* Within struct cls_classifier 'subtables'
73 struct hmap rules; /* Contains "struct cls_rule"s. */
74 int n_rules; /* Number of rules, including duplicates. */
75 unsigned int max_priority; /* Max priority of any rule in the subtable. */
76 unsigned int max_count; /* Count of max_priority rules. */
77 tag_type tag; /* Tag generated from mask for partitioning. */
78 uint8_t n_indices; /* How many indices to use. */
79 uint8_t index_ofs[CLS_MAX_INDICES]; /* u32 flow segment boundaries. */
80 struct hindex indices[CLS_MAX_INDICES]; /* Staged lookup indices. */
81 unsigned int trie_plen[CLS_MAX_TRIES]; /* Trie prefix length in 'mask'. */
82 struct minimask mask; /* Wildcards for fields. */
83 /* 'mask' must be the last field. */
86 /* Associates a metadata value (that is, a value of the OpenFlow 1.1+ metadata
87 * field) with tags for the "cls_subtable"s that contain rules that match that
89 struct cls_partition {
90 struct 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 miniflow flow; /* Matching rule. Mask is in the subtable. */
107 /* 'flow' must be the last field. */
110 static struct cls_match *
111 cls_match_alloc(struct cls_rule *rule)
113 int count = count_1bits(rule->match.flow.map);
115 struct cls_match *cls_match
116 = xmalloc(sizeof *cls_match - sizeof cls_match->flow.inline_values
117 + MINIFLOW_VALUES_SIZE(count));
119 cls_match->cls_rule = rule;
120 miniflow_clone_inline(&cls_match->flow, &rule->match.flow, count);
121 cls_match->priority = rule->priority;
122 rule->cls_match = cls_match;
128 static struct cls_subtable *find_subtable(const struct cls_classifier *,
129 const struct minimask *);
130 static struct cls_subtable *insert_subtable(struct cls_classifier *,
131 const struct minimask *);
133 static void destroy_subtable(struct cls_classifier *, struct cls_subtable *);
135 static void update_subtables_after_insertion(struct cls_classifier *,
136 struct cls_subtable *,
137 unsigned int new_priority);
138 static void update_subtables_after_removal(struct cls_classifier *,
139 struct cls_subtable *,
140 unsigned int del_priority);
142 static struct cls_match *find_match_wc(const struct cls_subtable *,
143 const struct flow *, struct trie_ctx *,
144 unsigned int n_tries,
145 struct flow_wildcards *);
146 static struct cls_match *find_equal(struct cls_subtable *,
147 const struct miniflow *, uint32_t hash);
148 static struct cls_match *insert_rule(struct cls_classifier *,
149 struct cls_subtable *, struct cls_rule *);
151 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list. */
152 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD) \
153 for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
154 #define FOR_EACH_RULE_IN_LIST_SAFE(RULE, NEXT, HEAD) \
155 for ((RULE) = (HEAD); \
156 (RULE) != NULL && ((NEXT) = next_rule_in_list(RULE), true); \
159 static struct cls_match *next_rule_in_list__(struct cls_match *);
160 static struct cls_match *next_rule_in_list(struct cls_match *);
162 static unsigned int minimask_get_prefix_len(const struct minimask *,
163 const struct mf_field *);
164 static void trie_init(struct cls_classifier *, int trie_idx,
165 const struct mf_field *);
166 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
167 unsigned int *checkbits);
169 static void trie_destroy(struct trie_node *);
170 static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
171 static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
172 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
174 static bool mask_prefix_bits_set(const struct flow_wildcards *,
175 uint8_t be32ofs, unsigned int nbits);
178 cls_subtable_cache_init(struct cls_subtable_cache *array)
180 memset(array, 0, sizeof *array);
184 cls_subtable_cache_destroy(struct cls_subtable_cache *array)
186 free(array->subtables);
187 memset(array, 0, sizeof *array);
190 /* Array insertion. */
192 cls_subtable_cache_push_back(struct cls_subtable_cache *array,
193 struct cls_subtable_entry a)
195 if (array->size == array->alloc_size) {
196 array->subtables = x2nrealloc(array->subtables, &array->alloc_size,
200 array->subtables[array->size++] = a;
203 /* Only for rearranging entries in the same cache. */
205 cls_subtable_cache_splice(struct cls_subtable_entry *to,
206 struct cls_subtable_entry *start,
207 struct cls_subtable_entry *end)
210 /* Same as splicing entries to (start) from [end, to). */
211 struct cls_subtable_entry *temp = to;
212 to = start; start = end; end = temp;
215 while (start != end) {
216 struct cls_subtable_entry temp = *start;
218 memmove(to + 1, to, (start - to) * sizeof *to);
222 } /* Else nothing to be done. */
227 cls_subtable_cache_remove(struct cls_subtable_cache *array,
228 struct cls_subtable_entry *elem)
230 ssize_t size = (&array->subtables[array->size]
231 - (elem + 1)) * sizeof *elem;
233 memmove(elem, elem + 1, size);
238 #define CLS_SUBTABLE_CACHE_FOR_EACH(SUBTABLE, ITER, ARRAY) \
239 for (ITER = (ARRAY)->subtables; \
240 ITER < &(ARRAY)->subtables[(ARRAY)->size] \
241 && OVS_LIKELY(SUBTABLE = ITER->subtable); \
243 #define CLS_SUBTABLE_CACHE_FOR_EACH_CONTINUE(SUBTABLE, ITER, ARRAY) \
245 ITER < &(ARRAY)->subtables[(ARRAY)->size] \
246 && OVS_LIKELY(SUBTABLE = ITER->subtable); \
248 #define CLS_SUBTABLE_CACHE_FOR_EACH_REVERSE(SUBTABLE, ITER, ARRAY) \
249 for (ITER = &(ARRAY)->subtables[(ARRAY)->size]; \
250 ITER > (ARRAY)->subtables \
251 && OVS_LIKELY(SUBTABLE = (--ITER)->subtable);)
254 /* flow/miniflow/minimask/minimatch utilities.
255 * These are only used by the classifier, so place them here to allow
256 * for better optimization. */
258 static inline uint64_t
259 miniflow_get_map_in_range(const struct miniflow *miniflow,
260 uint8_t start, uint8_t end, unsigned int *offset)
262 uint64_t map = miniflow->map;
266 uint64_t msk = (UINT64_C(1) << start) - 1; /* 'start' LSBs set */
267 *offset = count_1bits(map & msk);
270 if (end < FLOW_U32S) {
271 uint64_t msk = (UINT64_C(1) << end) - 1; /* 'end' LSBs set */
277 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
278 * 'mask', given 'basis'.
280 * The hash values returned by this function are the same as those returned by
281 * miniflow_hash_in_minimask(), only the form of the arguments differ. */
282 static inline uint32_t
283 flow_hash_in_minimask(const struct flow *flow, const struct minimask *mask,
286 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
287 const uint32_t *flow_u32 = (const uint32_t *)flow;
288 const uint32_t *p = mask_values;
293 for (map = mask->masks.map; map; map = zero_rightmost_1bit(map)) {
294 hash = mhash_add(hash, flow_u32[raw_ctz(map)] & *p++);
297 return mhash_finish(hash, (p - mask_values) * 4);
300 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
301 * 'mask', given 'basis'.
303 * The hash values returned by this function are the same as those returned by
304 * flow_hash_in_minimask(), only the form of the arguments differ. */
305 static inline uint32_t
306 miniflow_hash_in_minimask(const struct miniflow *flow,
307 const struct minimask *mask, uint32_t basis)
309 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
310 const uint32_t *p = mask_values;
311 uint32_t hash = basis;
314 MINIFLOW_FOR_EACH_IN_MAP(flow_u32, flow, mask->masks.map) {
315 hash = mhash_add(hash, flow_u32 & *p++);
318 return mhash_finish(hash, (p - mask_values) * 4);
321 /* Returns a hash value for the bits of range [start, end) in 'flow',
322 * where there are 1-bits in 'mask', given 'hash'.
324 * The hash values returned by this function are the same as those returned by
325 * minimatch_hash_range(), only the form of the arguments differ. */
326 static inline uint32_t
327 flow_hash_in_minimask_range(const struct flow *flow,
328 const struct minimask *mask,
329 uint8_t start, uint8_t end, uint32_t *basis)
331 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
332 const uint32_t *flow_u32 = (const uint32_t *)flow;
334 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
336 const uint32_t *p = mask_values + offset;
337 uint32_t hash = *basis;
339 for (; map; map = zero_rightmost_1bit(map)) {
340 hash = mhash_add(hash, flow_u32[raw_ctz(map)] & *p++);
343 *basis = hash; /* Allow continuation from the unfinished value. */
344 return mhash_finish(hash, (p - mask_values) * 4);
347 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask. */
349 flow_wildcards_fold_minimask(struct flow_wildcards *wc,
350 const struct minimask *mask)
352 flow_union_with_miniflow(&wc->masks, &mask->masks);
355 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask
356 * in range [start, end). */
358 flow_wildcards_fold_minimask_range(struct flow_wildcards *wc,
359 const struct minimask *mask,
360 uint8_t start, uint8_t end)
362 uint32_t *dst_u32 = (uint32_t *)&wc->masks;
364 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
366 const uint32_t *p = miniflow_get_u32_values(&mask->masks) + offset;
368 for (; map; map = zero_rightmost_1bit(map)) {
369 dst_u32[raw_ctz(map)] |= *p++;
373 /* Returns a hash value for 'flow', given 'basis'. */
374 static inline uint32_t
375 miniflow_hash(const struct miniflow *flow, uint32_t basis)
377 const uint32_t *values = miniflow_get_u32_values(flow);
378 const uint32_t *p = values;
379 uint32_t hash = basis;
380 uint64_t hash_map = 0;
383 for (map = flow->map; map; map = zero_rightmost_1bit(map)) {
385 hash = mhash_add(hash, *p);
386 hash_map |= rightmost_1bit(map);
390 hash = mhash_add(hash, hash_map);
391 hash = mhash_add(hash, hash_map >> 32);
393 return mhash_finish(hash, p - values);
396 /* Returns a hash value for 'mask', given 'basis'. */
397 static inline uint32_t
398 minimask_hash(const struct minimask *mask, uint32_t basis)
400 return miniflow_hash(&mask->masks, basis);
403 /* Returns a hash value for 'match', given 'basis'. */
404 static inline uint32_t
405 minimatch_hash(const struct minimatch *match, uint32_t basis)
407 return miniflow_hash(&match->flow, minimask_hash(&match->mask, basis));
410 /* Returns a hash value for the bits of range [start, end) in 'minimatch',
413 * The hash values returned by this function are the same as those returned by
414 * flow_hash_in_minimask_range(), only the form of the arguments differ. */
415 static inline uint32_t
416 minimatch_hash_range(const struct minimatch *match, uint8_t start, uint8_t end,
420 const uint32_t *p, *q;
421 uint32_t hash = *basis;
424 n = count_1bits(miniflow_get_map_in_range(&match->mask.masks, start, end,
426 q = miniflow_get_u32_values(&match->mask.masks) + offset;
427 p = miniflow_get_u32_values(&match->flow) + offset;
429 for (i = 0; i < n; i++) {
430 hash = mhash_add(hash, p[i] & q[i]);
432 *basis = hash; /* Allow continuation from the unfinished value. */
433 return mhash_finish(hash, (offset + n) * 4);
439 /* Initializes 'rule' to match packets specified by 'match' at the given
440 * 'priority'. 'match' must satisfy the invariant described in the comment at
441 * the definition of struct match.
443 * The caller must eventually destroy 'rule' with cls_rule_destroy().
445 * (OpenFlow uses priorities between 0 and UINT16_MAX, inclusive, but
446 * internally Open vSwitch supports a wider range.) */
448 cls_rule_init(struct cls_rule *rule,
449 const struct match *match, unsigned int priority)
451 minimatch_init(&rule->match, match);
452 rule->priority = priority;
453 rule->cls_match = NULL;
456 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
458 cls_rule_init_from_minimatch(struct cls_rule *rule,
459 const struct minimatch *match,
460 unsigned int priority)
462 minimatch_clone(&rule->match, match);
463 rule->priority = priority;
464 rule->cls_match = NULL;
467 /* Initializes 'dst' as a copy of 'src'.
469 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
471 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
473 minimatch_clone(&dst->match, &src->match);
474 dst->priority = src->priority;
475 dst->cls_match = NULL;
478 /* Initializes 'dst' with the data in 'src', destroying 'src'.
480 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
482 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
484 minimatch_move(&dst->match, &src->match);
485 dst->priority = src->priority;
486 dst->cls_match = NULL;
489 /* Frees memory referenced by 'rule'. Doesn't free 'rule' itself (it's
490 * normally embedded into a larger structure).
492 * ('rule' must not currently be in a classifier.) */
494 cls_rule_destroy(struct cls_rule *rule)
496 ovs_assert(!rule->cls_match);
497 minimatch_destroy(&rule->match);
500 /* Returns true if 'a' and 'b' match the same packets at the same priority,
501 * false if they differ in some way. */
503 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
505 return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
508 /* Returns a hash value for 'rule', folding in 'basis'. */
510 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
512 return minimatch_hash(&rule->match, hash_int(rule->priority, basis));
515 /* Appends a string describing 'rule' to 's'. */
517 cls_rule_format(const struct cls_rule *rule, struct ds *s)
519 minimatch_format(&rule->match, s, rule->priority);
522 /* Returns true if 'rule' matches every packet, false otherwise. */
524 cls_rule_is_catchall(const struct cls_rule *rule)
526 return minimask_is_catchall(&rule->match.mask);
529 /* Initializes 'cls' as a classifier that initially contains no classification
532 classifier_init(struct classifier *cls_, const uint8_t *flow_segments)
534 struct cls_classifier *cls = xmalloc(sizeof *cls);
536 fat_rwlock_init(&cls_->rwlock);
541 hmap_init(&cls->subtables);
542 cls_subtable_cache_init(&cls->subtables_priority);
543 hmap_init(&cls->partitions);
544 cls->n_flow_segments = 0;
546 while (cls->n_flow_segments < CLS_MAX_INDICES
547 && *flow_segments < FLOW_U32S) {
548 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
554 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
555 * caller's responsibility. */
557 classifier_destroy(struct classifier *cls_)
560 struct cls_classifier *cls = cls_->cls;
561 struct cls_subtable *partition, *next_partition;
562 struct cls_subtable *subtable, *next_subtable;
565 fat_rwlock_destroy(&cls_->rwlock);
570 for (i = 0; i < cls->n_tries; i++) {
571 trie_destroy(cls->tries[i].root);
574 HMAP_FOR_EACH_SAFE (subtable, next_subtable, hmap_node,
576 destroy_subtable(cls, subtable);
578 hmap_destroy(&cls->subtables);
580 HMAP_FOR_EACH_SAFE (partition, next_partition, hmap_node,
582 hmap_remove(&cls->partitions, &partition->hmap_node);
585 hmap_destroy(&cls->partitions);
587 cls_subtable_cache_destroy(&cls->subtables_priority);
592 /* We use uint64_t as a set for the fields below. */
593 BUILD_ASSERT_DECL(MFF_N_IDS <= 64);
595 /* Set the fields for which prefix lookup should be performed. */
597 classifier_set_prefix_fields(struct classifier *cls_,
598 const enum mf_field_id *trie_fields,
599 unsigned int n_fields)
601 struct cls_classifier *cls = cls_->cls;
605 for (i = 0, trie = 0; i < n_fields && trie < CLS_MAX_TRIES; i++) {
606 const struct mf_field *field = mf_from_id(trie_fields[i]);
607 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
608 /* Incompatible field. This is the only place where we
609 * enforce these requirements, but the rest of the trie code
610 * depends on the flow_be32ofs to be non-negative and the
611 * field length to be a multiple of 32 bits. */
615 if (fields & (UINT64_C(1) << trie_fields[i])) {
616 /* Duplicate field, there is no need to build more than
617 * one index for any one field. */
620 fields |= UINT64_C(1) << trie_fields[i];
622 if (trie >= cls->n_tries || field != cls->tries[trie].field) {
623 trie_init(cls, trie, field);
628 /* Destroy the rest. */
629 for (i = trie; i < cls->n_tries; i++) {
630 trie_init(cls, i, NULL);
636 trie_init(struct cls_classifier *cls, int trie_idx,
637 const struct mf_field *field)
639 struct cls_trie *trie = &cls->tries[trie_idx];
640 struct cls_subtable *subtable;
641 struct cls_subtable_entry *iter;
643 if (trie_idx < cls->n_tries) {
644 trie_destroy(trie->root);
649 /* Add existing rules to the trie. */
650 CLS_SUBTABLE_CACHE_FOR_EACH (subtable, iter, &cls->subtables_priority) {
653 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
654 /* Initialize subtable's prefix length on this field. */
655 subtable->trie_plen[trie_idx] = plen;
658 struct cls_match *head;
660 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
661 struct cls_match *match;
663 FOR_EACH_RULE_IN_LIST (match, head) {
664 trie_insert(trie, match->cls_rule, plen);
671 /* Returns true if 'cls' contains no classification rules, false otherwise. */
673 classifier_is_empty(const struct classifier *cls)
675 return cls->cls->n_rules == 0;
678 /* Returns the number of rules in 'cls'. */
680 classifier_count(const struct classifier *cls)
682 return cls->cls->n_rules;
686 hash_metadata(ovs_be64 metadata_)
688 uint64_t metadata = (OVS_FORCE uint64_t) metadata_;
689 return hash_uint64(metadata);
692 static struct cls_partition *
693 find_partition(const struct cls_classifier *cls, ovs_be64 metadata,
696 struct cls_partition *partition;
698 HMAP_FOR_EACH_IN_BUCKET (partition, hmap_node, hash, &cls->partitions) {
699 if (partition->metadata == metadata) {
707 static struct cls_partition *
708 create_partition(struct cls_classifier *cls, struct cls_subtable *subtable,
711 uint32_t hash = hash_metadata(metadata);
712 struct cls_partition *partition = find_partition(cls, metadata, hash);
714 partition = xmalloc(sizeof *partition);
715 partition->metadata = metadata;
717 tag_tracker_init(&partition->tracker);
718 hmap_insert(&cls->partitions, &partition->hmap_node, hash);
720 tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
724 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
725 * must not modify or free it.
727 * If 'cls' already contains an identical rule (including wildcards, values of
728 * fixed fields, and priority), replaces the old rule by 'rule' and returns the
729 * rule that was replaced. The caller takes ownership of the returned rule and
730 * is thus responsible for destroying it with cls_rule_destroy(), freeing the
731 * memory block in which it resides, etc., as necessary.
733 * Returns NULL if 'cls' does not contain a rule with an identical key, after
734 * inserting the new rule. In this case, no rules are displaced by the new
735 * rule, even rules that cannot have any effect because the new rule matches a
736 * superset of their flows and has higher priority. */
738 classifier_replace(struct classifier *cls_, struct cls_rule *rule)
740 struct cls_classifier *cls = cls_->cls;
741 struct cls_match *old_rule;
742 struct cls_subtable *subtable;
744 subtable = find_subtable(cls, &rule->match.mask);
746 subtable = insert_subtable(cls, &rule->match.mask);
749 old_rule = insert_rule(cls, subtable, rule);
753 rule->cls_match->partition = NULL;
754 if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
755 ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
756 rule->cls_match->partition = create_partition(cls, subtable,
763 for (i = 0; i < cls->n_tries; i++) {
764 if (subtable->trie_plen[i]) {
765 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
770 struct cls_rule *old_cls_rule = old_rule->cls_rule;
772 rule->cls_match->partition = old_rule->partition;
773 old_cls_rule->cls_match = NULL;
779 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
780 * must not modify or free it.
782 * 'cls' must not contain an identical rule (including wildcards, values of
783 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
786 classifier_insert(struct classifier *cls, struct cls_rule *rule)
788 struct cls_rule *displaced_rule = classifier_replace(cls, rule);
789 ovs_assert(!displaced_rule);
792 /* Removes 'rule' from 'cls'. It is the caller's responsibility to destroy
793 * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
794 * resides, etc., as necessary. */
796 classifier_remove(struct classifier *cls_, struct cls_rule *rule)
798 struct cls_classifier *cls = cls_->cls;
799 struct cls_partition *partition;
800 struct cls_match *cls_match = rule->cls_match;
801 struct cls_match *head;
802 struct cls_subtable *subtable;
805 ovs_assert(cls_match);
807 subtable = find_subtable(cls, &rule->match.mask);
809 ovs_assert(subtable);
811 for (i = 0; i < cls->n_tries; i++) {
812 if (subtable->trie_plen[i]) {
813 trie_remove(&cls->tries[i], rule, subtable->trie_plen[i]);
817 /* Remove rule node from indices. */
818 for (i = 0; i < subtable->n_indices; i++) {
819 hindex_remove(&subtable->indices[i], &cls_match->index_nodes[i]);
822 head = find_equal(subtable, &rule->match.flow, cls_match->hmap_node.hash);
823 if (head != cls_match) {
824 list_remove(&cls_match->list);
825 } else if (list_is_empty(&cls_match->list)) {
826 hmap_remove(&subtable->rules, &cls_match->hmap_node);
828 struct cls_match *next = CONTAINER_OF(cls_match->list.next,
829 struct cls_match, list);
831 list_remove(&cls_match->list);
832 hmap_replace(&subtable->rules, &cls_match->hmap_node,
836 partition = cls_match->partition;
838 tag_tracker_subtract(&partition->tracker, &partition->tags,
840 if (!partition->tags) {
841 hmap_remove(&cls->partitions, &partition->hmap_node);
846 if (--subtable->n_rules == 0) {
847 destroy_subtable(cls, subtable);
849 update_subtables_after_removal(cls, subtable, cls_match->priority);
854 rule->cls_match = NULL;
858 /* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
859 * subtables which have more than 'match_plen' bits in their corresponding
860 * field at offset 'be32ofs'. If skipped, 'maskbits' prefix bits should be
861 * unwildcarded to quarantee datapath flow matches only packets it should. */
863 const struct cls_trie *trie;
864 bool lookup_done; /* Status of the lookup. */
865 uint8_t be32ofs; /* U32 offset of the field in question. */
866 unsigned int match_plen; /* Longest prefix than could possibly match. */
867 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
871 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
874 ctx->be32ofs = trie->field->flow_be32ofs;
875 ctx->lookup_done = false;
879 lookahead_subtable(const struct cls_subtable_entry *subtables)
881 ovs_prefetch_range(subtables->subtable, sizeof *subtables->subtable);
884 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
885 * Returns a null pointer if no rules in 'cls' match 'flow'. If multiple rules
886 * of equal priority match 'flow', returns one arbitrarily.
888 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
889 * set of bits that were significant in the lookup. At some point
890 * earlier, 'wc' should have been initialized (e.g., by
891 * flow_wildcards_init_catchall()). */
893 classifier_lookup(const struct classifier *cls_, const struct flow *flow,
894 struct flow_wildcards *wc)
896 struct cls_classifier *cls = cls_->cls;
897 const struct cls_partition *partition;
899 struct cls_match *best;
900 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
902 struct cls_subtable_entry *subtables = cls->subtables_priority.subtables;
903 int n_subtables = cls->subtables_priority.size;
904 int64_t best_priority = -1;
906 /* Prefetch the subtables array. */
907 ovs_prefetch_range(subtables, n_subtables * sizeof *subtables);
909 /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
910 * then 'flow' cannot possibly match in 'subtable':
912 * - If flow->metadata maps to a given 'partition', then we can use
913 * 'tags' for 'partition->tags'.
915 * - If flow->metadata has no partition, then no rule in 'cls' has an
916 * exact-match for flow->metadata. That means that we don't need to
917 * search any subtable that includes flow->metadata in its mask.
919 * In either case, we always need to search any cls_subtables that do not
920 * include flow->metadata in its mask. One way to do that would be to
921 * check the "cls_subtable"s explicitly for that, but that would require an
922 * extra branch per subtable. Instead, we mark such a cls_subtable's
923 * 'tags' as TAG_ALL and make sure that 'tags' is never empty. This means
924 * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
925 * need a special case.
927 partition = (hmap_is_empty(&cls->partitions)
929 : find_partition(cls, flow->metadata,
930 hash_metadata(flow->metadata)));
931 tags = partition ? partition->tags : TAG_ARBITRARY;
933 /* Initialize trie contexts for match_find_wc(). */
934 for (i = 0; i < cls->n_tries; i++) {
935 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
938 /* Prefetch the first subtables. */
939 if (n_subtables > 1) {
940 lookahead_subtable(subtables);
941 lookahead_subtable(subtables + 1);
945 for (i = 0; OVS_LIKELY(i < n_subtables); i++) {
946 struct cls_match *rule;
948 if ((int64_t)subtables[i].max_priority <= best_priority) {
949 /* Subtables are in descending priority order,
950 * can not find anything better. */
954 /* Prefetch a forthcoming subtable. */
955 if (i + 2 < n_subtables) {
956 lookahead_subtable(&subtables[i + 2]);
959 if (!tag_intersects(tags, subtables[i].tag)) {
963 rule = find_match_wc(subtables[i].subtable, flow, trie_ctx,
965 if (rule && (int64_t)rule->priority > best_priority) {
966 best_priority = (int64_t)rule->priority;
971 return best ? best->cls_rule : NULL;
974 /* Returns true if 'target' satisifies 'match', that is, if each bit for which
975 * 'match' specifies a particular value has the correct value in 'target'.
977 * 'flow' and 'mask' have the same mask! */
979 miniflow_and_mask_matches_miniflow(const struct miniflow *flow,
980 const struct minimask *mask,
981 const struct miniflow *target)
983 const uint32_t *flowp = miniflow_get_u32_values(flow);
984 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
987 MINIFLOW_FOR_EACH_IN_MAP(target_u32, target, mask->masks.map) {
988 if ((*flowp++ ^ target_u32) & *maskp++) {
996 static inline struct cls_match *
997 find_match_miniflow(const struct cls_subtable *subtable,
998 const struct miniflow *flow,
1001 struct cls_match *rule;
1003 HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &subtable->rules) {
1004 if (miniflow_and_mask_matches_miniflow(&rule->flow, &subtable->mask,
1013 /* Finds and returns the highest-priority rule in 'cls' that matches
1014 * 'miniflow'. Returns a null pointer if no rules in 'cls' match 'flow'.
1015 * If multiple rules of equal priority match 'flow', returns one arbitrarily.
1017 * This function is optimized for the userspace datapath, which only ever has
1018 * one priority value for it's flows!
1020 struct cls_rule *classifier_lookup_miniflow_first(const struct classifier *cls_,
1021 const struct miniflow *flow)
1023 struct cls_classifier *cls = cls_->cls;
1024 struct cls_subtable *subtable;
1025 struct cls_subtable_entry *iter;
1027 CLS_SUBTABLE_CACHE_FOR_EACH (subtable, iter, &cls->subtables_priority) {
1028 struct cls_match *rule;
1030 rule = find_match_miniflow(subtable, flow,
1031 miniflow_hash_in_minimask(flow,
1035 return rule->cls_rule;
1042 /* Finds and returns a rule in 'cls' with exactly the same priority and
1043 * matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
1044 * contain an exact match. */
1046 classifier_find_rule_exactly(const struct classifier *cls_,
1047 const struct cls_rule *target)
1049 struct cls_classifier *cls = cls_->cls;
1050 struct cls_match *head, *rule;
1051 struct cls_subtable *subtable;
1053 subtable = find_subtable(cls, &target->match.mask);
1058 /* Skip if there is no hope. */
1059 if (target->priority > subtable->max_priority) {
1063 head = find_equal(subtable, &target->match.flow,
1064 miniflow_hash_in_minimask(&target->match.flow,
1065 &target->match.mask, 0));
1066 FOR_EACH_RULE_IN_LIST (rule, head) {
1067 if (target->priority >= rule->priority) {
1068 return target->priority == rule->priority ? rule->cls_rule : NULL;
1074 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
1075 * same matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
1076 * contain an exact match. */
1078 classifier_find_match_exactly(const struct classifier *cls,
1079 const struct match *target,
1080 unsigned int priority)
1082 struct cls_rule *retval;
1085 cls_rule_init(&cr, target, priority);
1086 retval = classifier_find_rule_exactly(cls, &cr);
1087 cls_rule_destroy(&cr);
1092 /* Checks if 'target' would overlap any other rule in 'cls'. Two rules are
1093 * considered to overlap if both rules have the same priority and a packet
1094 * could match both. */
1096 classifier_rule_overlaps(const struct classifier *cls_,
1097 const struct cls_rule *target)
1099 struct cls_classifier *cls = cls_->cls;
1100 struct cls_subtable *subtable;
1101 struct cls_subtable_entry *iter;
1103 /* Iterate subtables in the descending max priority order. */
1104 CLS_SUBTABLE_CACHE_FOR_EACH (subtable, iter, &cls->subtables_priority) {
1105 uint32_t storage[FLOW_U32S];
1106 struct minimask mask;
1107 struct cls_match *head;
1109 if (target->priority > iter->max_priority) {
1110 break; /* Can skip this and the rest of the subtables. */
1113 minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
1114 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
1115 struct cls_match *rule;
1117 FOR_EACH_RULE_IN_LIST (rule, head) {
1118 if (rule->priority < target->priority) {
1119 break; /* Rules in descending priority order. */
1121 if (rule->priority == target->priority
1122 && miniflow_equal_in_minimask(&target->match.flow,
1123 &rule->flow, &mask)) {
1133 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
1134 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
1135 * function returns true if, for every field:
1137 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
1140 * - 'criteria' wildcards the field,
1142 * Conversely, 'rule' does not match 'criteria' and this function returns false
1143 * if, for at least one field:
1145 * - 'criteria' and 'rule' specify different values for the field, or
1147 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
1149 * Equivalently, the truth table for whether a field matches is:
1154 * r +---------+---------+
1155 * i wild | yes | yes |
1157 * e +---------+---------+
1158 * r exact | no |if values|
1160 * a +---------+---------+
1162 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
1163 * commands and by OpenFlow 1.0 aggregate and flow stats.
1165 * Ignores rule->priority. */
1167 cls_rule_is_loose_match(const struct cls_rule *rule,
1168 const struct minimatch *criteria)
1170 return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
1171 && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
1178 rule_matches(const struct cls_match *rule, const struct cls_rule *target)
1181 || miniflow_equal_in_minimask(&rule->flow,
1182 &target->match.flow,
1183 &target->match.mask));
1186 static struct cls_match *
1187 search_subtable(const struct cls_subtable *subtable,
1188 const struct cls_rule *target)
1190 if (!target || !minimask_has_extra(&subtable->mask, &target->match.mask)) {
1191 struct cls_match *rule;
1193 HMAP_FOR_EACH (rule, hmap_node, &subtable->rules) {
1194 if (rule_matches(rule, target)) {
1202 /* Initializes 'cursor' for iterating through rules in 'cls':
1204 * - If 'target' is null, the cursor will visit every rule in 'cls'.
1206 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1207 * such that cls_rule_is_loose_match(rule, target) returns true.
1209 * Ignores target->priority. */
1211 cls_cursor_init(struct cls_cursor *cursor, const struct classifier *cls,
1212 const struct cls_rule *target)
1214 cursor->cls = cls->cls;
1215 cursor->target = target && !cls_rule_is_catchall(target) ? target : NULL;
1218 /* Returns the first matching cls_rule in 'cursor''s iteration, or a null
1219 * pointer if there are no matches. */
1221 cls_cursor_first(struct cls_cursor *cursor)
1223 struct cls_subtable *subtable;
1225 HMAP_FOR_EACH (subtable, hmap_node, &cursor->cls->subtables) {
1226 struct cls_match *rule = search_subtable(subtable, cursor->target);
1228 cursor->subtable = subtable;
1229 return rule->cls_rule;
1236 /* Returns the next matching cls_rule in 'cursor''s iteration, or a null
1237 * pointer if there are no more matches. */
1239 cls_cursor_next(struct cls_cursor *cursor, const struct cls_rule *rule_)
1241 struct cls_match *rule = CONST_CAST(struct cls_match *, rule_->cls_match);
1242 const struct cls_subtable *subtable;
1243 struct cls_match *next;
1245 next = next_rule_in_list__(rule);
1246 if (next->priority < rule->priority) {
1247 return next->cls_rule;
1250 /* 'next' is the head of the list, that is, the rule that is included in
1251 * the subtable's hmap. (This is important when the classifier contains
1252 * rules that differ only in priority.) */
1254 HMAP_FOR_EACH_CONTINUE (rule, hmap_node, &cursor->subtable->rules) {
1255 if (rule_matches(rule, cursor->target)) {
1256 return rule->cls_rule;
1260 subtable = cursor->subtable;
1261 HMAP_FOR_EACH_CONTINUE (subtable, hmap_node, &cursor->cls->subtables) {
1262 rule = search_subtable(subtable, cursor->target);
1264 cursor->subtable = subtable;
1265 return rule->cls_rule;
1272 static struct cls_subtable *
1273 find_subtable(const struct cls_classifier *cls, const struct minimask *mask)
1275 struct cls_subtable *subtable;
1277 HMAP_FOR_EACH_IN_BUCKET (subtable, hmap_node, minimask_hash(mask, 0),
1279 if (minimask_equal(mask, &subtable->mask)) {
1286 static struct cls_subtable *
1287 insert_subtable(struct cls_classifier *cls, const struct minimask *mask)
1289 uint32_t hash = minimask_hash(mask, 0);
1290 struct cls_subtable *subtable;
1292 struct flow_wildcards old, new;
1294 struct cls_subtable_entry elem;
1295 int count = count_1bits(mask->masks.map);
1297 subtable = xzalloc(sizeof *subtable - sizeof mask->masks.inline_values
1298 + MINIFLOW_VALUES_SIZE(count));
1299 hmap_init(&subtable->rules);
1300 miniflow_clone_inline(&subtable->mask.masks, &mask->masks, count);
1302 /* Init indices for segmented lookup, if any. */
1303 flow_wildcards_init_catchall(&new);
1306 for (i = 0; i < cls->n_flow_segments; i++) {
1307 flow_wildcards_fold_minimask_range(&new, mask, prev,
1308 cls->flow_segments[i]);
1309 /* Add an index if it adds mask bits. */
1310 if (!flow_wildcards_equal(&new, &old)) {
1311 hindex_init(&subtable->indices[index]);
1312 subtable->index_ofs[index] = cls->flow_segments[i];
1316 prev = cls->flow_segments[i];
1318 /* Check if the rest of the subtable's mask adds any bits,
1319 * and remove the last index if it doesn't. */
1321 flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U32S);
1322 if (flow_wildcards_equal(&new, &old)) {
1324 subtable->index_ofs[index] = 0;
1325 hindex_destroy(&subtable->indices[index]);
1328 subtable->n_indices = index;
1330 subtable->tag = (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1331 ? tag_create_deterministic(hash)
1334 for (i = 0; i < cls->n_tries; i++) {
1335 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1336 cls->tries[i].field);
1339 hmap_insert(&cls->subtables, &subtable->hmap_node, hash);
1340 elem.subtable = subtable;
1341 elem.tag = subtable->tag;
1342 elem.max_priority = subtable->max_priority;
1343 cls_subtable_cache_push_back(&cls->subtables_priority, elem);
1349 destroy_subtable(struct cls_classifier *cls, struct cls_subtable *subtable)
1352 struct cls_subtable *table = NULL;
1353 struct cls_subtable_entry *iter;
1355 CLS_SUBTABLE_CACHE_FOR_EACH (table, iter, &cls->subtables_priority) {
1356 if (table == subtable) {
1357 cls_subtable_cache_remove(&cls->subtables_priority, iter);
1362 for (i = 0; i < subtable->n_indices; i++) {
1363 hindex_destroy(&subtable->indices[i]);
1365 minimask_destroy(&subtable->mask);
1366 hmap_remove(&cls->subtables, &subtable->hmap_node);
1367 hmap_destroy(&subtable->rules);
1371 /* This function performs the following updates for 'subtable' in 'cls'
1372 * following the addition of a new rule with priority 'new_priority' to
1375 * - Update 'subtable->max_priority' and 'subtable->max_count' if necessary.
1377 * - Update 'subtable''s position in 'cls->subtables_priority' if necessary.
1379 * This function should only be called after adding a new rule, not after
1380 * replacing a rule by an identical one or modifying a rule in-place. */
1382 update_subtables_after_insertion(struct cls_classifier *cls,
1383 struct cls_subtable *subtable,
1384 unsigned int new_priority)
1386 if (new_priority == subtable->max_priority) {
1387 ++subtable->max_count;
1388 } else if (new_priority > subtable->max_priority) {
1389 struct cls_subtable *table;
1390 struct cls_subtable_entry *iter, *subtable_iter = NULL;
1392 subtable->max_priority = new_priority;
1393 subtable->max_count = 1;
1395 /* Possibly move 'subtable' earlier in the priority list. If we break
1396 * out of the loop, then 'subtable_iter' should be moved just before
1397 * 'iter'. If the loop terminates normally, then 'iter' will be the
1398 * first list element and we'll move subtable just before that
1399 * (e.g. to the front of the list). */
1400 CLS_SUBTABLE_CACHE_FOR_EACH_REVERSE (table, iter, &cls->subtables_priority) {
1401 if (table == subtable) {
1402 subtable_iter = iter; /* Locate the subtable as we go. */
1403 iter->max_priority = new_priority;
1404 } else if (table->max_priority >= new_priority) {
1405 ovs_assert(subtable_iter != NULL);
1411 /* Move 'subtable' just before 'iter' (unless it's already there). */
1412 if (iter != subtable_iter) {
1413 cls_subtable_cache_splice(iter, subtable_iter, subtable_iter + 1);
1418 /* This function performs the following updates for 'subtable' in 'cls'
1419 * following the deletion of a rule with priority 'del_priority' from
1422 * - Update 'subtable->max_priority' and 'subtable->max_count' if necessary.
1424 * - Update 'subtable''s position in 'cls->subtables_priority' if necessary.
1426 * This function should only be called after removing a rule, not after
1427 * replacing a rule by an identical one or modifying a rule in-place. */
1429 update_subtables_after_removal(struct cls_classifier *cls,
1430 struct cls_subtable *subtable,
1431 unsigned int del_priority)
1433 if (del_priority == subtable->max_priority && --subtable->max_count == 0) {
1434 struct cls_match *head;
1435 struct cls_subtable *table;
1436 struct cls_subtable_entry *iter, *subtable_iter = NULL;
1438 subtable->max_priority = 0;
1439 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
1440 if (head->priority > subtable->max_priority) {
1441 subtable->max_priority = head->priority;
1442 subtable->max_count = 1;
1443 } else if (head->priority == subtable->max_priority) {
1444 ++subtable->max_count;
1448 /* Possibly move 'subtable' later in the priority list. If we break
1449 * out of the loop, then 'subtable' should be moved just before that
1450 * 'iter'. If the loop terminates normally, then 'iter' will be the
1451 * list head and we'll move subtable just before that (e.g. to the back
1453 CLS_SUBTABLE_CACHE_FOR_EACH (table, iter, &cls->subtables_priority) {
1454 if (table == subtable) {
1455 subtable_iter = iter; /* Locate the subtable as we go. */
1456 iter->max_priority = subtable->max_priority;
1457 } else if (table->max_priority <= subtable->max_priority) {
1458 ovs_assert(subtable_iter != NULL);
1463 /* Move 'subtable' just before 'iter' (unless it's already there). */
1464 if (iter != subtable_iter) {
1465 cls_subtable_cache_splice(iter, subtable_iter, subtable_iter + 1);
1475 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1476 * lookup results. */
1478 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1479 const unsigned int field_plen[CLS_MAX_TRIES],
1480 const struct range ofs, const struct flow *flow,
1481 struct flow_wildcards *wc)
1485 /* Check if we could avoid fully unwildcarding the next level of
1486 * fields using the prefix tries. The trie checks are done only as
1487 * needed to avoid folding in additional bits to the wildcards mask. */
1488 for (j = 0; j < n_tries; j++) {
1489 /* Is the trie field relevant for this subtable? */
1490 if (field_plen[j]) {
1491 struct trie_ctx *ctx = &trie_ctx[j];
1492 uint8_t be32ofs = ctx->be32ofs;
1494 /* Is the trie field within the current range of fields? */
1495 if (be32ofs >= ofs.start && be32ofs < ofs.end) {
1496 /* On-demand trie lookup. */
1497 if (!ctx->lookup_done) {
1498 ctx->match_plen = trie_lookup(ctx->trie, flow,
1500 ctx->lookup_done = true;
1502 /* Possible to skip the rest of the subtable if subtable's
1503 * prefix on the field is longer than what is known to match
1504 * based on the trie lookup. */
1505 if (field_plen[j] > ctx->match_plen) {
1506 /* RFC: We want the trie lookup to never result in
1507 * unwildcarding any bits that would not be unwildcarded
1508 * otherwise. Since the trie is shared by the whole
1509 * classifier, it is possible that the 'maskbits' contain
1510 * bits that are irrelevant for the partition of the
1511 * classifier relevant for the current flow. */
1513 /* Can skip if the field is already unwildcarded. */
1514 if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1517 /* Check that the trie result will not unwildcard more bits
1518 * than this stage will. */
1519 if (ctx->maskbits <= field_plen[j]) {
1520 /* Unwildcard the bits and skip the rest. */
1521 mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1522 /* Note: Prerequisite already unwildcarded, as the only
1523 * prerequisite of the supported trie lookup fields is
1524 * the ethertype, which is currently always
1536 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1537 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1538 * value has the correct value in 'target'.
1540 * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
1541 * target, mask) but it is faster because of the invariant that
1542 * flow->map and mask->masks.map are the same. */
1544 miniflow_and_mask_matches_flow(const struct miniflow *flow,
1545 const struct minimask *mask,
1546 const struct flow *target)
1548 const uint32_t *flowp = miniflow_get_u32_values(flow);
1549 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1550 uint32_t target_u32;
1552 FLOW_FOR_EACH_IN_MAP(target_u32, target, mask->masks.map) {
1553 if ((*flowp++ ^ target_u32) & *maskp++) {
1561 static inline struct cls_match *
1562 find_match(const struct cls_subtable *subtable, const struct flow *flow,
1565 struct cls_match *rule;
1567 HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &subtable->rules) {
1568 if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
1577 static struct cls_match *
1578 find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
1579 struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1580 struct flow_wildcards *wc)
1582 uint32_t basis = 0, hash;
1583 struct cls_match *rule = NULL;
1587 if (OVS_UNLIKELY(!wc)) {
1588 return find_match(subtable, flow,
1589 flow_hash_in_minimask(flow, &subtable->mask, 0));
1593 /* Try to finish early by checking fields in segments. */
1594 for (i = 0; i < subtable->n_indices; i++) {
1595 struct hindex_node *inode;
1596 ofs.end = subtable->index_ofs[i];
1598 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1602 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1604 ofs.start = ofs.end;
1605 inode = hindex_node_with_hash(&subtable->indices[i], hash);
1607 /* No match, can stop immediately, but must fold in the mask
1608 * covered so far. */
1612 /* If we have narrowed down to a single rule already, check whether
1613 * that rule matches. If it does match, then we're done. If it does
1614 * not match, then we know that we will never get a match, but we do
1615 * not yet know how many wildcards we need to fold into 'wc' so we
1616 * continue iterating through indices to find that out. (We won't
1617 * waste time calling miniflow_and_mask_matches_flow() again because
1618 * we've set 'rule' nonnull.)
1620 * This check shows a measurable benefit with non-trivial flow tables.
1622 * (Rare) hash collisions may cause us to miss the opportunity for this
1624 if (!inode->s && !rule) {
1625 ASSIGN_CONTAINER(rule, inode - i, index_nodes);
1626 if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
1632 ofs.end = FLOW_U32S;
1633 /* Trie check for the final range. */
1634 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1638 /* Multiple potential matches exist, look for one. */
1639 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1641 rule = find_match(subtable, flow, hash);
1643 /* We already narrowed the matching candidates down to just 'rule',
1644 * but it didn't match. */
1648 /* Must unwildcard all the fields, as they were looked at. */
1649 flow_wildcards_fold_minimask(wc, &subtable->mask);
1653 /* Must unwildcard the fields looked up so far, if any. */
1655 flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, ofs.start);
1660 static struct cls_match *
1661 find_equal(struct cls_subtable *subtable, const struct miniflow *flow,
1664 struct cls_match *head;
1666 HMAP_FOR_EACH_WITH_HASH (head, hmap_node, hash, &subtable->rules) {
1667 if (miniflow_equal(&head->flow, flow)) {
1674 static struct cls_match *
1675 insert_rule(struct cls_classifier *cls, struct cls_subtable *subtable,
1676 struct cls_rule *new)
1678 struct cls_match *cls_match = cls_match_alloc(new);
1679 struct cls_match *head;
1680 struct cls_match *old = NULL;
1682 uint32_t basis = 0, hash;
1683 uint8_t prev_be32ofs = 0;
1685 /* Add new node to segment indices. */
1686 for (i = 0; i < subtable->n_indices; i++) {
1687 hash = minimatch_hash_range(&new->match, prev_be32ofs,
1688 subtable->index_ofs[i], &basis);
1689 hindex_insert(&subtable->indices[i], &cls_match->index_nodes[i], hash);
1690 prev_be32ofs = subtable->index_ofs[i];
1692 hash = minimatch_hash_range(&new->match, prev_be32ofs, FLOW_U32S, &basis);
1693 head = find_equal(subtable, &new->match.flow, hash);
1695 hmap_insert(&subtable->rules, &cls_match->hmap_node, hash);
1696 list_init(&cls_match->list);
1699 /* Scan the list for the insertion point that will keep the list in
1700 * order of decreasing priority. */
1701 struct cls_match *rule;
1703 cls_match->hmap_node.hash = hash; /* Otherwise done by hmap_insert. */
1705 FOR_EACH_RULE_IN_LIST (rule, head) {
1706 if (cls_match->priority >= rule->priority) {
1708 /* 'new' is the new highest-priority flow in the list. */
1709 hmap_replace(&subtable->rules,
1710 &rule->hmap_node, &cls_match->hmap_node);
1713 if (cls_match->priority == rule->priority) {
1714 list_replace(&cls_match->list, &rule->list);
1718 list_insert(&rule->list, &cls_match->list);
1724 /* Insert 'new' at the end of the list. */
1725 list_push_back(&head->list, &cls_match->list);
1730 update_subtables_after_insertion(cls, subtable, cls_match->priority);
1732 /* Remove old node from indices. */
1733 for (i = 0; i < subtable->n_indices; i++) {
1734 hindex_remove(&subtable->indices[i], &old->index_nodes[i]);
1740 static struct cls_match *
1741 next_rule_in_list__(struct cls_match *rule)
1743 struct cls_match *next = OBJECT_CONTAINING(rule->list.next, next, list);
1747 static struct cls_match *
1748 next_rule_in_list(struct cls_match *rule)
1750 struct cls_match *next = next_rule_in_list__(rule);
1751 return next->priority < rule->priority ? next : NULL;
1754 /* A longest-prefix match tree. */
1756 uint32_t prefix; /* Prefix bits for this node, MSB first. */
1757 uint8_t nbits; /* Never zero, except for the root node. */
1758 unsigned int n_rules; /* Number of rules that have this prefix. */
1759 struct trie_node *edges[2]; /* Both NULL if leaf. */
1762 /* Max bits per node. Must fit in struct trie_node's 'prefix'.
1763 * Also tested with 16, 8, and 5 to stress the implementation. */
1764 #define TRIE_PREFIX_BITS 32
1766 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1767 * Prefixes are in the network byte order, and the offset 0 corresponds to
1768 * the most significant bit of the first byte. The offset can be read as
1769 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1771 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1775 pr += ofs / 32; /* Where to start. */
1776 ofs %= 32; /* How many bits to skip at 'pr'. */
1778 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1779 if (plen > 32 - ofs) { /* Need more than we have already? */
1780 prefix |= ntohl(*++pr) >> (32 - ofs);
1782 /* Return with possible unwanted bits at the end. */
1786 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1787 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1788 * corresponds to the most significant bit of the first byte. The offset can
1789 * be read as "how many bits to skip from the start of the prefix starting at
1792 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1797 if (plen > TRIE_PREFIX_BITS) {
1798 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1800 /* Return with unwanted bits cleared. */
1801 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1804 /* Return the number of equal bits in 'nbits' of 'prefix's MSBs and a 'value'
1805 * starting at "MSB 0"-based offset 'ofs'. */
1807 prefix_equal_bits(uint32_t prefix, unsigned int nbits, const ovs_be32 value[],
1810 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, nbits);
1811 /* Set the bit after the relevant bits to limit the result. */
1812 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - nbits));
1815 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1816 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1818 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1819 unsigned int ofs, unsigned int plen)
1821 return prefix_equal_bits(node->prefix, MIN(node->nbits, plen - ofs),
1825 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1826 * be greater than 31. */
1828 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1830 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1833 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1834 * be between 0 and 31, inclusive. */
1836 get_bit_at(const uint32_t prefix, unsigned int ofs)
1838 return (prefix >> (31 - ofs)) & 1u;
1841 /* Create new branch. */
1842 static struct trie_node *
1843 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1844 unsigned int n_rules)
1846 struct trie_node *node = xmalloc(sizeof *node);
1848 node->prefix = trie_get_prefix(prefix, ofs, plen);
1850 if (plen <= TRIE_PREFIX_BITS) {
1852 node->edges[0] = NULL;
1853 node->edges[1] = NULL;
1854 node->n_rules = n_rules;
1855 } else { /* Need intermediate nodes. */
1856 struct trie_node *subnode = trie_branch_create(prefix,
1857 ofs + TRIE_PREFIX_BITS,
1858 plen - TRIE_PREFIX_BITS,
1860 int bit = get_bit_at(subnode->prefix, 0);
1861 node->nbits = TRIE_PREFIX_BITS;
1862 node->edges[bit] = subnode;
1863 node->edges[!bit] = NULL;
1870 trie_node_destroy(struct trie_node *node)
1876 trie_destroy(struct trie_node *node)
1879 trie_destroy(node->edges[0]);
1880 trie_destroy(node->edges[1]);
1886 trie_is_leaf(const struct trie_node *trie)
1888 return !trie->edges[0] && !trie->edges[1]; /* No children. */
1892 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1895 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1898 for (i = 0; i < nbits / 32; i++) {
1899 mask[i] = OVS_BE32_MAX;
1902 mask[i] |= htonl(~0u << (32 - nbits % 32));
1907 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
1910 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1912 ovs_be32 zeroes = 0;
1914 for (i = 0; i < nbits / 32; i++) {
1918 zeroes |= ~mask[i] & htonl(~0u << (32 - nbits % 32));
1921 return !zeroes; /* All 'nbits' bits set. */
1924 static struct trie_node **
1925 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
1928 return node->edges + be_get_bit_at(value, ofs);
1931 static const struct trie_node *
1932 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
1935 return node->edges[be_get_bit_at(value, ofs)];
1938 /* Return the prefix mask length necessary to find the longest-prefix match for
1939 * the '*value' in the prefix tree 'node'.
1940 * '*checkbits' is set to the number of bits in the prefix mask necessary to
1941 * determine a mismatch, in case there are longer prefixes in the tree below
1942 * the one that matched.
1945 trie_lookup_value(const struct trie_node *node, const ovs_be32 value[],
1946 unsigned int *checkbits)
1948 unsigned int plen = 0, match_len = 0;
1949 const struct trie_node *prev = NULL;
1951 for (; node; prev = node, node = trie_next_node(node, value, plen)) {
1952 unsigned int eqbits;
1953 /* Check if this edge can be followed. */
1954 eqbits = prefix_equal_bits(node->prefix, node->nbits, value, plen);
1956 if (eqbits < node->nbits) { /* Mismatch, nothing more to be found. */
1957 /* Bit at offset 'plen' differed. */
1958 *checkbits = plen + 1; /* Includes the first mismatching bit. */
1961 /* Full match, check if rules exist at this prefix length. */
1962 if (node->n_rules > 0) {
1966 /* Dead end, exclude the other branch if it exists. */
1967 *checkbits = !prev || trie_is_leaf(prev) ? plen : plen + 1;
1972 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
1973 unsigned int *checkbits)
1975 const struct mf_field *mf = trie->field;
1977 /* Check that current flow matches the prerequisites for the trie
1978 * field. Some match fields are used for multiple purposes, so we
1979 * must check that the trie is relevant for this flow. */
1980 if (mf_are_prereqs_ok(mf, flow)) {
1981 return trie_lookup_value(trie->root,
1982 &((ovs_be32 *)flow)[mf->flow_be32ofs],
1985 *checkbits = 0; /* Value not used in this case. */
1989 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
1990 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
1991 * 'miniflow_index' is not NULL. */
1993 minimask_get_prefix_len(const struct minimask *minimask,
1994 const struct mf_field *mf)
1996 unsigned int nbits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
1997 uint8_t u32_ofs = mf->flow_be32ofs;
1998 uint8_t u32_end = u32_ofs + mf->n_bytes / 4;
2000 for (; u32_ofs < u32_end; ++u32_ofs) {
2002 mask = ntohl((OVS_FORCE ovs_be32)minimask_get(minimask, u32_ofs));
2004 /* Validate mask, count the mask length. */
2007 return 0; /* No bits allowed after mask ended. */
2010 if (~mask & (~mask + 1)) {
2011 return 0; /* Mask not contiguous. */
2013 mask_tz = ctz32(mask);
2014 nbits += 32 - mask_tz;
2022 * This is called only when mask prefix is known to be CIDR and non-zero.
2023 * Relies on the fact that the flow and mask have the same map, and since
2024 * the mask is CIDR, the storage for the flow field exists even if it
2025 * happened to be zeros.
2027 static const ovs_be32 *
2028 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
2030 return miniflow_get_be32_values(&match->flow) +
2031 count_1bits(match->flow.map & ((UINT64_C(1) << mf->flow_be32ofs) - 1));
2034 /* Insert rule in to the prefix tree.
2035 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2038 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2040 const ovs_be32 *prefix = minimatch_get_prefix(&rule->match, trie->field);
2041 struct trie_node *node;
2042 struct trie_node **edge;
2045 /* Walk the tree. */
2046 for (edge = &trie->root;
2047 (node = *edge) != NULL;
2048 edge = trie_next_edge(node, prefix, ofs)) {
2049 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2051 if (eqbits < node->nbits) {
2052 /* Mismatch, new node needs to be inserted above. */
2053 int old_branch = get_bit_at(node->prefix, eqbits);
2055 /* New parent node. */
2056 *edge = trie_branch_create(prefix, ofs - eqbits, eqbits,
2057 ofs == mlen ? 1 : 0);
2059 /* Adjust old node for its new position in the tree. */
2060 node->prefix <<= eqbits;
2061 node->nbits -= eqbits;
2062 (*edge)->edges[old_branch] = node;
2064 /* Check if need a new branch for the new rule. */
2066 (*edge)->edges[!old_branch]
2067 = trie_branch_create(prefix, ofs, mlen - ofs, 1);
2071 /* Full match so far. */
2074 /* Full match at the current node, rule needs to be added here. */
2079 /* Must insert a new tree branch for the new rule. */
2080 *edge = trie_branch_create(prefix, ofs, mlen - ofs, 1);
2083 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2086 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2088 const ovs_be32 *prefix = minimatch_get_prefix(&rule->match, trie->field);
2089 struct trie_node *node;
2090 struct trie_node **edges[sizeof(union mf_value) * 8];
2091 int depth = 0, ofs = 0;
2093 /* Walk the tree. */
2094 for (edges[depth] = &trie->root;
2095 (node = *edges[depth]) != NULL;
2096 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
2097 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2098 if (eqbits < node->nbits) {
2099 /* Mismatch, nothing to be removed. This should never happen, as
2100 * only rules in the classifier are ever removed. */
2101 break; /* Log a warning. */
2103 /* Full match so far. */
2107 /* Full prefix match at the current node, remove rule here. */
2108 if (!node->n_rules) {
2109 break; /* Log a warning. */
2113 /* Check if can prune the tree. */
2114 while (!node->n_rules && !(node->edges[0] && node->edges[1])) {
2115 /* No rules and at most one child node, remove this node. */
2116 struct trie_node *next;
2117 next = node->edges[0] ? node->edges[0] : node->edges[1];
2120 if (node->nbits + next->nbits > TRIE_PREFIX_BITS) {
2121 break; /* Cannot combine. */
2123 /* Combine node with next. */
2124 next->prefix = node->prefix | next->prefix >> node->nbits;
2125 next->nbits += node->nbits;
2127 trie_node_destroy(node);
2128 /* Update the parent's edge. */
2129 *edges[depth] = next;
2130 if (next || !depth) {
2131 /* Branch not pruned or at root, nothing more to do. */
2134 node = *edges[--depth];
2139 /* Cannot go deeper. This should never happen, since only rules
2140 * that actually exist in the classifier are ever removed. */
2141 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");