2 * Copyright (c) 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include "classifier.h"
20 #include <netinet/in.h>
21 #include "byte-order.h"
22 #include "dynamic-string.h"
29 #include "ovs-thread.h"
36 VLOG_DEFINE_THIS_MODULE(classifier);
41 /* Ports trie depends on both ports sharing the same ovs_be32. */
42 #define TP_PORTS_OFS32 (offsetof(struct flow, tp_src) / 4)
43 BUILD_ASSERT_DECL(TP_PORTS_OFS32 == offsetof(struct flow, tp_dst) / 4);
45 typedef OVSRCU_TYPE(struct trie_node *) rcu_trie_ptr;
47 /* Prefix trie for a 'field' */
49 const struct mf_field *field; /* Trie field, or NULL. */
50 rcu_trie_ptr root; /* NULL if none. */
54 CLS_MAX_INDICES = 3 /* Maximum number of lookup indices per subtable. */
57 struct cls_classifier {
58 struct ovs_mutex mutex;
59 int n_rules OVS_GUARDED; /* Total number of rules. */
60 uint8_t n_flow_segments;
61 uint8_t flow_segments[CLS_MAX_INDICES]; /* Flow segment boundaries to use
62 * for staged lookup. */
63 struct cmap subtables_map; /* Contains "struct cls_subtable"s. */
64 struct pvector subtables;
65 struct cmap partitions; /* Contains "struct cls_partition"s. */
66 struct cls_trie tries[CLS_MAX_TRIES]; /* Prefix tries. */
70 /* A set of rules that all have the same fields wildcarded. */
72 /* The fields are only used by writers and iterators. */
73 struct cmap_node cmap_node; /* Within struct cls_classifier
76 /* The fields are only used by writers. */
77 int n_rules OVS_GUARDED; /* Number of rules, including
79 unsigned int max_priority OVS_GUARDED; /* Max priority of any rule in
81 unsigned int max_count OVS_GUARDED; /* Count of max_priority rules. */
83 /* These fields are accessed by readers who care about wildcarding. */
84 tag_type tag; /* Tag generated from mask for partitioning (const). */
85 uint8_t n_indices; /* How many indices to use (const). */
86 uint8_t index_ofs[CLS_MAX_INDICES]; /* u32 segment boundaries (const). */
87 unsigned int trie_plen[CLS_MAX_TRIES]; /* Trie prefix length in 'mask'
88 * (runtime configurable). */
89 int ports_mask_len; /* (const) */
90 struct cmap indices[CLS_MAX_INDICES]; /* Staged lookup indices. */
91 rcu_trie_ptr ports_trie; /* NULL if none. */
93 /* These fields are accessed by all readers. */
94 struct cmap rules; /* Contains "struct cls_rule"s. */
95 struct minimask mask; /* Wildcards for fields (const). */
96 /* 'mask' must be the last field. */
99 /* Associates a metadata value (that is, a value of the OpenFlow 1.1+ metadata
100 * field) with tags for the "cls_subtable"s that contain rules that match that
102 struct cls_partition {
103 struct cmap_node cmap_node; /* In struct cls_classifier's 'partitions'
105 ovs_be64 metadata; /* metadata value for this partition. */
106 tag_type tags; /* OR of each flow's cls_subtable tag. */
107 struct tag_tracker tracker OVS_GUARDED; /* Tracks the bits in 'tags'. */
110 /* Internal representation of a rule in a "struct cls_subtable". */
112 /* Accessed only by writers and iterators. */
113 struct list list OVS_GUARDED; /* List of identical, lower-priority rules. */
115 /* Accessed only by writers. */
116 struct cls_partition *partition OVS_GUARDED;
118 /* Accessed by readers interested in wildcarding. */
119 unsigned int priority; /* Larger numbers are higher priorities. */
120 struct cmap_node index_nodes[CLS_MAX_INDICES]; /* Within subtable's
122 /* Accessed by all readers. */
123 struct cmap_node cmap_node; /* Within struct cls_subtable 'rules'. */
124 struct cls_rule *cls_rule;
125 struct miniflow flow; /* Matching rule. Mask is in the subtable. */
126 /* 'flow' must be the last field. */
129 static struct cls_match *
130 cls_match_alloc(struct cls_rule *rule)
132 int count = count_1bits(rule->match.flow.map);
134 struct cls_match *cls_match
135 = xmalloc(sizeof *cls_match - sizeof cls_match->flow.inline_values
136 + MINIFLOW_VALUES_SIZE(count));
138 cls_match->cls_rule = rule;
139 miniflow_clone_inline(&cls_match->flow, &rule->match.flow, count);
140 cls_match->priority = rule->priority;
141 rule->cls_match = cls_match;
146 static struct cls_subtable *find_subtable(const struct cls_classifier *cls,
147 const struct minimask *)
148 OVS_REQUIRES(cls->mutex);
149 static struct cls_subtable *insert_subtable(struct cls_classifier *cls,
150 const struct minimask *)
151 OVS_REQUIRES(cls->mutex);
152 static void destroy_subtable(struct cls_classifier *cls, struct cls_subtable *)
153 OVS_REQUIRES(cls->mutex);
154 static struct cls_match *insert_rule(struct cls_classifier *cls,
155 struct cls_subtable *, struct cls_rule *)
156 OVS_REQUIRES(cls->mutex);
158 static struct cls_match *find_match_wc(const struct cls_subtable *,
159 const struct flow *, struct trie_ctx *,
160 unsigned int n_tries,
161 struct flow_wildcards *);
162 static struct cls_match *find_equal(struct cls_subtable *,
163 const struct miniflow *, uint32_t hash);
165 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list.
166 * Classifier's mutex must be held while iterating, as the list is
167 * protoceted by it. */
168 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD) \
169 for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
170 #define FOR_EACH_RULE_IN_LIST_SAFE(RULE, NEXT, HEAD) \
171 for ((RULE) = (HEAD); \
172 (RULE) != NULL && ((NEXT) = next_rule_in_list(RULE), true); \
175 static struct cls_match *next_rule_in_list__(struct cls_match *);
176 static struct cls_match *next_rule_in_list(struct cls_match *);
178 static unsigned int minimask_get_prefix_len(const struct minimask *,
179 const struct mf_field *);
180 static void trie_init(struct cls_classifier *cls, int trie_idx,
181 const struct mf_field *)
182 OVS_REQUIRES(cls->mutex);
183 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
184 unsigned int *checkbits);
185 static unsigned int trie_lookup_value(const rcu_trie_ptr *,
186 const ovs_be32 value[],
187 unsigned int value_bits,
188 unsigned int *checkbits);
189 static void trie_destroy(rcu_trie_ptr *);
190 static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
191 static void trie_insert_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
193 static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
194 static void trie_remove_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
196 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
197 unsigned int n_bits);
198 static bool mask_prefix_bits_set(const struct flow_wildcards *,
199 uint8_t be32ofs, unsigned int n_bits);
201 /* flow/miniflow/minimask/minimatch utilities.
202 * These are only used by the classifier, so place them here to allow
203 * for better optimization. */
205 static inline uint64_t
206 miniflow_get_map_in_range(const struct miniflow *miniflow,
207 uint8_t start, uint8_t end, unsigned int *offset)
209 uint64_t map = miniflow->map;
213 uint64_t msk = (UINT64_C(1) << start) - 1; /* 'start' LSBs set */
214 *offset = count_1bits(map & msk);
217 if (end < FLOW_U32S) {
218 uint64_t msk = (UINT64_C(1) << end) - 1; /* 'end' LSBs set */
224 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
225 * 'mask', given 'basis'.
227 * The hash values returned by this function are the same as those returned by
228 * miniflow_hash_in_minimask(), only the form of the arguments differ. */
229 static inline uint32_t
230 flow_hash_in_minimask(const struct flow *flow, const struct minimask *mask,
233 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
234 const uint32_t *flow_u32 = (const uint32_t *)flow;
235 const uint32_t *p = mask_values;
240 for (map = mask->masks.map; map; map = zero_rightmost_1bit(map)) {
241 hash = hash_add(hash, flow_u32[raw_ctz(map)] & *p++);
244 return hash_finish(hash, (p - mask_values) * 4);
247 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
248 * 'mask', given 'basis'.
250 * The hash values returned by this function are the same as those returned by
251 * flow_hash_in_minimask(), only the form of the arguments differ. */
252 static inline uint32_t
253 miniflow_hash_in_minimask(const struct miniflow *flow,
254 const struct minimask *mask, uint32_t basis)
256 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
257 const uint32_t *p = mask_values;
258 uint32_t hash = basis;
261 MINIFLOW_FOR_EACH_IN_MAP(flow_u32, flow, mask->masks.map) {
262 hash = hash_add(hash, flow_u32 & *p++);
265 return hash_finish(hash, (p - mask_values) * 4);
268 /* Returns a hash value for the bits of range [start, end) in 'flow',
269 * where there are 1-bits in 'mask', given 'hash'.
271 * The hash values returned by this function are the same as those returned by
272 * minimatch_hash_range(), only the form of the arguments differ. */
273 static inline uint32_t
274 flow_hash_in_minimask_range(const struct flow *flow,
275 const struct minimask *mask,
276 uint8_t start, uint8_t end, uint32_t *basis)
278 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
279 const uint32_t *flow_u32 = (const uint32_t *)flow;
281 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
283 const uint32_t *p = mask_values + offset;
284 uint32_t hash = *basis;
286 for (; map; map = zero_rightmost_1bit(map)) {
287 hash = hash_add(hash, flow_u32[raw_ctz(map)] & *p++);
290 *basis = hash; /* Allow continuation from the unfinished value. */
291 return hash_finish(hash, (p - mask_values) * 4);
294 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask. */
296 flow_wildcards_fold_minimask(struct flow_wildcards *wc,
297 const struct minimask *mask)
299 flow_union_with_miniflow(&wc->masks, &mask->masks);
302 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask
303 * in range [start, end). */
305 flow_wildcards_fold_minimask_range(struct flow_wildcards *wc,
306 const struct minimask *mask,
307 uint8_t start, uint8_t end)
309 uint32_t *dst_u32 = (uint32_t *)&wc->masks;
311 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
313 const uint32_t *p = miniflow_get_u32_values(&mask->masks) + offset;
315 for (; map; map = zero_rightmost_1bit(map)) {
316 dst_u32[raw_ctz(map)] |= *p++;
320 /* Returns a hash value for 'flow', given 'basis'. */
321 static inline uint32_t
322 miniflow_hash(const struct miniflow *flow, uint32_t basis)
324 const uint32_t *values = miniflow_get_u32_values(flow);
325 const uint32_t *p = values;
326 uint32_t hash = basis;
327 uint64_t hash_map = 0;
330 for (map = flow->map; map; map = zero_rightmost_1bit(map)) {
332 hash = hash_add(hash, *p);
333 hash_map |= rightmost_1bit(map);
337 hash = hash_add(hash, hash_map);
338 hash = hash_add(hash, hash_map >> 32);
340 return hash_finish(hash, p - values);
343 /* Returns a hash value for 'mask', given 'basis'. */
344 static inline uint32_t
345 minimask_hash(const struct minimask *mask, uint32_t basis)
347 return miniflow_hash(&mask->masks, basis);
350 /* Returns a hash value for 'match', given 'basis'. */
351 static inline uint32_t
352 minimatch_hash(const struct minimatch *match, uint32_t basis)
354 return miniflow_hash(&match->flow, minimask_hash(&match->mask, basis));
357 /* Returns a hash value for the bits of range [start, end) in 'minimatch',
360 * The hash values returned by this function are the same as those returned by
361 * flow_hash_in_minimask_range(), only the form of the arguments differ. */
362 static inline uint32_t
363 minimatch_hash_range(const struct minimatch *match, uint8_t start, uint8_t end,
367 const uint32_t *p, *q;
368 uint32_t hash = *basis;
371 n = count_1bits(miniflow_get_map_in_range(&match->mask.masks, start, end,
373 q = miniflow_get_u32_values(&match->mask.masks) + offset;
374 p = miniflow_get_u32_values(&match->flow) + offset;
376 for (i = 0; i < n; i++) {
377 hash = hash_add(hash, p[i] & q[i]);
379 *basis = hash; /* Allow continuation from the unfinished value. */
380 return hash_finish(hash, (offset + n) * 4);
386 /* Initializes 'rule' to match packets specified by 'match' at the given
387 * 'priority'. 'match' must satisfy the invariant described in the comment at
388 * the definition of struct match.
390 * The caller must eventually destroy 'rule' with cls_rule_destroy().
392 * (OpenFlow uses priorities between 0 and UINT16_MAX, inclusive, but
393 * internally Open vSwitch supports a wider range.) */
395 cls_rule_init(struct cls_rule *rule,
396 const struct match *match, unsigned int priority)
398 minimatch_init(&rule->match, match);
399 rule->priority = priority;
400 rule->cls_match = NULL;
403 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
405 cls_rule_init_from_minimatch(struct cls_rule *rule,
406 const struct minimatch *match,
407 unsigned int priority)
409 minimatch_clone(&rule->match, match);
410 rule->priority = priority;
411 rule->cls_match = NULL;
414 /* Initializes 'dst' as a copy of 'src'.
416 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
418 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
420 minimatch_clone(&dst->match, &src->match);
421 dst->priority = src->priority;
422 dst->cls_match = NULL;
425 /* Initializes 'dst' with the data in 'src', destroying 'src'.
427 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
429 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
431 minimatch_move(&dst->match, &src->match);
432 dst->priority = src->priority;
433 dst->cls_match = NULL;
436 /* Frees memory referenced by 'rule'. Doesn't free 'rule' itself (it's
437 * normally embedded into a larger structure).
439 * ('rule' must not currently be in a classifier.) */
441 cls_rule_destroy(struct cls_rule *rule)
443 ovs_assert(!rule->cls_match);
444 minimatch_destroy(&rule->match);
447 /* Returns true if 'a' and 'b' match the same packets at the same priority,
448 * false if they differ in some way. */
450 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
452 return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
455 /* Returns a hash value for 'rule', folding in 'basis'. */
457 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
459 return minimatch_hash(&rule->match, hash_int(rule->priority, basis));
462 /* Appends a string describing 'rule' to 's'. */
464 cls_rule_format(const struct cls_rule *rule, struct ds *s)
466 minimatch_format(&rule->match, s, rule->priority);
469 /* Returns true if 'rule' matches every packet, false otherwise. */
471 cls_rule_is_catchall(const struct cls_rule *rule)
473 return minimask_is_catchall(&rule->match.mask);
476 /* Initializes 'cls' as a classifier that initially contains no classification
479 classifier_init(struct classifier *cls_, const uint8_t *flow_segments)
480 OVS_EXCLUDED(cls_->cls->mutex)
482 struct cls_classifier *cls = xmalloc(sizeof *cls);
484 ovs_mutex_init(&cls->mutex);
486 ovs_mutex_lock(&cls->mutex);
490 cmap_init(&cls->subtables_map);
491 pvector_init(&cls->subtables);
492 cmap_init(&cls->partitions);
493 cls->n_flow_segments = 0;
495 while (cls->n_flow_segments < CLS_MAX_INDICES
496 && *flow_segments < FLOW_U32S) {
497 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
501 for (int i = 0; i < CLS_MAX_TRIES; i++) {
502 trie_init(cls, i, NULL);
504 ovs_mutex_unlock(&cls->mutex);
507 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
508 * caller's responsibility.
509 * May only be called after all the readers have been terminated. */
511 classifier_destroy(struct classifier *cls_)
512 OVS_EXCLUDED(cls_->cls->mutex)
515 struct cls_classifier *cls = cls_->cls;
516 struct cls_partition *partition, *next_partition;
517 struct cls_subtable *subtable, *next_subtable;
524 ovs_mutex_lock(&cls->mutex);
525 for (i = 0; i < cls->n_tries; i++) {
526 trie_destroy(&cls->tries[i].root);
529 CMAP_FOR_EACH_SAFE (subtable, next_subtable, cmap_node,
530 &cls->subtables_map) {
531 destroy_subtable(cls, subtable);
533 cmap_destroy(&cls->subtables_map);
535 CMAP_FOR_EACH_SAFE (partition, next_partition, cmap_node,
537 ovsrcu_postpone(free, partition);
539 cmap_destroy(&cls->partitions);
541 pvector_destroy(&cls->subtables);
542 ovs_mutex_unlock(&cls->mutex);
543 ovs_mutex_destroy(&cls->mutex);
548 /* We use uint64_t as a set for the fields below. */
549 BUILD_ASSERT_DECL(MFF_N_IDS <= 64);
551 /* Set the fields for which prefix lookup should be performed. */
553 classifier_set_prefix_fields(struct classifier *cls_,
554 const enum mf_field_id *trie_fields,
555 unsigned int n_fields)
556 OVS_EXCLUDED(cls_->cls->mutex)
558 struct cls_classifier *cls = cls_->cls;
560 const struct mf_field * new_fields[CLS_MAX_TRIES];
562 bool changed = false;
564 ovs_mutex_lock(&cls->mutex);
565 for (i = 0; i < n_fields && n_tries < CLS_MAX_TRIES; i++) {
566 const struct mf_field *field = mf_from_id(trie_fields[i]);
567 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
568 /* Incompatible field. This is the only place where we
569 * enforce these requirements, but the rest of the trie code
570 * depends on the flow_be32ofs to be non-negative and the
571 * field length to be a multiple of 32 bits. */
575 if (fields & (UINT64_C(1) << trie_fields[i])) {
576 /* Duplicate field, there is no need to build more than
577 * one index for any one field. */
580 fields |= UINT64_C(1) << trie_fields[i];
582 new_fields[n_tries] = NULL;
583 if (n_tries >= cls->n_tries || field != cls->tries[n_tries].field) {
584 new_fields[n_tries] = field;
590 if (changed || n_tries < cls->n_tries) {
591 struct cls_subtable *subtable;
593 /* Trie configuration needs to change. Disable trie lookups
594 * for the tries that are changing and wait all the current readers
595 * with the old configuration to be done. */
597 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
598 for (i = 0; i < cls->n_tries; i++) {
599 if ((i < n_tries && new_fields[i]) || i >= n_tries) {
600 if (subtable->trie_plen[i]) {
601 subtable->trie_plen[i] = 0;
607 /* Synchronize if any readers were using tries. The readers may
608 * temporarily function without the trie lookup based optimizations. */
610 /* ovsrcu_synchronize() functions as a memory barrier, so it does
611 * not matter that subtable->trie_plen is not atomic. */
612 ovsrcu_synchronize();
615 /* Now set up the tries. */
616 for (i = 0; i < n_tries; i++) {
618 trie_init(cls, i, new_fields[i]);
621 /* Destroy the rest, if any. */
622 for (; i < cls->n_tries; i++) {
623 trie_init(cls, i, NULL);
626 cls->n_tries = n_tries;
627 ovs_mutex_unlock(&cls->mutex);
631 ovs_mutex_unlock(&cls->mutex);
632 return false; /* No change. */
636 trie_init(struct cls_classifier *cls, int trie_idx,
637 const struct mf_field *field)
638 OVS_REQUIRES(cls->mutex)
640 struct cls_trie *trie = &cls->tries[trie_idx];
641 struct cls_subtable *subtable;
643 if (trie_idx < cls->n_tries) {
644 trie_destroy(&trie->root);
646 ovsrcu_set_hidden(&trie->root, NULL);
650 /* Add existing rules to the new trie. */
651 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
654 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
656 struct cls_match *head;
658 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
659 struct cls_match *match;
661 FOR_EACH_RULE_IN_LIST (match, head) {
662 trie_insert(trie, match->cls_rule, plen);
666 /* Initialize subtable's prefix length on this field. This will
667 * allow readers to use the trie. */
668 atomic_thread_fence(memory_order_release);
669 subtable->trie_plen[trie_idx] = plen;
673 /* Returns true if 'cls' contains no classification rules, false otherwise.
674 * Checking the cmap requires no locking. */
676 classifier_is_empty(const struct classifier *cls)
678 return cmap_is_empty(&cls->cls->subtables_map);
681 /* Returns the number of rules in 'cls'. */
683 classifier_count(const struct classifier *cls)
684 OVS_NO_THREAD_SAFETY_ANALYSIS
686 /* n_rules is an int, so in the presence of concurrent writers this will
687 * return either the old or a new value. */
688 return cls->cls->n_rules;
692 hash_metadata(ovs_be64 metadata_)
694 uint64_t metadata = (OVS_FORCE uint64_t) metadata_;
695 return hash_uint64(metadata);
698 static struct cls_partition *
699 find_partition(const struct cls_classifier *cls, ovs_be64 metadata,
702 struct cls_partition *partition;
704 CMAP_FOR_EACH_WITH_HASH (partition, cmap_node, hash, &cls->partitions) {
705 if (partition->metadata == metadata) {
713 static struct cls_partition *
714 create_partition(struct cls_classifier *cls, struct cls_subtable *subtable,
716 OVS_REQUIRES(cls->mutex)
718 uint32_t hash = hash_metadata(metadata);
719 struct cls_partition *partition = find_partition(cls, metadata, hash);
721 partition = xmalloc(sizeof *partition);
722 partition->metadata = metadata;
724 tag_tracker_init(&partition->tracker);
725 cmap_insert(&cls->partitions, &partition->cmap_node, hash);
727 tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
731 static inline ovs_be32 minimatch_get_ports(const struct minimatch *match)
733 /* Could optimize to use the same map if needed for fast path. */
734 return MINIFLOW_GET_BE32(&match->flow, tp_src)
735 & MINIFLOW_GET_BE32(&match->mask.masks, tp_src);
738 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
739 * must not modify or free it.
741 * If 'cls' already contains an identical rule (including wildcards, values of
742 * fixed fields, and priority), replaces the old rule by 'rule' and returns the
743 * rule that was replaced. The caller takes ownership of the returned rule and
744 * is thus responsible for destroying it with cls_rule_destroy(), freeing the
745 * memory block in which it resides, etc., as necessary.
747 * Returns NULL if 'cls' does not contain a rule with an identical key, after
748 * inserting the new rule. In this case, no rules are displaced by the new
749 * rule, even rules that cannot have any effect because the new rule matches a
750 * superset of their flows and has higher priority. */
752 classifier_replace(struct classifier *cls_, struct cls_rule *rule)
753 OVS_EXCLUDED(cls_->cls->mutex)
755 struct cls_classifier *cls = cls_->cls;
756 struct cls_match *old_rule;
757 struct cls_subtable *subtable;
758 struct cls_rule *old_cls_rule = NULL;
760 ovs_mutex_lock(&cls->mutex);
761 subtable = find_subtable(cls, &rule->match.mask);
763 subtable = insert_subtable(cls, &rule->match.mask);
766 old_rule = insert_rule(cls, subtable, rule);
770 rule->cls_match->partition = NULL;
771 if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
772 ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
773 rule->cls_match->partition = create_partition(cls, subtable,
779 for (int i = 0; i < cls->n_tries; i++) {
780 if (subtable->trie_plen[i]) {
781 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
786 if (subtable->ports_mask_len) {
787 /* We mask the value to be inserted to always have the wildcarded
788 * bits in known (zero) state, so we can include them in comparison
789 * and they will always match (== their original value does not
791 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
793 trie_insert_prefix(&subtable->ports_trie, &masked_ports,
794 subtable->ports_mask_len);
797 old_cls_rule = old_rule->cls_rule;
798 rule->cls_match->partition = old_rule->partition;
799 old_cls_rule->cls_match = NULL;
801 /* 'old_rule' contains a cmap_node, which may not be freed
803 ovsrcu_postpone(free, old_rule);
805 ovs_mutex_unlock(&cls->mutex);
809 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
810 * must not modify or free it.
812 * 'cls' must not contain an identical rule (including wildcards, values of
813 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
816 classifier_insert(struct classifier *cls, struct cls_rule *rule)
818 struct cls_rule *displaced_rule = classifier_replace(cls, rule);
819 ovs_assert(!displaced_rule);
822 /* Removes 'rule' from 'cls'. It is the caller's responsibility to destroy
823 * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
824 * resides, etc., as necessary. */
826 classifier_remove(struct classifier *cls_, struct cls_rule *rule)
827 OVS_EXCLUDED(cls_->cls->mutex)
829 struct cls_classifier *cls = cls_->cls;
830 struct cls_partition *partition;
831 struct cls_match *cls_match = rule->cls_match;
832 struct cls_match *head;
833 struct cls_subtable *subtable;
835 uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
836 uint8_t prev_be32ofs = 0;
838 ovs_assert(cls_match);
840 ovs_mutex_lock(&cls->mutex);
841 subtable = find_subtable(cls, &rule->match.mask);
842 ovs_assert(subtable);
844 if (subtable->ports_mask_len) {
845 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
847 trie_remove_prefix(&subtable->ports_trie,
848 &masked_ports, subtable->ports_mask_len);
850 for (i = 0; i < cls->n_tries; i++) {
851 if (subtable->trie_plen[i]) {
852 trie_remove(&cls->tries[i], rule, subtable->trie_plen[i]);
856 /* Remove rule node from indices. */
857 for (i = 0; i < subtable->n_indices; i++) {
858 ihash[i] = minimatch_hash_range(&rule->match, prev_be32ofs,
859 subtable->index_ofs[i], &basis);
860 cmap_remove(&subtable->indices[i], &cls_match->index_nodes[i],
862 prev_be32ofs = subtable->index_ofs[i];
864 hash = minimatch_hash_range(&rule->match, prev_be32ofs, FLOW_U32S, &basis);
866 head = find_equal(subtable, &rule->match.flow, hash);
867 if (head != cls_match) {
868 list_remove(&cls_match->list);
869 } else if (list_is_empty(&cls_match->list)) {
870 cmap_remove(&subtable->rules, &cls_match->cmap_node, hash);
872 struct cls_match *next = CONTAINER_OF(cls_match->list.next,
873 struct cls_match, list);
875 list_remove(&cls_match->list);
876 cmap_replace(&subtable->rules, &cls_match->cmap_node,
877 &next->cmap_node, hash);
880 partition = cls_match->partition;
882 tag_tracker_subtract(&partition->tracker, &partition->tags,
884 if (!partition->tags) {
885 cmap_remove(&cls->partitions, &partition->cmap_node,
886 hash_metadata(partition->metadata));
887 ovsrcu_postpone(free, partition);
891 if (--subtable->n_rules == 0) {
892 destroy_subtable(cls, subtable);
893 } else if (subtable->max_priority == cls_match->priority
894 && --subtable->max_count == 0) {
895 /* Find the new 'max_priority' and 'max_count'. */
896 struct cls_match *head;
897 unsigned int max_priority = 0;
899 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
900 if (head->priority > max_priority) {
901 max_priority = head->priority;
902 subtable->max_count = 1;
903 } else if (head->priority == max_priority) {
904 ++subtable->max_count;
907 subtable->max_priority = max_priority;
908 pvector_change_priority(&cls->subtables, subtable, max_priority);
913 rule->cls_match = NULL;
914 ovsrcu_postpone(free, cls_match);
915 ovs_mutex_unlock(&cls->mutex);
918 /* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
919 * subtables which have more than 'match_plen' bits in their corresponding
920 * field at offset 'be32ofs'. If skipped, 'maskbits' prefix bits should be
921 * unwildcarded to quarantee datapath flow matches only packets it should. */
923 const struct cls_trie *trie;
924 bool lookup_done; /* Status of the lookup. */
925 uint8_t be32ofs; /* U32 offset of the field in question. */
926 unsigned int match_plen; /* Longest prefix than could possibly match. */
927 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
931 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
934 ctx->be32ofs = trie->field->flow_be32ofs;
935 ctx->lookup_done = false;
938 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
939 * Returns a null pointer if no rules in 'cls' match 'flow'. If multiple rules
940 * of equal priority match 'flow', returns one arbitrarily.
942 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
943 * set of bits that were significant in the lookup. At some point
944 * earlier, 'wc' should have been initialized (e.g., by
945 * flow_wildcards_init_catchall()). */
947 classifier_lookup(const struct classifier *cls_, const struct flow *flow,
948 struct flow_wildcards *wc)
950 struct cls_classifier *cls = cls_->cls;
951 const struct cls_partition *partition;
953 int64_t best_priority = -1;
954 const struct cls_match *best;
955 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
956 struct cls_subtable *subtable;
958 /* Synchronize for cls->n_tries and subtable->trie_plen. They can change
959 * when table configuration changes, which happens typically only on
961 atomic_thread_fence(memory_order_acquire);
963 /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
964 * then 'flow' cannot possibly match in 'subtable':
966 * - If flow->metadata maps to a given 'partition', then we can use
967 * 'tags' for 'partition->tags'.
969 * - If flow->metadata has no partition, then no rule in 'cls' has an
970 * exact-match for flow->metadata. That means that we don't need to
971 * search any subtable that includes flow->metadata in its mask.
973 * In either case, we always need to search any cls_subtables that do not
974 * include flow->metadata in its mask. One way to do that would be to
975 * check the "cls_subtable"s explicitly for that, but that would require an
976 * extra branch per subtable. Instead, we mark such a cls_subtable's
977 * 'tags' as TAG_ALL and make sure that 'tags' is never empty. This means
978 * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
979 * need a special case.
981 partition = (cmap_is_empty(&cls->partitions)
983 : find_partition(cls, flow->metadata,
984 hash_metadata(flow->metadata)));
985 tags = partition ? partition->tags : TAG_ARBITRARY;
987 /* Initialize trie contexts for match_find_wc(). */
988 for (int i = 0; i < cls->n_tries; i++) {
989 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
993 PVECTOR_FOR_EACH_PRIORITY(subtable, best_priority, 2,
994 sizeof(struct cls_subtable), &cls->subtables) {
995 struct cls_match *rule;
997 if (!tag_intersects(tags, subtable->tag)) {
1001 rule = find_match_wc(subtable, flow, trie_ctx, cls->n_tries, wc);
1002 if (rule && (int64_t)rule->priority > best_priority) {
1003 best_priority = (int64_t)rule->priority;
1008 return best ? best->cls_rule : NULL;
1011 /* Returns true if 'target' satisifies 'match', that is, if each bit for which
1012 * 'match' specifies a particular value has the correct value in 'target'.
1014 * 'flow' and 'mask' have the same mask! */
1016 miniflow_and_mask_matches_miniflow(const struct miniflow *flow,
1017 const struct minimask *mask,
1018 const struct miniflow *target)
1020 const uint32_t *flowp = miniflow_get_u32_values(flow);
1021 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1022 uint32_t target_u32;
1024 MINIFLOW_FOR_EACH_IN_MAP(target_u32, target, mask->masks.map) {
1025 if ((*flowp++ ^ target_u32) & *maskp++) {
1033 static inline struct cls_match *
1034 find_match_miniflow(const struct cls_subtable *subtable,
1035 const struct miniflow *flow,
1038 struct cls_match *rule;
1040 CMAP_FOR_EACH_WITH_HASH (rule, cmap_node, hash, &subtable->rules) {
1041 if (miniflow_and_mask_matches_miniflow(&rule->flow, &subtable->mask,
1050 /* For each miniflow in 'flows' performs a classifier lookup writing the result
1051 * into the corresponding slot in 'rules'. If a particular entry in 'flows' is
1052 * NULL it is skipped.
1054 * This function is optimized for use in the userspace datapath and therefore
1055 * does not implement a lot of features available in the standard
1056 * classifier_lookup() function. Specifically, it does not implement
1057 * priorities, instead returning any rule which matches the flow. */
1059 classifier_lookup_miniflow_batch(const struct classifier *cls_,
1060 const struct miniflow **flows,
1061 struct cls_rule **rules, size_t len)
1063 struct cls_classifier *cls = cls_->cls;
1064 struct cls_subtable *subtable;
1065 size_t i, begin = 0;
1067 memset(rules, 0, len * sizeof *rules);
1068 PVECTOR_FOR_EACH (subtable, &cls->subtables) {
1069 for (i = begin; i < len; i++) {
1070 struct cls_match *match;
1073 if (OVS_UNLIKELY(rules[i] || !flows[i])) {
1077 hash = miniflow_hash_in_minimask(flows[i], &subtable->mask, 0);
1078 match = find_match_miniflow(subtable, flows[i], hash);
1079 if (OVS_UNLIKELY(match)) {
1080 rules[i] = match->cls_rule;
1084 while (begin < len && (rules[begin] || !flows[begin])) {
1093 /* Finds and returns a rule in 'cls' with exactly the same priority and
1094 * matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
1095 * contain an exact match. */
1097 classifier_find_rule_exactly(const struct classifier *cls_,
1098 const struct cls_rule *target)
1099 OVS_EXCLUDED(cls_->cls->mutex)
1101 struct cls_classifier *cls = cls_->cls;
1102 struct cls_match *head, *rule;
1103 struct cls_subtable *subtable;
1105 ovs_mutex_lock(&cls->mutex);
1106 subtable = find_subtable(cls, &target->match.mask);
1111 /* Skip if there is no hope. */
1112 if (target->priority > subtable->max_priority) {
1116 head = find_equal(subtable, &target->match.flow,
1117 miniflow_hash_in_minimask(&target->match.flow,
1118 &target->match.mask, 0));
1119 FOR_EACH_RULE_IN_LIST (rule, head) {
1120 if (target->priority >= rule->priority) {
1121 ovs_mutex_unlock(&cls->mutex);
1122 return target->priority == rule->priority ? rule->cls_rule : NULL;
1126 ovs_mutex_unlock(&cls->mutex);
1130 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
1131 * same matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
1132 * contain an exact match. */
1134 classifier_find_match_exactly(const struct classifier *cls,
1135 const struct match *target,
1136 unsigned int priority)
1138 struct cls_rule *retval;
1141 cls_rule_init(&cr, target, priority);
1142 retval = classifier_find_rule_exactly(cls, &cr);
1143 cls_rule_destroy(&cr);
1148 /* Checks if 'target' would overlap any other rule in 'cls'. Two rules are
1149 * considered to overlap if both rules have the same priority and a packet
1150 * could match both. */
1152 classifier_rule_overlaps(const struct classifier *cls_,
1153 const struct cls_rule *target)
1154 OVS_EXCLUDED(cls_->cls->mutex)
1156 struct cls_classifier *cls = cls_->cls;
1157 struct cls_subtable *subtable;
1158 int64_t stop_at_priority = (int64_t)target->priority - 1;
1160 ovs_mutex_lock(&cls->mutex);
1161 /* Iterate subtables in the descending max priority order. */
1162 PVECTOR_FOR_EACH_PRIORITY (subtable, stop_at_priority, 2,
1163 sizeof(struct cls_subtable), &cls->subtables) {
1164 uint32_t storage[FLOW_U32S];
1165 struct minimask mask;
1166 struct cls_match *head;
1168 minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
1169 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
1170 struct cls_match *rule;
1172 FOR_EACH_RULE_IN_LIST (rule, head) {
1173 if (rule->priority < target->priority) {
1174 break; /* Rules in descending priority order. */
1176 if (rule->priority == target->priority
1177 && miniflow_equal_in_minimask(&target->match.flow,
1178 &rule->flow, &mask)) {
1179 ovs_mutex_unlock(&cls->mutex);
1186 ovs_mutex_unlock(&cls->mutex);
1190 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
1191 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
1192 * function returns true if, for every field:
1194 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
1197 * - 'criteria' wildcards the field,
1199 * Conversely, 'rule' does not match 'criteria' and this function returns false
1200 * if, for at least one field:
1202 * - 'criteria' and 'rule' specify different values for the field, or
1204 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
1206 * Equivalently, the truth table for whether a field matches is:
1211 * r +---------+---------+
1212 * i wild | yes | yes |
1214 * e +---------+---------+
1215 * r exact | no |if values|
1217 * a +---------+---------+
1219 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
1220 * commands and by OpenFlow 1.0 aggregate and flow stats.
1222 * Ignores rule->priority. */
1224 cls_rule_is_loose_match(const struct cls_rule *rule,
1225 const struct minimatch *criteria)
1227 return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
1228 && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
1235 rule_matches(const struct cls_match *rule, const struct cls_rule *target)
1238 || miniflow_equal_in_minimask(&rule->flow,
1239 &target->match.flow,
1240 &target->match.mask));
1243 static struct cls_match *
1244 search_subtable(const struct cls_subtable *subtable,
1245 struct cls_cursor *cursor)
1248 || !minimask_has_extra(&subtable->mask, &cursor->target->match.mask)) {
1249 struct cls_match *rule;
1251 CMAP_CURSOR_FOR_EACH (rule, cmap_node, &cursor->rules,
1253 if (rule_matches(rule, cursor->target)) {
1261 /* Initializes 'cursor' for iterating through rules in 'cls', and returns the
1262 * first matching cls_rule via '*pnode', or NULL if there are no matches.
1264 * - If 'target' is null, the cursor will visit every rule in 'cls'.
1266 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1267 * such that cls_rule_is_loose_match(rule, target) returns true.
1269 * Ignores target->priority. */
1270 struct cls_cursor cls_cursor_init(const struct classifier *cls,
1271 const struct cls_rule *target,
1272 void **pnode, const void *offset, bool safe)
1273 OVS_NO_THREAD_SAFETY_ANALYSIS
1275 struct cls_cursor cursor;
1276 struct cls_subtable *subtable;
1277 struct cls_rule *cls_rule = NULL;
1280 cursor.cls = cls->cls;
1281 cursor.target = target && !cls_rule_is_catchall(target) ? target : NULL;
1283 /* Find first rule. */
1284 ovs_mutex_lock(&cursor.cls->mutex);
1285 CMAP_CURSOR_FOR_EACH (subtable, cmap_node, &cursor.subtables,
1286 &cursor.cls->subtables_map) {
1287 struct cls_match *rule = search_subtable(subtable, &cursor);
1290 cursor.subtable = subtable;
1291 cls_rule = rule->cls_rule;
1295 *pnode = (char *)cls_rule + (ptrdiff_t)offset;
1297 /* Leave locked if requested and have a rule. */
1298 if (safe || !cls_rule) {
1299 ovs_mutex_unlock(&cursor.cls->mutex);
1305 cls_cursor_next_unlock(struct cls_cursor *cursor, struct cls_rule *rule)
1306 OVS_NO_THREAD_SAFETY_ANALYSIS
1308 /* Release the mutex if no rule, or 'safe' mode. */
1309 if (!rule || cursor->safe) {
1310 ovs_mutex_unlock(&cursor->cls->mutex);
1314 /* Returns the next matching cls_rule in 'cursor''s iteration, or a null
1315 * pointer if there are no more matches. */
1317 cls_cursor_next(struct cls_cursor *cursor, const struct cls_rule *rule_)
1318 OVS_NO_THREAD_SAFETY_ANALYSIS
1320 struct cls_match *rule = CONST_CAST(struct cls_match *, rule_->cls_match);
1321 const struct cls_subtable *subtable;
1322 struct cls_match *next;
1324 /* Lock if not locked already. */
1326 ovs_mutex_lock(&cursor->cls->mutex);
1329 next = next_rule_in_list__(rule);
1330 if (next->priority < rule->priority) {
1331 cls_cursor_next_unlock(cursor, next->cls_rule);
1332 return next->cls_rule;
1335 /* 'next' is the head of the list, that is, the rule that is included in
1336 * the subtable's map. (This is important when the classifier contains
1337 * rules that differ only in priority.) */
1339 CMAP_CURSOR_FOR_EACH_CONTINUE (rule, cmap_node, &cursor->rules) {
1340 if (rule_matches(rule, cursor->target)) {
1341 cls_cursor_next_unlock(cursor, rule->cls_rule);
1342 return rule->cls_rule;
1346 subtable = cursor->subtable;
1347 CMAP_CURSOR_FOR_EACH_CONTINUE (subtable, cmap_node, &cursor->subtables) {
1348 rule = search_subtable(subtable, cursor);
1350 cursor->subtable = subtable;
1351 cls_cursor_next_unlock(cursor, rule->cls_rule);
1352 return rule->cls_rule;
1356 ovs_mutex_unlock(&cursor->cls->mutex);
1360 static struct cls_subtable *
1361 find_subtable(const struct cls_classifier *cls, const struct minimask *mask)
1362 OVS_REQUIRES(cls->mutex)
1364 struct cls_subtable *subtable;
1366 CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, minimask_hash(mask, 0),
1367 &cls->subtables_map) {
1368 if (minimask_equal(mask, &subtable->mask)) {
1375 /* The new subtable will be visible to the readers only after this. */
1376 static struct cls_subtable *
1377 insert_subtable(struct cls_classifier *cls, const struct minimask *mask)
1378 OVS_REQUIRES(cls->mutex)
1380 uint32_t hash = minimask_hash(mask, 0);
1381 struct cls_subtable *subtable;
1383 struct flow_wildcards old, new;
1385 int count = count_1bits(mask->masks.map);
1387 subtable = xzalloc(sizeof *subtable - sizeof mask->masks.inline_values
1388 + MINIFLOW_VALUES_SIZE(count));
1389 cmap_init(&subtable->rules);
1390 miniflow_clone_inline(&subtable->mask.masks, &mask->masks, count);
1392 /* Init indices for segmented lookup, if any. */
1393 flow_wildcards_init_catchall(&new);
1396 for (i = 0; i < cls->n_flow_segments; i++) {
1397 flow_wildcards_fold_minimask_range(&new, mask, prev,
1398 cls->flow_segments[i]);
1399 /* Add an index if it adds mask bits. */
1400 if (!flow_wildcards_equal(&new, &old)) {
1401 cmap_init(&subtable->indices[index]);
1402 subtable->index_ofs[index] = cls->flow_segments[i];
1406 prev = cls->flow_segments[i];
1408 /* Check if the rest of the subtable's mask adds any bits,
1409 * and remove the last index if it doesn't. */
1411 flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U32S);
1412 if (flow_wildcards_equal(&new, &old)) {
1414 subtable->index_ofs[index] = 0;
1415 cmap_destroy(&subtable->indices[index]);
1418 subtable->n_indices = index;
1420 subtable->tag = (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1421 ? tag_create_deterministic(hash)
1424 for (i = 0; i < cls->n_tries; i++) {
1425 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1426 cls->tries[i].field);
1430 ovsrcu_set_hidden(&subtable->ports_trie, NULL);
1431 subtable->ports_mask_len
1432 = 32 - ctz32(ntohl(MINIFLOW_GET_BE32(&mask->masks, tp_src)));
1434 cmap_insert(&cls->subtables_map, &subtable->cmap_node, hash);
1440 destroy_subtable(struct cls_classifier *cls, struct cls_subtable *subtable)
1441 OVS_REQUIRES(cls->mutex)
1445 pvector_remove(&cls->subtables, subtable);
1446 trie_destroy(&subtable->ports_trie);
1448 for (i = 0; i < subtable->n_indices; i++) {
1449 cmap_destroy(&subtable->indices[i]);
1451 cmap_remove(&cls->subtables_map, &subtable->cmap_node,
1452 minimask_hash(&subtable->mask, 0));
1453 minimask_destroy(&subtable->mask);
1454 cmap_destroy(&subtable->rules);
1455 ovsrcu_postpone(free, subtable);
1463 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1464 * lookup results. */
1466 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1467 const unsigned int field_plen[CLS_MAX_TRIES],
1468 const struct range ofs, const struct flow *flow,
1469 struct flow_wildcards *wc)
1473 /* Check if we could avoid fully unwildcarding the next level of
1474 * fields using the prefix tries. The trie checks are done only as
1475 * needed to avoid folding in additional bits to the wildcards mask. */
1476 for (j = 0; j < n_tries; j++) {
1477 /* Is the trie field relevant for this subtable? */
1478 if (field_plen[j]) {
1479 struct trie_ctx *ctx = &trie_ctx[j];
1480 uint8_t be32ofs = ctx->be32ofs;
1482 /* Is the trie field within the current range of fields? */
1483 if (be32ofs >= ofs.start && be32ofs < ofs.end) {
1484 /* On-demand trie lookup. */
1485 if (!ctx->lookup_done) {
1486 ctx->match_plen = trie_lookup(ctx->trie, flow,
1488 ctx->lookup_done = true;
1490 /* Possible to skip the rest of the subtable if subtable's
1491 * prefix on the field is longer than what is known to match
1492 * based on the trie lookup. */
1493 if (field_plen[j] > ctx->match_plen) {
1494 /* RFC: We want the trie lookup to never result in
1495 * unwildcarding any bits that would not be unwildcarded
1496 * otherwise. Since the trie is shared by the whole
1497 * classifier, it is possible that the 'maskbits' contain
1498 * bits that are irrelevant for the partition of the
1499 * classifier relevant for the current flow. */
1501 /* Can skip if the field is already unwildcarded. */
1502 if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1505 /* Check that the trie result will not unwildcard more bits
1506 * than this stage will. */
1507 if (ctx->maskbits <= field_plen[j]) {
1508 /* Unwildcard the bits and skip the rest. */
1509 mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1510 /* Note: Prerequisite already unwildcarded, as the only
1511 * prerequisite of the supported trie lookup fields is
1512 * the ethertype, which is currently always
1524 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1525 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1526 * value has the correct value in 'target'.
1528 * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
1529 * target, mask) but this is faster because of the invariant that
1530 * flow->map and mask->masks.map are the same, and that this version
1531 * takes the 'wc'. */
1533 miniflow_and_mask_matches_flow(const struct miniflow *flow,
1534 const struct minimask *mask,
1535 const struct flow *target)
1537 const uint32_t *flowp = miniflow_get_u32_values(flow);
1538 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1541 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1542 uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & *maskp++;
1552 static inline struct cls_match *
1553 find_match(const struct cls_subtable *subtable, const struct flow *flow,
1556 struct cls_match *rule;
1558 CMAP_FOR_EACH_WITH_HASH (rule, cmap_node, hash, &subtable->rules) {
1559 if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
1568 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1569 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1570 * value has the correct value in 'target'.
1572 * This function is equivalent to miniflow_and_mask_matches_flow() but this
1573 * version fills in the mask bits in 'wc'. */
1575 miniflow_and_mask_matches_flow_wc(const struct miniflow *flow,
1576 const struct minimask *mask,
1577 const struct flow *target,
1578 struct flow_wildcards *wc)
1580 const uint32_t *flowp = miniflow_get_u32_values(flow);
1581 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1584 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1585 uint32_t mask = *maskp++;
1586 uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & mask;
1589 /* Only unwildcard if none of the differing bits is already
1591 if (!(flow_u32_value(&wc->masks, idx) & diff)) {
1592 /* Keep one bit of the difference. */
1593 *flow_u32_lvalue(&wc->masks, idx) |= rightmost_1bit(diff);
1597 /* Fill in the bits that were looked at. */
1598 *flow_u32_lvalue(&wc->masks, idx) |= mask;
1604 /* Unwildcard the fields looked up so far, if any. */
1606 fill_range_wc(const struct cls_subtable *subtable, struct flow_wildcards *wc,
1610 flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, to);
1614 static struct cls_match *
1615 find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
1616 struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1617 struct flow_wildcards *wc)
1619 uint32_t basis = 0, hash;
1620 struct cls_match *rule;
1624 if (OVS_UNLIKELY(!wc)) {
1625 return find_match(subtable, flow,
1626 flow_hash_in_minimask(flow, &subtable->mask, 0));
1630 /* Try to finish early by checking fields in segments. */
1631 for (i = 0; i < subtable->n_indices; i++) {
1632 struct cmap_node *inode;
1634 ofs.end = subtable->index_ofs[i];
1636 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1638 /* 'wc' bits for the trie field set, now unwildcard the preceding
1639 * bits used so far. */
1640 fill_range_wc(subtable, wc, ofs.start);
1643 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1645 inode = cmap_find(&subtable->indices[i], hash);
1647 /* No match, can stop immediately, but must fold in the bits
1648 * used in lookup so far. */
1649 fill_range_wc(subtable, wc, ofs.end);
1653 /* If we have narrowed down to a single rule already, check whether
1654 * that rule matches. Either way, we're done.
1656 * (Rare) hash collisions may cause us to miss the opportunity for this
1658 if (!cmap_node_next(inode)) {
1659 ASSIGN_CONTAINER(rule, inode - i, index_nodes);
1660 if (miniflow_and_mask_matches_flow_wc(&rule->flow, &subtable->mask,
1666 ofs.start = ofs.end;
1668 ofs.end = FLOW_U32S;
1669 /* Trie check for the final range. */
1670 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1671 fill_range_wc(subtable, wc, ofs.start);
1674 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1676 rule = find_match(subtable, flow, hash);
1677 if (!rule && subtable->ports_mask_len) {
1678 /* Ports are always part of the final range, if any.
1679 * No match was found for the ports. Use the ports trie to figure out
1680 * which ports bits to unwildcard. */
1682 ovs_be32 value, mask;
1684 mask = MINIFLOW_GET_BE32(&subtable->mask.masks, tp_src);
1685 value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
1686 trie_lookup_value(&subtable->ports_trie, &value, 32, &mbits);
1688 ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
1689 mask & htonl(~0 << (32 - mbits));
1691 /* Unwildcard all bits in the mask upto the ports, as they were used
1692 * to determine there is no match. */
1693 fill_range_wc(subtable, wc, TP_PORTS_OFS32);
1697 /* Must unwildcard all the fields, as they were looked at. */
1698 flow_wildcards_fold_minimask(wc, &subtable->mask);
1702 static struct cls_match *
1703 find_equal(struct cls_subtable *subtable, const struct miniflow *flow,
1706 struct cls_match *head;
1708 CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1709 if (miniflow_equal(&head->flow, flow)) {
1717 * As the readers are operating concurrently with the modifications, a
1718 * concurrent reader may or may not see the new rule, depending on how
1719 * the concurrent events overlap with each other. This is no
1720 * different from the former locked behavior, but there the visibility
1721 * of the new rule only depended on the timing of the locking
1724 * The new rule is first added to the segment indices, so the readers
1725 * may find the rule in the indices before the rule is visible in the
1726 * subtables 'rules' map. This may result in us losing the
1727 * opportunity to quit lookups earlier, resulting in sub-optimal
1728 * wildcarding. This will be fixed by forthcoming revalidation always
1729 * scheduled after flow table changes.
1731 * Similar behavior may happen due to us removing the overlapping rule
1732 * (if any) from the indices only after the new rule has been added.
1734 * The subtable's max priority is updated only after the rule is
1735 * inserted, so the concurrent readers may not see the rule, as the
1736 * updated priority ordered subtable list will only be visible after
1737 * the subtable's max priority is updated.
1739 * Similarly, the classifier's partitions for new rules are updated by
1740 * the caller after this function, so the readers may keep skipping
1741 * the subtable until they see the updated partitions.
1743 static struct cls_match *
1744 insert_rule(struct cls_classifier *cls, struct cls_subtable *subtable,
1745 struct cls_rule *new_rule)
1746 OVS_REQUIRES(cls->mutex)
1748 struct cls_match *old = NULL;
1749 struct cls_match *new = cls_match_alloc(new_rule);
1750 struct cls_match *head;
1752 uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
1753 uint8_t prev_be32ofs = 0;
1755 /* Add new node to segment indices. */
1756 for (i = 0; i < subtable->n_indices; i++) {
1757 ihash[i] = minimatch_hash_range(&new_rule->match, prev_be32ofs,
1758 subtable->index_ofs[i], &basis);
1759 cmap_insert(&subtable->indices[i], &new->index_nodes[i], ihash[i]);
1760 prev_be32ofs = subtable->index_ofs[i];
1762 hash = minimatch_hash_range(&new_rule->match, prev_be32ofs, FLOW_U32S,
1764 head = find_equal(subtable, &new_rule->match.flow, hash);
1766 cmap_insert(&subtable->rules, &new->cmap_node, hash);
1767 list_init(&new->list);
1770 /* Scan the list for the insertion point that will keep the list in
1771 * order of decreasing priority. */
1772 struct cls_match *rule;
1774 FOR_EACH_RULE_IN_LIST (rule, head) {
1775 if (new->priority >= rule->priority) {
1777 /* 'new' is the new highest-priority flow in the list. */
1778 cmap_replace(&subtable->rules, &rule->cmap_node,
1779 &new->cmap_node, hash);
1782 if (new->priority == rule->priority) {
1783 list_replace(&new->list, &rule->list);
1786 list_insert(&rule->list, &new->list);
1792 /* Insert 'new' at the end of the list. */
1793 list_push_back(&head->list, &new->list);
1798 subtable->n_rules++;
1800 /* Rule was added, not replaced. Update 'subtable's 'max_priority'
1801 * and 'max_count', if necessary. */
1802 if (subtable->n_rules == 1) {
1803 subtable->max_priority = new->priority;
1804 subtable->max_count = 1;
1805 pvector_insert(&cls->subtables, subtable, new->priority);
1806 } else if (subtable->max_priority == new->priority) {
1807 ++subtable->max_count;
1808 } else if (new->priority > subtable->max_priority) {
1809 subtable->max_priority = new->priority;
1810 subtable->max_count = 1;
1811 pvector_change_priority(&cls->subtables, subtable, new->priority);
1814 /* Remove old node from indices. */
1815 for (i = 0; i < subtable->n_indices; i++) {
1816 cmap_remove(&subtable->indices[i], &old->index_nodes[i], ihash[i]);
1822 static struct cls_match *
1823 next_rule_in_list__(struct cls_match *rule)
1824 OVS_NO_THREAD_SAFETY_ANALYSIS
1826 struct cls_match *next = OBJECT_CONTAINING(rule->list.next, next, list);
1830 static struct cls_match *
1831 next_rule_in_list(struct cls_match *rule)
1833 struct cls_match *next = next_rule_in_list__(rule);
1834 return next->priority < rule->priority ? next : NULL;
1837 /* A longest-prefix match tree. */
1839 uint32_t prefix; /* Prefix bits for this node, MSB first. */
1840 uint8_t n_bits; /* Never zero, except for the root node. */
1841 unsigned int n_rules; /* Number of rules that have this prefix. */
1842 rcu_trie_ptr edges[2]; /* Both NULL if leaf. */
1845 /* Max bits per node. Must fit in struct trie_node's 'prefix'.
1846 * Also tested with 16, 8, and 5 to stress the implementation. */
1847 #define TRIE_PREFIX_BITS 32
1849 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1850 * Prefixes are in the network byte order, and the offset 0 corresponds to
1851 * the most significant bit of the first byte. The offset can be read as
1852 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1854 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1858 pr += ofs / 32; /* Where to start. */
1859 ofs %= 32; /* How many bits to skip at 'pr'. */
1861 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1862 if (plen > 32 - ofs) { /* Need more than we have already? */
1863 prefix |= ntohl(*++pr) >> (32 - ofs);
1865 /* Return with possible unwanted bits at the end. */
1869 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1870 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1871 * corresponds to the most significant bit of the first byte. The offset can
1872 * be read as "how many bits to skip from the start of the prefix starting at
1875 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1880 if (plen > TRIE_PREFIX_BITS) {
1881 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1883 /* Return with unwanted bits cleared. */
1884 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1887 /* Return the number of equal bits in 'n_bits' of 'prefix's MSBs and a 'value'
1888 * starting at "MSB 0"-based offset 'ofs'. */
1890 prefix_equal_bits(uint32_t prefix, unsigned int n_bits, const ovs_be32 value[],
1893 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, n_bits);
1894 /* Set the bit after the relevant bits to limit the result. */
1895 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - n_bits));
1898 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1899 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1901 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1902 unsigned int ofs, unsigned int plen)
1904 return prefix_equal_bits(node->prefix, MIN(node->n_bits, plen - ofs),
1908 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1909 * be greater than 31. */
1911 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1913 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1916 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1917 * be between 0 and 31, inclusive. */
1919 get_bit_at(const uint32_t prefix, unsigned int ofs)
1921 return (prefix >> (31 - ofs)) & 1u;
1924 /* Create new branch. */
1925 static struct trie_node *
1926 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1927 unsigned int n_rules)
1929 struct trie_node *node = xmalloc(sizeof *node);
1931 node->prefix = trie_get_prefix(prefix, ofs, plen);
1933 if (plen <= TRIE_PREFIX_BITS) {
1934 node->n_bits = plen;
1935 ovsrcu_set_hidden(&node->edges[0], NULL);
1936 ovsrcu_set_hidden(&node->edges[1], NULL);
1937 node->n_rules = n_rules;
1938 } else { /* Need intermediate nodes. */
1939 struct trie_node *subnode = trie_branch_create(prefix,
1940 ofs + TRIE_PREFIX_BITS,
1941 plen - TRIE_PREFIX_BITS,
1943 int bit = get_bit_at(subnode->prefix, 0);
1944 node->n_bits = TRIE_PREFIX_BITS;
1945 ovsrcu_set_hidden(&node->edges[bit], subnode);
1946 ovsrcu_set_hidden(&node->edges[!bit], NULL);
1953 trie_node_destroy(const struct trie_node *node)
1955 ovsrcu_postpone(free, CONST_CAST(struct trie_node *, node));
1958 /* Copy a trie node for modification and postpone delete the old one. */
1959 static struct trie_node *
1960 trie_node_rcu_realloc(const struct trie_node *node)
1962 struct trie_node *new_node = xmalloc(sizeof *node);
1965 trie_node_destroy(node);
1970 /* May only be called while holding the cls_classifier mutex. */
1972 trie_destroy(rcu_trie_ptr *trie)
1974 struct trie_node *node = ovsrcu_get_protected(struct trie_node *, trie);
1977 ovsrcu_set_hidden(trie, NULL);
1978 trie_destroy(&node->edges[0]);
1979 trie_destroy(&node->edges[1]);
1980 trie_node_destroy(node);
1985 trie_is_leaf(const struct trie_node *trie)
1988 return !ovsrcu_get(struct trie_node *, &trie->edges[0])
1989 && !ovsrcu_get(struct trie_node *, &trie->edges[1]);
1993 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1994 unsigned int n_bits)
1996 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1999 for (i = 0; i < n_bits / 32; i++) {
2000 mask[i] = OVS_BE32_MAX;
2003 mask[i] |= htonl(~0u << (32 - n_bits % 32));
2008 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
2009 unsigned int n_bits)
2011 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
2013 ovs_be32 zeroes = 0;
2015 for (i = 0; i < n_bits / 32; i++) {
2019 zeroes |= ~mask[i] & htonl(~0u << (32 - n_bits % 32));
2022 return !zeroes; /* All 'n_bits' bits set. */
2025 static rcu_trie_ptr *
2026 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
2029 return node->edges + be_get_bit_at(value, ofs);
2032 static const struct trie_node *
2033 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
2036 return ovsrcu_get(struct trie_node *,
2037 &node->edges[be_get_bit_at(value, ofs)]);
2040 /* Return the prefix mask length necessary to find the longest-prefix match for
2041 * the '*value' in the prefix tree 'node'.
2042 * '*checkbits' is set to the number of bits in the prefix mask necessary to
2043 * determine a mismatch, in case there are longer prefixes in the tree below
2044 * the one that matched.
2047 trie_lookup_value(const rcu_trie_ptr *trie, const ovs_be32 value[],
2048 unsigned int n_bits, unsigned int *checkbits)
2050 const struct trie_node *node = ovsrcu_get(struct trie_node *, trie);
2051 unsigned int ofs = 0, match_len = 0;
2052 const struct trie_node *prev = NULL;
2054 for (; node; prev = node, node = trie_next_node(node, value, ofs)) {
2055 unsigned int eqbits;
2056 /* Check if this edge can be followed. */
2057 eqbits = prefix_equal_bits(node->prefix, node->n_bits, value, ofs);
2059 if (eqbits < node->n_bits) { /* Mismatch, nothing more to be found. */
2060 /* Bit at offset 'ofs' differed. */
2061 *checkbits = ofs + 1; /* Includes the first mismatching bit. */
2064 /* Full match, check if rules exist at this prefix length. */
2065 if (node->n_rules > 0) {
2068 if (ofs >= n_bits) {
2069 *checkbits = n_bits; /* Full prefix. */
2073 /* node == NULL. Full match so far, but we came to a dead end.
2074 * need to exclude the other branch if it exists. */
2075 *checkbits = !prev || trie_is_leaf(prev) ? ofs : ofs + 1;
2080 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
2081 unsigned int *checkbits)
2083 const struct mf_field *mf = trie->field;
2085 /* Check that current flow matches the prerequisites for the trie
2086 * field. Some match fields are used for multiple purposes, so we
2087 * must check that the trie is relevant for this flow. */
2088 if (mf_are_prereqs_ok(mf, flow)) {
2089 return trie_lookup_value(&trie->root,
2090 &((ovs_be32 *)flow)[mf->flow_be32ofs],
2091 mf->n_bits, checkbits);
2093 *checkbits = 0; /* Value not used in this case. */
2097 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
2098 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
2099 * 'miniflow_index' is not NULL. */
2101 minimask_get_prefix_len(const struct minimask *minimask,
2102 const struct mf_field *mf)
2104 unsigned int n_bits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
2105 uint8_t u32_ofs = mf->flow_be32ofs;
2106 uint8_t u32_end = u32_ofs + mf->n_bytes / 4;
2108 for (; u32_ofs < u32_end; ++u32_ofs) {
2110 mask = ntohl((OVS_FORCE ovs_be32)minimask_get(minimask, u32_ofs));
2112 /* Validate mask, count the mask length. */
2115 return 0; /* No bits allowed after mask ended. */
2118 if (~mask & (~mask + 1)) {
2119 return 0; /* Mask not contiguous. */
2121 mask_tz = ctz32(mask);
2122 n_bits += 32 - mask_tz;
2130 * This is called only when mask prefix is known to be CIDR and non-zero.
2131 * Relies on the fact that the flow and mask have the same map, and since
2132 * the mask is CIDR, the storage for the flow field exists even if it
2133 * happened to be zeros.
2135 static const ovs_be32 *
2136 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
2138 return miniflow_get_be32_values(&match->flow) +
2139 count_1bits(match->flow.map & ((UINT64_C(1) << mf->flow_be32ofs) - 1));
2142 /* Insert rule in to the prefix tree.
2143 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2146 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2148 trie_insert_prefix(&trie->root,
2149 minimatch_get_prefix(&rule->match, trie->field), mlen);
2153 trie_insert_prefix(rcu_trie_ptr *edge, const ovs_be32 *prefix, int mlen)
2155 struct trie_node *node;
2158 /* Walk the tree. */
2159 for (; (node = ovsrcu_get_protected(struct trie_node *, edge));
2160 edge = trie_next_edge(node, prefix, ofs)) {
2161 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2163 if (eqbits < node->n_bits) {
2164 /* Mismatch, new node needs to be inserted above. */
2165 int old_branch = get_bit_at(node->prefix, eqbits);
2166 struct trie_node *new_parent;
2168 new_parent = trie_branch_create(prefix, ofs - eqbits, eqbits,
2169 ofs == mlen ? 1 : 0);
2170 /* Copy the node to modify it. */
2171 node = trie_node_rcu_realloc(node);
2172 /* Adjust the new node for its new position in the tree. */
2173 node->prefix <<= eqbits;
2174 node->n_bits -= eqbits;
2175 ovsrcu_set_hidden(&new_parent->edges[old_branch], node);
2177 /* Check if need a new branch for the new rule. */
2179 ovsrcu_set_hidden(&new_parent->edges[!old_branch],
2180 trie_branch_create(prefix, ofs, mlen - ofs,
2183 ovsrcu_set(edge, new_parent); /* Publish changes. */
2186 /* Full match so far. */
2189 /* Full match at the current node, rule needs to be added here. */
2194 /* Must insert a new tree branch for the new rule. */
2195 ovsrcu_set(edge, trie_branch_create(prefix, ofs, mlen - ofs, 1));
2198 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2201 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2203 trie_remove_prefix(&trie->root,
2204 minimatch_get_prefix(&rule->match, trie->field), mlen);
2207 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2210 trie_remove_prefix(rcu_trie_ptr *root, const ovs_be32 *prefix, int mlen)
2212 struct trie_node *node;
2213 rcu_trie_ptr *edges[sizeof(union mf_value) * 8];
2214 int depth = 0, ofs = 0;
2216 /* Walk the tree. */
2217 for (edges[0] = root;
2218 (node = ovsrcu_get_protected(struct trie_node *, edges[depth]));
2219 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
2220 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2222 if (eqbits < node->n_bits) {
2223 /* Mismatch, nothing to be removed. This should never happen, as
2224 * only rules in the classifier are ever removed. */
2225 break; /* Log a warning. */
2227 /* Full match so far. */
2231 /* Full prefix match at the current node, remove rule here. */
2232 if (!node->n_rules) {
2233 break; /* Log a warning. */
2237 /* Check if can prune the tree. */
2238 while (!node->n_rules) {
2239 struct trie_node *next,
2240 *edge0 = ovsrcu_get_protected(struct trie_node *,
2242 *edge1 = ovsrcu_get_protected(struct trie_node *,
2245 if (edge0 && edge1) {
2246 break; /* A branching point, cannot prune. */
2249 /* Else have at most one child node, remove this node. */
2250 next = edge0 ? edge0 : edge1;
2253 if (node->n_bits + next->n_bits > TRIE_PREFIX_BITS) {
2254 break; /* Cannot combine. */
2256 next = trie_node_rcu_realloc(next); /* Modify. */
2258 /* Combine node with next. */
2259 next->prefix = node->prefix | next->prefix >> node->n_bits;
2260 next->n_bits += node->n_bits;
2262 /* Update the parent's edge. */
2263 ovsrcu_set(edges[depth], next); /* Publish changes. */
2264 trie_node_destroy(node);
2266 if (next || !depth) {
2267 /* Branch not pruned or at root, nothing more to do. */
2270 node = ovsrcu_get_protected(struct trie_node *,
2276 /* Cannot go deeper. This should never happen, since only rules
2277 * that actually exist in the classifier are ever removed. */
2278 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");