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);
36 /* Ports trie depends on both ports sharing the same ovs_be32. */
37 #define TP_PORTS_OFS32 (offsetof(struct flow, tp_src) / 4)
38 BUILD_ASSERT_DECL(TP_PORTS_OFS32 == offsetof(struct flow, tp_dst) / 4);
40 /* Prefix trie for a 'field' */
42 const struct mf_field *field; /* Trie field, or NULL. */
43 struct trie_node *root; /* NULL if none. */
46 struct cls_subtable_entry {
47 struct cls_subtable *subtable;
49 unsigned int max_priority;
52 struct cls_subtable_cache {
53 struct cls_subtable_entry *subtables;
54 size_t alloc_size; /* Number of allocated elements. */
55 size_t size; /* One past last valid array element. */
59 CLS_MAX_INDICES = 3 /* Maximum number of lookup indices per subtable. */
62 struct cls_classifier {
63 int n_rules; /* Total number of rules. */
64 uint8_t n_flow_segments;
65 uint8_t flow_segments[CLS_MAX_INDICES]; /* Flow segment boundaries to use
66 * for staged lookup. */
67 struct hmap subtables; /* Contains "struct cls_subtable"s. */
68 struct cls_subtable_cache subtables_priority;
69 struct hmap partitions; /* Contains "struct cls_partition"s. */
70 struct cls_trie tries[CLS_MAX_TRIES]; /* Prefix tries. */
74 /* A set of rules that all have the same fields wildcarded. */
76 struct hmap_node hmap_node; /* Within struct cls_classifier 'subtables'
78 struct hmap rules; /* Contains "struct cls_rule"s. */
79 int n_rules; /* Number of rules, including duplicates. */
80 unsigned int max_priority; /* Max priority of any rule in the subtable. */
81 unsigned int max_count; /* Count of max_priority rules. */
82 tag_type tag; /* Tag generated from mask for partitioning. */
83 uint8_t n_indices; /* How many indices to use. */
84 uint8_t index_ofs[CLS_MAX_INDICES]; /* u32 flow segment boundaries. */
85 struct hindex indices[CLS_MAX_INDICES]; /* Staged lookup indices. */
86 unsigned int trie_plen[CLS_MAX_TRIES]; /* Trie prefix length in 'mask'. */
88 struct trie_node *ports_trie; /* NULL if none. */
89 struct minimask mask; /* Wildcards for fields. */
90 /* 'mask' must be the last field. */
93 /* Associates a metadata value (that is, a value of the OpenFlow 1.1+ metadata
94 * field) with tags for the "cls_subtable"s that contain rules that match that
96 struct cls_partition {
97 struct hmap_node hmap_node; /* In struct cls_classifier's 'partitions'
99 ovs_be64 metadata; /* metadata value for this partition. */
100 tag_type tags; /* OR of each flow's cls_subtable tag. */
101 struct tag_tracker tracker; /* Tracks the bits in 'tags'. */
104 /* Internal representation of a rule in a "struct cls_subtable". */
106 struct cls_rule *cls_rule;
107 struct hindex_node index_nodes[CLS_MAX_INDICES]; /* Within subtable's
109 struct hmap_node hmap_node; /* Within struct cls_subtable 'rules'. */
110 unsigned int priority; /* Larger numbers are higher priorities. */
111 struct cls_partition *partition;
112 struct list list; /* List of identical, lower-priority rules. */
113 struct miniflow flow; /* Matching rule. Mask is in the subtable. */
114 /* 'flow' must be the last field. */
117 static struct cls_match *
118 cls_match_alloc(struct cls_rule *rule)
120 int count = count_1bits(rule->match.flow.map);
122 struct cls_match *cls_match
123 = xmalloc(sizeof *cls_match - sizeof cls_match->flow.inline_values
124 + MINIFLOW_VALUES_SIZE(count));
126 cls_match->cls_rule = rule;
127 miniflow_clone_inline(&cls_match->flow, &rule->match.flow, count);
128 cls_match->priority = rule->priority;
129 rule->cls_match = cls_match;
134 static struct cls_subtable *find_subtable(const struct cls_classifier *,
135 const struct minimask *);
136 static struct cls_subtable *insert_subtable(struct cls_classifier *,
137 const struct minimask *);
139 static void destroy_subtable(struct cls_classifier *, struct cls_subtable *);
141 static void update_subtables_after_insertion(struct cls_classifier *,
142 struct cls_subtable *,
143 unsigned int new_priority);
144 static void update_subtables_after_removal(struct cls_classifier *,
145 struct cls_subtable *,
146 unsigned int del_priority);
148 static struct cls_match *find_match_wc(const struct cls_subtable *,
149 const struct flow *, struct trie_ctx *,
150 unsigned int n_tries,
151 struct flow_wildcards *);
152 static struct cls_match *find_equal(struct cls_subtable *,
153 const struct miniflow *, uint32_t hash);
154 static struct cls_match *insert_rule(struct cls_classifier *,
155 struct cls_subtable *, struct cls_rule *);
157 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list. */
158 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD) \
159 for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
160 #define FOR_EACH_RULE_IN_LIST_SAFE(RULE, NEXT, HEAD) \
161 for ((RULE) = (HEAD); \
162 (RULE) != NULL && ((NEXT) = next_rule_in_list(RULE), true); \
165 static struct cls_match *next_rule_in_list__(struct cls_match *);
166 static struct cls_match *next_rule_in_list(struct cls_match *);
168 static unsigned int minimask_get_prefix_len(const struct minimask *,
169 const struct mf_field *);
170 static void trie_init(struct cls_classifier *, int trie_idx,
171 const struct mf_field *);
172 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
173 unsigned int *checkbits);
174 static unsigned int trie_lookup_value(const struct trie_node *,
175 const ovs_be32 value[],
176 unsigned int value_bits,
177 unsigned int *checkbits);
178 static void trie_destroy(struct trie_node *);
179 static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
180 static void trie_insert_prefix(struct trie_node **, const ovs_be32 *prefix,
182 static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
183 static void trie_remove_prefix(struct trie_node **, const ovs_be32 *prefix,
185 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
187 static bool mask_prefix_bits_set(const struct flow_wildcards *,
188 uint8_t be32ofs, unsigned int nbits);
191 cls_subtable_cache_init(struct cls_subtable_cache *array)
193 memset(array, 0, sizeof *array);
197 cls_subtable_cache_destroy(struct cls_subtable_cache *array)
199 free(array->subtables);
200 memset(array, 0, sizeof *array);
203 /* Array insertion. */
205 cls_subtable_cache_push_back(struct cls_subtable_cache *array,
206 struct cls_subtable_entry a)
208 if (array->size == array->alloc_size) {
209 array->subtables = x2nrealloc(array->subtables, &array->alloc_size,
213 array->subtables[array->size++] = a;
216 /* Move subtable entry at 'from' to 'to', shifting the elements in between
217 * (including the one at 'to') accordingly. */
219 cls_subtable_cache_move(struct cls_subtable_entry *to,
220 struct cls_subtable_entry *from)
223 struct cls_subtable_entry temp = *from;
226 /* Shift entries (from,to] backwards to make space at 'to'. */
227 memmove(from, from + 1, (to - from) * sizeof *to);
229 /* Shift entries [to,from) forward to make space at 'to'. */
230 memmove(to + 1, to, (from - to) * sizeof *to);
239 cls_subtable_cache_remove(struct cls_subtable_cache *array,
240 struct cls_subtable_entry *elem)
242 ssize_t size = (&array->subtables[array->size]
243 - (elem + 1)) * sizeof *elem;
245 memmove(elem, elem + 1, size);
250 #define CLS_SUBTABLE_CACHE_FOR_EACH(SUBTABLE, ITER, ARRAY) \
251 for (ITER = (ARRAY)->subtables; \
252 ITER < &(ARRAY)->subtables[(ARRAY)->size] \
253 && OVS_LIKELY(SUBTABLE = ITER->subtable); \
255 #define CLS_SUBTABLE_CACHE_FOR_EACH_CONTINUE(SUBTABLE, ITER, ARRAY) \
257 ITER < &(ARRAY)->subtables[(ARRAY)->size] \
258 && OVS_LIKELY(SUBTABLE = ITER->subtable); \
260 #define CLS_SUBTABLE_CACHE_FOR_EACH_REVERSE(SUBTABLE, ITER, ARRAY) \
261 for (ITER = &(ARRAY)->subtables[(ARRAY)->size]; \
262 ITER > (ARRAY)->subtables \
263 && OVS_LIKELY(SUBTABLE = (--ITER)->subtable);)
266 cls_subtable_cache_verify(struct cls_subtable_cache *array)
268 struct cls_subtable *table;
269 struct cls_subtable_entry *iter;
270 unsigned int priority = 0;
272 CLS_SUBTABLE_CACHE_FOR_EACH_REVERSE (table, iter, array) {
273 if (iter->max_priority != table->max_priority) {
274 VLOG_WARN("Subtable %p has mismatching priority in cache (%u != %u)",
275 table, iter->max_priority, table->max_priority);
277 if (iter->max_priority < priority) {
278 VLOG_WARN("Subtable cache is out of order (%u < %u)",
279 iter->max_priority, priority);
281 priority = iter->max_priority;
286 cls_subtable_cache_reset(struct cls_classifier *cls)
288 struct cls_subtable_cache old = cls->subtables_priority;
289 struct cls_subtable *subtable;
291 VLOG_WARN("Resetting subtable cache.");
293 cls_subtable_cache_verify(&cls->subtables_priority);
295 cls_subtable_cache_init(&cls->subtables_priority);
297 HMAP_FOR_EACH (subtable, hmap_node, &cls->subtables) {
298 struct cls_match *head;
299 struct cls_subtable_entry elem;
300 struct cls_subtable *table;
301 struct cls_subtable_entry *iter, *from = NULL;
302 unsigned int new_max = 0;
303 unsigned int max_count = 0;
306 /* Verify max_priority. */
307 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
308 if (head->priority > new_max) {
309 new_max = head->priority;
311 } else if (head->priority == new_max) {
315 if (new_max != subtable->max_priority ||
316 max_count != subtable->max_count) {
317 VLOG_WARN("subtable %p (%u rules) has mismatching max_priority "
318 "(%u) or max_count (%u). Highest priority found was %u, "
320 subtable, subtable->n_rules, subtable->max_priority,
321 subtable->max_count, new_max, max_count);
322 subtable->max_priority = new_max;
323 subtable->max_count = max_count;
326 /* Locate the subtable from the old cache. */
328 CLS_SUBTABLE_CACHE_FOR_EACH (table, iter, &old) {
329 if (table == subtable) {
330 if (iter->max_priority != new_max) {
331 VLOG_WARN("Subtable %p has wrong max priority (%u != %u) "
333 subtable, iter->max_priority, new_max);
336 VLOG_WARN("Subtable %p duplicated in the old cache.",
343 VLOG_WARN("Subtable %p not found from the old cache.", subtable);
346 elem.subtable = subtable;
347 elem.tag = subtable->tag;
348 elem.max_priority = subtable->max_priority;
349 cls_subtable_cache_push_back(&cls->subtables_priority, elem);
351 /* Possibly move 'subtable' earlier in the priority array. If
352 * we break out of the loop, then the subtable (at 'from')
353 * should be moved to the position right after the current
354 * element. If the loop terminates normally, then 'iter' will
355 * be at the first array element and we'll move the subtable
356 * to the front of the array. */
357 CLS_SUBTABLE_CACHE_FOR_EACH_REVERSE (table, iter,
358 &cls->subtables_priority) {
359 if (table == subtable) {
360 from = iter; /* Locate the subtable as we go. */
361 } else if (table->max_priority >= new_max) {
362 ovs_assert(from != NULL);
363 iter++; /* After this. */
368 /* Move subtable at 'from' to 'iter'. */
369 cls_subtable_cache_move(iter, from);
372 /* Verify that the old and the new have the same size. */
373 if (old.size != cls->subtables_priority.size) {
374 VLOG_WARN("subtables cache sizes differ: old (%"PRIuSIZE
375 ") != new (%"PRIuSIZE").",
376 old.size, cls->subtables_priority.size);
379 cls_subtable_cache_destroy(&old);
381 cls_subtable_cache_verify(&cls->subtables_priority);
385 /* flow/miniflow/minimask/minimatch utilities.
386 * These are only used by the classifier, so place them here to allow
387 * for better optimization. */
389 static inline uint64_t
390 miniflow_get_map_in_range(const struct miniflow *miniflow,
391 uint8_t start, uint8_t end, unsigned int *offset)
393 uint64_t map = miniflow->map;
397 uint64_t msk = (UINT64_C(1) << start) - 1; /* 'start' LSBs set */
398 *offset = count_1bits(map & msk);
401 if (end < FLOW_U32S) {
402 uint64_t msk = (UINT64_C(1) << end) - 1; /* 'end' LSBs set */
408 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
409 * 'mask', given 'basis'.
411 * The hash values returned by this function are the same as those returned by
412 * miniflow_hash_in_minimask(), only the form of the arguments differ. */
413 static inline uint32_t
414 flow_hash_in_minimask(const struct flow *flow, const struct minimask *mask,
417 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
418 const uint32_t *flow_u32 = (const uint32_t *)flow;
419 const uint32_t *p = mask_values;
424 for (map = mask->masks.map; map; map = zero_rightmost_1bit(map)) {
425 hash = mhash_add(hash, flow_u32[raw_ctz(map)] & *p++);
428 return mhash_finish(hash, (p - mask_values) * 4);
431 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
432 * 'mask', given 'basis'.
434 * The hash values returned by this function are the same as those returned by
435 * flow_hash_in_minimask(), only the form of the arguments differ. */
436 static inline uint32_t
437 miniflow_hash_in_minimask(const struct miniflow *flow,
438 const struct minimask *mask, uint32_t basis)
440 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
441 const uint32_t *p = mask_values;
442 uint32_t hash = basis;
445 MINIFLOW_FOR_EACH_IN_MAP(flow_u32, flow, mask->masks.map) {
446 hash = mhash_add(hash, flow_u32 & *p++);
449 return mhash_finish(hash, (p - mask_values) * 4);
452 /* Returns a hash value for the bits of range [start, end) in 'flow',
453 * where there are 1-bits in 'mask', given 'hash'.
455 * The hash values returned by this function are the same as those returned by
456 * minimatch_hash_range(), only the form of the arguments differ. */
457 static inline uint32_t
458 flow_hash_in_minimask_range(const struct flow *flow,
459 const struct minimask *mask,
460 uint8_t start, uint8_t end, uint32_t *basis)
462 const uint32_t *mask_values = miniflow_get_u32_values(&mask->masks);
463 const uint32_t *flow_u32 = (const uint32_t *)flow;
465 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
467 const uint32_t *p = mask_values + offset;
468 uint32_t hash = *basis;
470 for (; map; map = zero_rightmost_1bit(map)) {
471 hash = mhash_add(hash, flow_u32[raw_ctz(map)] & *p++);
474 *basis = hash; /* Allow continuation from the unfinished value. */
475 return mhash_finish(hash, (p - mask_values) * 4);
478 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask. */
480 flow_wildcards_fold_minimask(struct flow_wildcards *wc,
481 const struct minimask *mask)
483 flow_union_with_miniflow(&wc->masks, &mask->masks);
486 /* Fold minimask 'mask''s wildcard mask into 'wc's wildcard mask
487 * in range [start, end). */
489 flow_wildcards_fold_minimask_range(struct flow_wildcards *wc,
490 const struct minimask *mask,
491 uint8_t start, uint8_t end)
493 uint32_t *dst_u32 = (uint32_t *)&wc->masks;
495 uint64_t map = miniflow_get_map_in_range(&mask->masks, start, end,
497 const uint32_t *p = miniflow_get_u32_values(&mask->masks) + offset;
499 for (; map; map = zero_rightmost_1bit(map)) {
500 dst_u32[raw_ctz(map)] |= *p++;
504 /* Returns a hash value for 'flow', given 'basis'. */
505 static inline uint32_t
506 miniflow_hash(const struct miniflow *flow, uint32_t basis)
508 const uint32_t *values = miniflow_get_u32_values(flow);
509 const uint32_t *p = values;
510 uint32_t hash = basis;
511 uint64_t hash_map = 0;
514 for (map = flow->map; map; map = zero_rightmost_1bit(map)) {
516 hash = mhash_add(hash, *p);
517 hash_map |= rightmost_1bit(map);
521 hash = mhash_add(hash, hash_map);
522 hash = mhash_add(hash, hash_map >> 32);
524 return mhash_finish(hash, p - values);
527 /* Returns a hash value for 'mask', given 'basis'. */
528 static inline uint32_t
529 minimask_hash(const struct minimask *mask, uint32_t basis)
531 return miniflow_hash(&mask->masks, basis);
534 /* Returns a hash value for 'match', given 'basis'. */
535 static inline uint32_t
536 minimatch_hash(const struct minimatch *match, uint32_t basis)
538 return miniflow_hash(&match->flow, minimask_hash(&match->mask, basis));
541 /* Returns a hash value for the bits of range [start, end) in 'minimatch',
544 * The hash values returned by this function are the same as those returned by
545 * flow_hash_in_minimask_range(), only the form of the arguments differ. */
546 static inline uint32_t
547 minimatch_hash_range(const struct minimatch *match, uint8_t start, uint8_t end,
551 const uint32_t *p, *q;
552 uint32_t hash = *basis;
555 n = count_1bits(miniflow_get_map_in_range(&match->mask.masks, start, end,
557 q = miniflow_get_u32_values(&match->mask.masks) + offset;
558 p = miniflow_get_u32_values(&match->flow) + offset;
560 for (i = 0; i < n; i++) {
561 hash = mhash_add(hash, p[i] & q[i]);
563 *basis = hash; /* Allow continuation from the unfinished value. */
564 return mhash_finish(hash, (offset + n) * 4);
570 /* Initializes 'rule' to match packets specified by 'match' at the given
571 * 'priority'. 'match' must satisfy the invariant described in the comment at
572 * the definition of struct match.
574 * The caller must eventually destroy 'rule' with cls_rule_destroy().
576 * (OpenFlow uses priorities between 0 and UINT16_MAX, inclusive, but
577 * internally Open vSwitch supports a wider range.) */
579 cls_rule_init(struct cls_rule *rule,
580 const struct match *match, unsigned int priority)
582 minimatch_init(&rule->match, match);
583 rule->priority = priority;
584 rule->cls_match = NULL;
587 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
589 cls_rule_init_from_minimatch(struct cls_rule *rule,
590 const struct minimatch *match,
591 unsigned int priority)
593 minimatch_clone(&rule->match, match);
594 rule->priority = priority;
595 rule->cls_match = NULL;
598 /* Initializes 'dst' as a copy of 'src'.
600 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
602 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
604 minimatch_clone(&dst->match, &src->match);
605 dst->priority = src->priority;
606 dst->cls_match = NULL;
609 /* Initializes 'dst' with the data in 'src', destroying 'src'.
611 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
613 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
615 minimatch_move(&dst->match, &src->match);
616 dst->priority = src->priority;
617 dst->cls_match = NULL;
620 /* Frees memory referenced by 'rule'. Doesn't free 'rule' itself (it's
621 * normally embedded into a larger structure).
623 * ('rule' must not currently be in a classifier.) */
625 cls_rule_destroy(struct cls_rule *rule)
627 ovs_assert(!rule->cls_match);
628 minimatch_destroy(&rule->match);
631 /* Returns true if 'a' and 'b' match the same packets at the same priority,
632 * false if they differ in some way. */
634 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
636 return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
639 /* Returns a hash value for 'rule', folding in 'basis'. */
641 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
643 return minimatch_hash(&rule->match, hash_int(rule->priority, basis));
646 /* Appends a string describing 'rule' to 's'. */
648 cls_rule_format(const struct cls_rule *rule, struct ds *s)
650 minimatch_format(&rule->match, s, rule->priority);
653 /* Returns true if 'rule' matches every packet, false otherwise. */
655 cls_rule_is_catchall(const struct cls_rule *rule)
657 return minimask_is_catchall(&rule->match.mask);
660 /* Initializes 'cls' as a classifier that initially contains no classification
663 classifier_init(struct classifier *cls_, const uint8_t *flow_segments)
665 struct cls_classifier *cls = xmalloc(sizeof *cls);
667 fat_rwlock_init(&cls_->rwlock);
672 hmap_init(&cls->subtables);
673 cls_subtable_cache_init(&cls->subtables_priority);
674 hmap_init(&cls->partitions);
675 cls->n_flow_segments = 0;
677 while (cls->n_flow_segments < CLS_MAX_INDICES
678 && *flow_segments < FLOW_U32S) {
679 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
685 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
686 * caller's responsibility. */
688 classifier_destroy(struct classifier *cls_)
691 struct cls_classifier *cls = cls_->cls;
692 struct cls_subtable *partition, *next_partition;
693 struct cls_subtable *subtable, *next_subtable;
696 fat_rwlock_destroy(&cls_->rwlock);
701 for (i = 0; i < cls->n_tries; i++) {
702 trie_destroy(cls->tries[i].root);
705 HMAP_FOR_EACH_SAFE (subtable, next_subtable, hmap_node,
707 destroy_subtable(cls, subtable);
709 hmap_destroy(&cls->subtables);
711 HMAP_FOR_EACH_SAFE (partition, next_partition, hmap_node,
713 hmap_remove(&cls->partitions, &partition->hmap_node);
716 hmap_destroy(&cls->partitions);
718 cls_subtable_cache_destroy(&cls->subtables_priority);
723 /* We use uint64_t as a set for the fields below. */
724 BUILD_ASSERT_DECL(MFF_N_IDS <= 64);
726 /* Set the fields for which prefix lookup should be performed. */
728 classifier_set_prefix_fields(struct classifier *cls_,
729 const enum mf_field_id *trie_fields,
730 unsigned int n_fields)
732 struct cls_classifier *cls = cls_->cls;
736 for (i = 0, trie = 0; i < n_fields && trie < CLS_MAX_TRIES; i++) {
737 const struct mf_field *field = mf_from_id(trie_fields[i]);
738 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
739 /* Incompatible field. This is the only place where we
740 * enforce these requirements, but the rest of the trie code
741 * depends on the flow_be32ofs to be non-negative and the
742 * field length to be a multiple of 32 bits. */
746 if (fields & (UINT64_C(1) << trie_fields[i])) {
747 /* Duplicate field, there is no need to build more than
748 * one index for any one field. */
751 fields |= UINT64_C(1) << trie_fields[i];
753 if (trie >= cls->n_tries || field != cls->tries[trie].field) {
754 trie_init(cls, trie, field);
759 /* Destroy the rest. */
760 for (i = trie; i < cls->n_tries; i++) {
761 trie_init(cls, i, NULL);
767 trie_init(struct cls_classifier *cls, int trie_idx,
768 const struct mf_field *field)
770 struct cls_trie *trie = &cls->tries[trie_idx];
771 struct cls_subtable *subtable;
772 struct cls_subtable_entry *iter;
774 if (trie_idx < cls->n_tries) {
775 trie_destroy(trie->root);
780 /* Add existing rules to the trie. */
781 CLS_SUBTABLE_CACHE_FOR_EACH (subtable, iter, &cls->subtables_priority) {
784 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
785 /* Initialize subtable's prefix length on this field. */
786 subtable->trie_plen[trie_idx] = plen;
789 struct cls_match *head;
791 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
792 struct cls_match *match;
794 FOR_EACH_RULE_IN_LIST (match, head) {
795 trie_insert(trie, match->cls_rule, plen);
802 /* Returns true if 'cls' contains no classification rules, false otherwise. */
804 classifier_is_empty(const struct classifier *cls)
806 return cls->cls->n_rules == 0;
809 /* Returns the number of rules in 'cls'. */
811 classifier_count(const struct classifier *cls)
813 return cls->cls->n_rules;
817 hash_metadata(ovs_be64 metadata_)
819 uint64_t metadata = (OVS_FORCE uint64_t) metadata_;
820 return hash_uint64(metadata);
823 static struct cls_partition *
824 find_partition(const struct cls_classifier *cls, ovs_be64 metadata,
827 struct cls_partition *partition;
829 HMAP_FOR_EACH_IN_BUCKET (partition, hmap_node, hash, &cls->partitions) {
830 if (partition->metadata == metadata) {
838 static struct cls_partition *
839 create_partition(struct cls_classifier *cls, struct cls_subtable *subtable,
842 uint32_t hash = hash_metadata(metadata);
843 struct cls_partition *partition = find_partition(cls, metadata, hash);
845 partition = xmalloc(sizeof *partition);
846 partition->metadata = metadata;
848 tag_tracker_init(&partition->tracker);
849 hmap_insert(&cls->partitions, &partition->hmap_node, hash);
851 tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
855 static inline ovs_be32 minimatch_get_ports(const struct minimatch *match)
857 /* Could optimize to use the same map if needed for fast path. */
858 return MINIFLOW_GET_BE32(&match->flow, tp_src)
859 & MINIFLOW_GET_BE32(&match->mask.masks, tp_src);
862 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
863 * must not modify or free it.
865 * If 'cls' already contains an identical rule (including wildcards, values of
866 * fixed fields, and priority), replaces the old rule by 'rule' and returns the
867 * rule that was replaced. The caller takes ownership of the returned rule and
868 * is thus responsible for destroying it with cls_rule_destroy(), freeing the
869 * memory block in which it resides, etc., as necessary.
871 * Returns NULL if 'cls' does not contain a rule with an identical key, after
872 * inserting the new rule. In this case, no rules are displaced by the new
873 * rule, even rules that cannot have any effect because the new rule matches a
874 * superset of their flows and has higher priority. */
876 classifier_replace(struct classifier *cls_, struct cls_rule *rule)
878 struct cls_classifier *cls = cls_->cls;
879 struct cls_match *old_rule;
880 struct cls_subtable *subtable;
882 subtable = find_subtable(cls, &rule->match.mask);
884 subtable = insert_subtable(cls, &rule->match.mask);
887 old_rule = insert_rule(cls, subtable, rule);
891 rule->cls_match->partition = NULL;
892 if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
893 ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
894 rule->cls_match->partition = create_partition(cls, subtable,
901 for (i = 0; i < cls->n_tries; i++) {
902 if (subtable->trie_plen[i]) {
903 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
908 if (subtable->ports_mask_len) {
909 /* We mask the value to be inserted to always have the wildcarded
910 * bits in known (zero) state, so we can include them in comparison
911 * and they will always match (== their original value does not
913 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
915 trie_insert_prefix(&subtable->ports_trie, &masked_ports,
916 subtable->ports_mask_len);
921 struct cls_rule *old_cls_rule = old_rule->cls_rule;
923 rule->cls_match->partition = old_rule->partition;
924 old_cls_rule->cls_match = NULL;
930 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
931 * must not modify or free it.
933 * 'cls' must not contain an identical rule (including wildcards, values of
934 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
937 classifier_insert(struct classifier *cls, struct cls_rule *rule)
939 struct cls_rule *displaced_rule = classifier_replace(cls, rule);
940 ovs_assert(!displaced_rule);
943 /* Removes 'rule' from 'cls'. It is the caller's responsibility to destroy
944 * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
945 * resides, etc., as necessary. */
947 classifier_remove(struct classifier *cls_, struct cls_rule *rule)
949 struct cls_classifier *cls = cls_->cls;
950 struct cls_partition *partition;
951 struct cls_match *cls_match = rule->cls_match;
952 struct cls_match *head;
953 struct cls_subtable *subtable;
956 ovs_assert(cls_match);
958 subtable = find_subtable(cls, &rule->match.mask);
959 ovs_assert(subtable);
961 if (subtable->ports_mask_len) {
962 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
964 trie_remove_prefix(&subtable->ports_trie,
965 &masked_ports, subtable->ports_mask_len);
967 for (i = 0; i < cls->n_tries; i++) {
968 if (subtable->trie_plen[i]) {
969 trie_remove(&cls->tries[i], rule, subtable->trie_plen[i]);
973 /* Remove rule node from indices. */
974 for (i = 0; i < subtable->n_indices; i++) {
975 hindex_remove(&subtable->indices[i], &cls_match->index_nodes[i]);
978 head = find_equal(subtable, &rule->match.flow, cls_match->hmap_node.hash);
979 if (head != cls_match) {
980 list_remove(&cls_match->list);
981 } else if (list_is_empty(&cls_match->list)) {
982 hmap_remove(&subtable->rules, &cls_match->hmap_node);
984 struct cls_match *next = CONTAINER_OF(cls_match->list.next,
985 struct cls_match, list);
987 list_remove(&cls_match->list);
988 hmap_replace(&subtable->rules, &cls_match->hmap_node,
992 partition = cls_match->partition;
994 tag_tracker_subtract(&partition->tracker, &partition->tags,
996 if (!partition->tags) {
997 hmap_remove(&cls->partitions, &partition->hmap_node);
1002 if (--subtable->n_rules == 0) {
1003 destroy_subtable(cls, subtable);
1005 update_subtables_after_removal(cls, subtable, cls_match->priority);
1010 rule->cls_match = NULL;
1014 /* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
1015 * subtables which have more than 'match_plen' bits in their corresponding
1016 * field at offset 'be32ofs'. If skipped, 'maskbits' prefix bits should be
1017 * unwildcarded to quarantee datapath flow matches only packets it should. */
1019 const struct cls_trie *trie;
1020 bool lookup_done; /* Status of the lookup. */
1021 uint8_t be32ofs; /* U32 offset of the field in question. */
1022 unsigned int match_plen; /* Longest prefix than could possibly match. */
1023 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
1027 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
1030 ctx->be32ofs = trie->field->flow_be32ofs;
1031 ctx->lookup_done = false;
1035 lookahead_subtable(const struct cls_subtable_entry *subtables)
1037 ovs_prefetch_range(subtables->subtable, sizeof *subtables->subtable);
1040 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
1041 * Returns a null pointer if no rules in 'cls' match 'flow'. If multiple rules
1042 * of equal priority match 'flow', returns one arbitrarily.
1044 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
1045 * set of bits that were significant in the lookup. At some point
1046 * earlier, 'wc' should have been initialized (e.g., by
1047 * flow_wildcards_init_catchall()). */
1049 classifier_lookup(const struct classifier *cls_, const struct flow *flow,
1050 struct flow_wildcards *wc)
1052 struct cls_classifier *cls = cls_->cls;
1053 const struct cls_partition *partition;
1055 struct cls_match *best;
1056 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
1058 struct cls_subtable_entry *subtables = cls->subtables_priority.subtables;
1059 int n_subtables = cls->subtables_priority.size;
1060 int64_t best_priority = -1;
1062 /* Prefetch the subtables array. */
1063 ovs_prefetch_range(subtables, n_subtables * sizeof *subtables);
1065 /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
1066 * then 'flow' cannot possibly match in 'subtable':
1068 * - If flow->metadata maps to a given 'partition', then we can use
1069 * 'tags' for 'partition->tags'.
1071 * - If flow->metadata has no partition, then no rule in 'cls' has an
1072 * exact-match for flow->metadata. That means that we don't need to
1073 * search any subtable that includes flow->metadata in its mask.
1075 * In either case, we always need to search any cls_subtables that do not
1076 * include flow->metadata in its mask. One way to do that would be to
1077 * check the "cls_subtable"s explicitly for that, but that would require an
1078 * extra branch per subtable. Instead, we mark such a cls_subtable's
1079 * 'tags' as TAG_ALL and make sure that 'tags' is never empty. This means
1080 * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
1081 * need a special case.
1083 partition = (hmap_is_empty(&cls->partitions)
1085 : find_partition(cls, flow->metadata,
1086 hash_metadata(flow->metadata)));
1087 tags = partition ? partition->tags : TAG_ARBITRARY;
1089 /* Initialize trie contexts for match_find_wc(). */
1090 for (i = 0; i < cls->n_tries; i++) {
1091 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
1094 /* Prefetch the first subtables. */
1095 if (n_subtables > 1) {
1096 lookahead_subtable(subtables);
1097 lookahead_subtable(subtables + 1);
1101 for (i = 0; OVS_LIKELY(i < n_subtables); i++) {
1102 struct cls_match *rule;
1104 if ((int64_t)subtables[i].max_priority <= best_priority) {
1105 /* Subtables are in descending priority order,
1106 * can not find anything better. */
1110 /* Prefetch a forthcoming subtable. */
1111 if (i + 2 < n_subtables) {
1112 lookahead_subtable(&subtables[i + 2]);
1115 if (!tag_intersects(tags, subtables[i].tag)) {
1119 rule = find_match_wc(subtables[i].subtable, flow, trie_ctx,
1121 if (rule && (int64_t)rule->priority > best_priority) {
1122 best_priority = (int64_t)rule->priority;
1127 return best ? best->cls_rule : NULL;
1130 /* Returns true if 'target' satisifies 'match', that is, if each bit for which
1131 * 'match' specifies a particular value has the correct value in 'target'.
1133 * 'flow' and 'mask' have the same mask! */
1135 miniflow_and_mask_matches_miniflow(const struct miniflow *flow,
1136 const struct minimask *mask,
1137 const struct miniflow *target)
1139 const uint32_t *flowp = miniflow_get_u32_values(flow);
1140 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1141 uint32_t target_u32;
1143 MINIFLOW_FOR_EACH_IN_MAP(target_u32, target, mask->masks.map) {
1144 if ((*flowp++ ^ target_u32) & *maskp++) {
1152 static inline struct cls_match *
1153 find_match_miniflow(const struct cls_subtable *subtable,
1154 const struct miniflow *flow,
1157 struct cls_match *rule;
1159 HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &subtable->rules) {
1160 if (miniflow_and_mask_matches_miniflow(&rule->flow, &subtable->mask,
1169 /* Finds and returns the highest-priority rule in 'cls' that matches
1170 * 'miniflow'. Returns a null pointer if no rules in 'cls' match 'flow'.
1171 * If multiple rules of equal priority match 'flow', returns one arbitrarily.
1173 * This function is optimized for the userspace datapath, which only ever has
1174 * one priority value for it's flows!
1176 struct cls_rule *classifier_lookup_miniflow_first(const struct classifier *cls_,
1177 const struct miniflow *flow)
1179 struct cls_classifier *cls = cls_->cls;
1180 struct cls_subtable *subtable;
1181 struct cls_subtable_entry *iter;
1183 CLS_SUBTABLE_CACHE_FOR_EACH (subtable, iter, &cls->subtables_priority) {
1184 struct cls_match *rule;
1186 rule = find_match_miniflow(subtable, flow,
1187 miniflow_hash_in_minimask(flow,
1191 return rule->cls_rule;
1198 /* Finds and returns a rule in 'cls' with exactly the same priority and
1199 * matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
1200 * contain an exact match. */
1202 classifier_find_rule_exactly(const struct classifier *cls_,
1203 const struct cls_rule *target)
1205 struct cls_classifier *cls = cls_->cls;
1206 struct cls_match *head, *rule;
1207 struct cls_subtable *subtable;
1209 subtable = find_subtable(cls, &target->match.mask);
1214 /* Skip if there is no hope. */
1215 if (target->priority > subtable->max_priority) {
1219 head = find_equal(subtable, &target->match.flow,
1220 miniflow_hash_in_minimask(&target->match.flow,
1221 &target->match.mask, 0));
1222 FOR_EACH_RULE_IN_LIST (rule, head) {
1223 if (target->priority >= rule->priority) {
1224 return target->priority == rule->priority ? rule->cls_rule : NULL;
1230 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
1231 * same matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
1232 * contain an exact match. */
1234 classifier_find_match_exactly(const struct classifier *cls,
1235 const struct match *target,
1236 unsigned int priority)
1238 struct cls_rule *retval;
1241 cls_rule_init(&cr, target, priority);
1242 retval = classifier_find_rule_exactly(cls, &cr);
1243 cls_rule_destroy(&cr);
1248 /* Checks if 'target' would overlap any other rule in 'cls'. Two rules are
1249 * considered to overlap if both rules have the same priority and a packet
1250 * could match both. */
1252 classifier_rule_overlaps(const struct classifier *cls_,
1253 const struct cls_rule *target)
1255 struct cls_classifier *cls = cls_->cls;
1256 struct cls_subtable *subtable;
1257 struct cls_subtable_entry *iter;
1259 /* Iterate subtables in the descending max priority order. */
1260 CLS_SUBTABLE_CACHE_FOR_EACH (subtable, iter, &cls->subtables_priority) {
1261 uint32_t storage[FLOW_U32S];
1262 struct minimask mask;
1263 struct cls_match *head;
1265 if (target->priority > iter->max_priority) {
1266 break; /* Can skip this and the rest of the subtables. */
1269 minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
1270 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
1271 struct cls_match *rule;
1273 FOR_EACH_RULE_IN_LIST (rule, head) {
1274 if (rule->priority < target->priority) {
1275 break; /* Rules in descending priority order. */
1277 if (rule->priority == target->priority
1278 && miniflow_equal_in_minimask(&target->match.flow,
1279 &rule->flow, &mask)) {
1289 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
1290 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
1291 * function returns true if, for every field:
1293 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
1296 * - 'criteria' wildcards the field,
1298 * Conversely, 'rule' does not match 'criteria' and this function returns false
1299 * if, for at least one field:
1301 * - 'criteria' and 'rule' specify different values for the field, or
1303 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
1305 * Equivalently, the truth table for whether a field matches is:
1310 * r +---------+---------+
1311 * i wild | yes | yes |
1313 * e +---------+---------+
1314 * r exact | no |if values|
1316 * a +---------+---------+
1318 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
1319 * commands and by OpenFlow 1.0 aggregate and flow stats.
1321 * Ignores rule->priority. */
1323 cls_rule_is_loose_match(const struct cls_rule *rule,
1324 const struct minimatch *criteria)
1326 return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
1327 && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
1334 rule_matches(const struct cls_match *rule, const struct cls_rule *target)
1337 || miniflow_equal_in_minimask(&rule->flow,
1338 &target->match.flow,
1339 &target->match.mask));
1342 static struct cls_match *
1343 search_subtable(const struct cls_subtable *subtable,
1344 const struct cls_rule *target)
1346 if (!target || !minimask_has_extra(&subtable->mask, &target->match.mask)) {
1347 struct cls_match *rule;
1349 HMAP_FOR_EACH (rule, hmap_node, &subtable->rules) {
1350 if (rule_matches(rule, target)) {
1358 /* Initializes 'cursor' for iterating through rules in 'cls':
1360 * - If 'target' is null, the cursor will visit every rule in 'cls'.
1362 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1363 * such that cls_rule_is_loose_match(rule, target) returns true.
1365 * Ignores target->priority. */
1367 cls_cursor_init(struct cls_cursor *cursor, const struct classifier *cls,
1368 const struct cls_rule *target)
1370 cursor->cls = cls->cls;
1371 cursor->target = target && !cls_rule_is_catchall(target) ? target : NULL;
1374 /* Returns the first matching cls_rule in 'cursor''s iteration, or a null
1375 * pointer if there are no matches. */
1377 cls_cursor_first(struct cls_cursor *cursor)
1379 struct cls_subtable *subtable;
1381 HMAP_FOR_EACH (subtable, hmap_node, &cursor->cls->subtables) {
1382 struct cls_match *rule = search_subtable(subtable, cursor->target);
1384 cursor->subtable = subtable;
1385 return rule->cls_rule;
1392 /* Returns the next matching cls_rule in 'cursor''s iteration, or a null
1393 * pointer if there are no more matches. */
1395 cls_cursor_next(struct cls_cursor *cursor, const struct cls_rule *rule_)
1397 struct cls_match *rule = CONST_CAST(struct cls_match *, rule_->cls_match);
1398 const struct cls_subtable *subtable;
1399 struct cls_match *next;
1401 next = next_rule_in_list__(rule);
1402 if (next->priority < rule->priority) {
1403 return next->cls_rule;
1406 /* 'next' is the head of the list, that is, the rule that is included in
1407 * the subtable's hmap. (This is important when the classifier contains
1408 * rules that differ only in priority.) */
1410 HMAP_FOR_EACH_CONTINUE (rule, hmap_node, &cursor->subtable->rules) {
1411 if (rule_matches(rule, cursor->target)) {
1412 return rule->cls_rule;
1416 subtable = cursor->subtable;
1417 HMAP_FOR_EACH_CONTINUE (subtable, hmap_node, &cursor->cls->subtables) {
1418 rule = search_subtable(subtable, cursor->target);
1420 cursor->subtable = subtable;
1421 return rule->cls_rule;
1428 static struct cls_subtable *
1429 find_subtable(const struct cls_classifier *cls, const struct minimask *mask)
1431 struct cls_subtable *subtable;
1433 HMAP_FOR_EACH_IN_BUCKET (subtable, hmap_node, minimask_hash(mask, 0),
1435 if (minimask_equal(mask, &subtable->mask)) {
1442 static struct cls_subtable *
1443 insert_subtable(struct cls_classifier *cls, const struct minimask *mask)
1445 uint32_t hash = minimask_hash(mask, 0);
1446 struct cls_subtable *subtable;
1448 struct flow_wildcards old, new;
1450 struct cls_subtable_entry elem;
1451 int count = count_1bits(mask->masks.map);
1453 subtable = xzalloc(sizeof *subtable - sizeof mask->masks.inline_values
1454 + MINIFLOW_VALUES_SIZE(count));
1455 hmap_init(&subtable->rules);
1456 miniflow_clone_inline(&subtable->mask.masks, &mask->masks, count);
1458 /* Init indices for segmented lookup, if any. */
1459 flow_wildcards_init_catchall(&new);
1462 for (i = 0; i < cls->n_flow_segments; i++) {
1463 flow_wildcards_fold_minimask_range(&new, mask, prev,
1464 cls->flow_segments[i]);
1465 /* Add an index if it adds mask bits. */
1466 if (!flow_wildcards_equal(&new, &old)) {
1467 hindex_init(&subtable->indices[index]);
1468 subtable->index_ofs[index] = cls->flow_segments[i];
1472 prev = cls->flow_segments[i];
1474 /* Check if the rest of the subtable's mask adds any bits,
1475 * and remove the last index if it doesn't. */
1477 flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U32S);
1478 if (flow_wildcards_equal(&new, &old)) {
1480 subtable->index_ofs[index] = 0;
1481 hindex_destroy(&subtable->indices[index]);
1484 subtable->n_indices = index;
1486 subtable->tag = (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1487 ? tag_create_deterministic(hash)
1490 for (i = 0; i < cls->n_tries; i++) {
1491 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1492 cls->tries[i].field);
1496 subtable->ports_trie = NULL;
1497 subtable->ports_mask_len
1498 = 32 - ctz32(ntohl(MINIFLOW_GET_BE32(&mask->masks, tp_src)));
1500 hmap_insert(&cls->subtables, &subtable->hmap_node, hash);
1501 elem.subtable = subtable;
1502 elem.tag = subtable->tag;
1503 elem.max_priority = subtable->max_priority;
1504 cls_subtable_cache_push_back(&cls->subtables_priority, elem);
1510 destroy_subtable(struct cls_classifier *cls, struct cls_subtable *subtable)
1513 struct cls_subtable *table = NULL;
1514 struct cls_subtable_entry *iter;
1516 CLS_SUBTABLE_CACHE_FOR_EACH (table, iter, &cls->subtables_priority) {
1517 if (table == subtable) {
1518 cls_subtable_cache_remove(&cls->subtables_priority, iter);
1523 trie_destroy(subtable->ports_trie);
1525 for (i = 0; i < subtable->n_indices; i++) {
1526 hindex_destroy(&subtable->indices[i]);
1528 minimask_destroy(&subtable->mask);
1529 hmap_remove(&cls->subtables, &subtable->hmap_node);
1530 hmap_destroy(&subtable->rules);
1534 /* This function performs the following updates for 'subtable' in 'cls'
1535 * following the addition of a new rule with priority 'new_priority' to
1538 * - Update 'subtable->max_priority' and 'subtable->max_count' if necessary.
1540 * - Update 'subtable''s position in 'cls->subtables_priority' if necessary.
1542 * This function should only be called after adding a new rule, not after
1543 * replacing a rule by an identical one or modifying a rule in-place. */
1545 update_subtables_after_insertion(struct cls_classifier *cls,
1546 struct cls_subtable *subtable,
1547 unsigned int new_priority)
1549 if (new_priority == subtable->max_priority) {
1550 ++subtable->max_count;
1551 } else if (new_priority > subtable->max_priority) {
1552 struct cls_subtable *table;
1553 struct cls_subtable_entry *iter, *from = NULL;
1555 subtable->max_priority = new_priority;
1556 subtable->max_count = 1;
1558 /* Possibly move 'subtable' earlier in the priority array. If
1559 * we break out of the loop, then the subtable (at 'from')
1560 * should be moved to the position right after the current
1561 * element. If the loop terminates normally, then 'iter' will
1562 * be at the first array element and we'll move the subtable
1563 * to the front of the array. */
1564 CLS_SUBTABLE_CACHE_FOR_EACH_REVERSE (table, iter,
1565 &cls->subtables_priority) {
1566 if (table == subtable) {
1567 from = iter; /* Locate the subtable as we go. */
1568 iter->max_priority = new_priority;
1569 } else if (table->max_priority >= new_priority) {
1571 /* Corrupted cache? */
1572 cls_subtable_cache_reset(cls);
1573 VLOG_ABORT("update_subtables_after_insertion(): Subtable priority list corrupted.");
1576 iter++; /* After this. */
1581 /* Move subtable at 'from' to 'iter'. */
1582 cls_subtable_cache_move(iter, from);
1586 /* This function performs the following updates for 'subtable' in 'cls'
1587 * following the deletion of a rule with priority 'del_priority' from
1590 * - Update 'subtable->max_priority' and 'subtable->max_count' if necessary.
1592 * - Update 'subtable''s position in 'cls->subtables_priority' if necessary.
1594 * This function should only be called after removing a rule, not after
1595 * replacing a rule by an identical one or modifying a rule in-place. */
1597 update_subtables_after_removal(struct cls_classifier *cls,
1598 struct cls_subtable *subtable,
1599 unsigned int del_priority)
1601 if (del_priority == subtable->max_priority && --subtable->max_count == 0) {
1602 struct cls_match *head;
1603 struct cls_subtable *table;
1604 struct cls_subtable_entry *iter, *from = NULL;
1606 subtable->max_priority = 0;
1607 HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
1608 if (head->priority > subtable->max_priority) {
1609 subtable->max_priority = head->priority;
1610 subtable->max_count = 1;
1611 } else if (head->priority == subtable->max_priority) {
1612 ++subtable->max_count;
1616 /* Possibly move 'subtable' later in the priority array.
1617 * After the loop the 'iter' will point right after the position
1618 * at which the subtable should be moved (either at a subtable
1619 * with an equal or lower priority, or just past the array),
1620 * so it is decremented once. */
1621 CLS_SUBTABLE_CACHE_FOR_EACH (table, iter, &cls->subtables_priority) {
1622 if (table == subtable) {
1623 from = iter; /* Locate the subtable as we go. */
1624 iter->max_priority = subtable->max_priority;
1625 } else if (table->max_priority <= subtable->max_priority) {
1627 /* Corrupted cache? */
1628 cls_subtable_cache_reset(cls);
1629 VLOG_ABORT("update_subtables_after_removal(): Subtable priority list corrupted.");
1635 /* Now at one past the destination. */
1638 /* Move subtable at 'from' to 'iter'. */
1639 cls_subtable_cache_move(iter, from);
1648 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1649 * lookup results. */
1651 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1652 const unsigned int field_plen[CLS_MAX_TRIES],
1653 const struct range ofs, const struct flow *flow,
1654 struct flow_wildcards *wc)
1658 /* Check if we could avoid fully unwildcarding the next level of
1659 * fields using the prefix tries. The trie checks are done only as
1660 * needed to avoid folding in additional bits to the wildcards mask. */
1661 for (j = 0; j < n_tries; j++) {
1662 /* Is the trie field relevant for this subtable? */
1663 if (field_plen[j]) {
1664 struct trie_ctx *ctx = &trie_ctx[j];
1665 uint8_t be32ofs = ctx->be32ofs;
1667 /* Is the trie field within the current range of fields? */
1668 if (be32ofs >= ofs.start && be32ofs < ofs.end) {
1669 /* On-demand trie lookup. */
1670 if (!ctx->lookup_done) {
1671 ctx->match_plen = trie_lookup(ctx->trie, flow,
1673 ctx->lookup_done = true;
1675 /* Possible to skip the rest of the subtable if subtable's
1676 * prefix on the field is longer than what is known to match
1677 * based on the trie lookup. */
1678 if (field_plen[j] > ctx->match_plen) {
1679 /* RFC: We want the trie lookup to never result in
1680 * unwildcarding any bits that would not be unwildcarded
1681 * otherwise. Since the trie is shared by the whole
1682 * classifier, it is possible that the 'maskbits' contain
1683 * bits that are irrelevant for the partition of the
1684 * classifier relevant for the current flow. */
1686 /* Can skip if the field is already unwildcarded. */
1687 if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1690 /* Check that the trie result will not unwildcard more bits
1691 * than this stage will. */
1692 if (ctx->maskbits <= field_plen[j]) {
1693 /* Unwildcard the bits and skip the rest. */
1694 mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1695 /* Note: Prerequisite already unwildcarded, as the only
1696 * prerequisite of the supported trie lookup fields is
1697 * the ethertype, which is currently always
1709 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1710 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1711 * value has the correct value in 'target'.
1713 * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
1714 * target, mask) but it is faster because of the invariant that
1715 * flow->map and mask->masks.map are the same. */
1717 miniflow_and_mask_matches_flow(const struct miniflow *flow,
1718 const struct minimask *mask,
1719 const struct flow *target)
1721 const uint32_t *flowp = miniflow_get_u32_values(flow);
1722 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1723 uint32_t target_u32;
1725 FLOW_FOR_EACH_IN_MAP(target_u32, target, mask->masks.map) {
1726 if ((*flowp++ ^ target_u32) & *maskp++) {
1734 static inline struct cls_match *
1735 find_match(const struct cls_subtable *subtable, const struct flow *flow,
1738 struct cls_match *rule;
1740 HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &subtable->rules) {
1741 if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
1750 static struct cls_match *
1751 find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
1752 struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1753 struct flow_wildcards *wc)
1755 uint32_t basis = 0, hash;
1756 struct cls_match *rule = NULL;
1760 if (OVS_UNLIKELY(!wc)) {
1761 return find_match(subtable, flow,
1762 flow_hash_in_minimask(flow, &subtable->mask, 0));
1766 /* Try to finish early by checking fields in segments. */
1767 for (i = 0; i < subtable->n_indices; i++) {
1768 struct hindex_node *inode;
1769 ofs.end = subtable->index_ofs[i];
1771 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1775 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1777 ofs.start = ofs.end;
1778 inode = hindex_node_with_hash(&subtable->indices[i], hash);
1780 /* No match, can stop immediately, but must fold in the mask
1781 * covered so far. */
1785 /* If we have narrowed down to a single rule already, check whether
1786 * that rule matches. If it does match, then we're done. If it does
1787 * not match, then we know that we will never get a match, but we do
1788 * not yet know how many wildcards we need to fold into 'wc' so we
1789 * continue iterating through indices to find that out. (We won't
1790 * waste time calling miniflow_and_mask_matches_flow() again because
1791 * we've set 'rule' nonnull.)
1793 * This check shows a measurable benefit with non-trivial flow tables.
1795 * (Rare) hash collisions may cause us to miss the opportunity for this
1797 if (!inode->s && !rule) {
1798 ASSIGN_CONTAINER(rule, inode - i, index_nodes);
1799 if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
1805 ofs.end = FLOW_U32S;
1806 /* Trie check for the final range. */
1807 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1811 /* Multiple potential matches exist, look for one. */
1812 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1814 rule = find_match(subtable, flow, hash);
1816 /* We already narrowed the matching candidates down to just 'rule',
1817 * but it didn't match. */
1820 if (!rule && subtable->ports_mask_len) {
1821 /* Ports are always part of the final range, if any.
1822 * No match was found for the ports. Use the ports trie to figure out
1823 * which ports bits to unwildcard. */
1825 ovs_be32 value, mask;
1827 mask = MINIFLOW_GET_BE32(&subtable->mask.masks, tp_src);
1828 value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
1829 trie_lookup_value(subtable->ports_trie, &value, 32, &mbits);
1831 ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
1832 mask & htonl(~0 << (32 - mbits));
1834 ofs.start = TP_PORTS_OFS32;
1838 /* Must unwildcard all the fields, as they were looked at. */
1839 flow_wildcards_fold_minimask(wc, &subtable->mask);
1843 /* Must unwildcard the fields looked up so far, if any. */
1845 flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, ofs.start);
1850 static struct cls_match *
1851 find_equal(struct cls_subtable *subtable, const struct miniflow *flow,
1854 struct cls_match *head;
1856 HMAP_FOR_EACH_WITH_HASH (head, hmap_node, hash, &subtable->rules) {
1857 if (miniflow_equal(&head->flow, flow)) {
1864 static struct cls_match *
1865 insert_rule(struct cls_classifier *cls, struct cls_subtable *subtable,
1866 struct cls_rule *new)
1868 struct cls_match *cls_match = cls_match_alloc(new);
1869 struct cls_match *head;
1870 struct cls_match *old = NULL;
1872 uint32_t basis = 0, hash;
1873 uint8_t prev_be32ofs = 0;
1875 /* Add new node to segment indices. */
1876 for (i = 0; i < subtable->n_indices; i++) {
1877 hash = minimatch_hash_range(&new->match, prev_be32ofs,
1878 subtable->index_ofs[i], &basis);
1879 hindex_insert(&subtable->indices[i], &cls_match->index_nodes[i], hash);
1880 prev_be32ofs = subtable->index_ofs[i];
1882 hash = minimatch_hash_range(&new->match, prev_be32ofs, FLOW_U32S, &basis);
1883 head = find_equal(subtable, &new->match.flow, hash);
1885 hmap_insert(&subtable->rules, &cls_match->hmap_node, hash);
1886 list_init(&cls_match->list);
1889 /* Scan the list for the insertion point that will keep the list in
1890 * order of decreasing priority. */
1891 struct cls_match *rule;
1893 cls_match->hmap_node.hash = hash; /* Otherwise done by hmap_insert. */
1895 FOR_EACH_RULE_IN_LIST (rule, head) {
1896 if (cls_match->priority >= rule->priority) {
1898 /* 'new' is the new highest-priority flow in the list. */
1899 hmap_replace(&subtable->rules,
1900 &rule->hmap_node, &cls_match->hmap_node);
1903 if (cls_match->priority == rule->priority) {
1904 list_replace(&cls_match->list, &rule->list);
1908 list_insert(&rule->list, &cls_match->list);
1914 /* Insert 'new' at the end of the list. */
1915 list_push_back(&head->list, &cls_match->list);
1920 update_subtables_after_insertion(cls, subtable, cls_match->priority);
1922 /* Remove old node from indices. */
1923 for (i = 0; i < subtable->n_indices; i++) {
1924 hindex_remove(&subtable->indices[i], &old->index_nodes[i]);
1930 static struct cls_match *
1931 next_rule_in_list__(struct cls_match *rule)
1933 struct cls_match *next = OBJECT_CONTAINING(rule->list.next, next, list);
1937 static struct cls_match *
1938 next_rule_in_list(struct cls_match *rule)
1940 struct cls_match *next = next_rule_in_list__(rule);
1941 return next->priority < rule->priority ? next : NULL;
1944 /* A longest-prefix match tree. */
1946 uint32_t prefix; /* Prefix bits for this node, MSB first. */
1947 uint8_t nbits; /* Never zero, except for the root node. */
1948 unsigned int n_rules; /* Number of rules that have this prefix. */
1949 struct trie_node *edges[2]; /* Both NULL if leaf. */
1952 /* Max bits per node. Must fit in struct trie_node's 'prefix'.
1953 * Also tested with 16, 8, and 5 to stress the implementation. */
1954 #define TRIE_PREFIX_BITS 32
1956 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1957 * Prefixes are in the network byte order, and the offset 0 corresponds to
1958 * the most significant bit of the first byte. The offset can be read as
1959 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1961 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1965 pr += ofs / 32; /* Where to start. */
1966 ofs %= 32; /* How many bits to skip at 'pr'. */
1968 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1969 if (plen > 32 - ofs) { /* Need more than we have already? */
1970 prefix |= ntohl(*++pr) >> (32 - ofs);
1972 /* Return with possible unwanted bits at the end. */
1976 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1977 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1978 * corresponds to the most significant bit of the first byte. The offset can
1979 * be read as "how many bits to skip from the start of the prefix starting at
1982 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1987 if (plen > TRIE_PREFIX_BITS) {
1988 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1990 /* Return with unwanted bits cleared. */
1991 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1994 /* Return the number of equal bits in 'nbits' of 'prefix's MSBs and a 'value'
1995 * starting at "MSB 0"-based offset 'ofs'. */
1997 prefix_equal_bits(uint32_t prefix, unsigned int nbits, const ovs_be32 value[],
2000 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, nbits);
2001 /* Set the bit after the relevant bits to limit the result. */
2002 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - nbits));
2005 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
2006 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
2008 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
2009 unsigned int ofs, unsigned int plen)
2011 return prefix_equal_bits(node->prefix, MIN(node->nbits, plen - ofs),
2015 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
2016 * be greater than 31. */
2018 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
2020 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
2023 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
2024 * be between 0 and 31, inclusive. */
2026 get_bit_at(const uint32_t prefix, unsigned int ofs)
2028 return (prefix >> (31 - ofs)) & 1u;
2031 /* Create new branch. */
2032 static struct trie_node *
2033 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
2034 unsigned int n_rules)
2036 struct trie_node *node = xmalloc(sizeof *node);
2038 node->prefix = trie_get_prefix(prefix, ofs, plen);
2040 if (plen <= TRIE_PREFIX_BITS) {
2042 node->edges[0] = NULL;
2043 node->edges[1] = NULL;
2044 node->n_rules = n_rules;
2045 } else { /* Need intermediate nodes. */
2046 struct trie_node *subnode = trie_branch_create(prefix,
2047 ofs + TRIE_PREFIX_BITS,
2048 plen - TRIE_PREFIX_BITS,
2050 int bit = get_bit_at(subnode->prefix, 0);
2051 node->nbits = TRIE_PREFIX_BITS;
2052 node->edges[bit] = subnode;
2053 node->edges[!bit] = NULL;
2060 trie_node_destroy(struct trie_node *node)
2066 trie_destroy(struct trie_node *node)
2069 trie_destroy(node->edges[0]);
2070 trie_destroy(node->edges[1]);
2076 trie_is_leaf(const struct trie_node *trie)
2078 return !trie->edges[0] && !trie->edges[1]; /* No children. */
2082 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
2085 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
2088 for (i = 0; i < nbits / 32; i++) {
2089 mask[i] = OVS_BE32_MAX;
2092 mask[i] |= htonl(~0u << (32 - nbits % 32));
2097 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
2100 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
2102 ovs_be32 zeroes = 0;
2104 for (i = 0; i < nbits / 32; i++) {
2108 zeroes |= ~mask[i] & htonl(~0u << (32 - nbits % 32));
2111 return !zeroes; /* All 'nbits' bits set. */
2114 static struct trie_node **
2115 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
2118 return node->edges + be_get_bit_at(value, ofs);
2121 static const struct trie_node *
2122 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
2125 return node->edges[be_get_bit_at(value, ofs)];
2128 /* Return the prefix mask length necessary to find the longest-prefix match for
2129 * the '*value' in the prefix tree 'node'.
2130 * '*checkbits' is set to the number of bits in the prefix mask necessary to
2131 * determine a mismatch, in case there are longer prefixes in the tree below
2132 * the one that matched.
2135 trie_lookup_value(const struct trie_node *node, const ovs_be32 value[],
2136 unsigned int n_bits, unsigned int *checkbits)
2138 unsigned int ofs = 0, match_len = 0;
2139 const struct trie_node *prev = NULL;
2141 for (; node; prev = node, node = trie_next_node(node, value, ofs)) {
2142 unsigned int eqbits;
2143 /* Check if this edge can be followed. */
2144 eqbits = prefix_equal_bits(node->prefix, node->nbits, value, ofs);
2146 if (eqbits < node->nbits) { /* Mismatch, nothing more to be found. */
2147 /* Bit at offset 'ofs' differed. */
2148 *checkbits = ofs + 1; /* Includes the first mismatching bit. */
2151 /* Full match, check if rules exist at this prefix length. */
2152 if (node->n_rules > 0) {
2155 if (ofs >= n_bits) {
2156 *checkbits = n_bits; /* Full prefix. */
2160 /* node == NULL. Full match so far, but we came to a dead end.
2161 * need to exclude the other branch if it exists. */
2162 *checkbits = !prev || trie_is_leaf(prev) ? ofs : ofs + 1;
2167 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
2168 unsigned int *checkbits)
2170 const struct mf_field *mf = trie->field;
2172 /* Check that current flow matches the prerequisites for the trie
2173 * field. Some match fields are used for multiple purposes, so we
2174 * must check that the trie is relevant for this flow. */
2175 if (mf_are_prereqs_ok(mf, flow)) {
2176 return trie_lookup_value(trie->root,
2177 &((ovs_be32 *)flow)[mf->flow_be32ofs],
2178 mf->n_bits, checkbits);
2180 *checkbits = 0; /* Value not used in this case. */
2184 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
2185 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
2186 * 'miniflow_index' is not NULL. */
2188 minimask_get_prefix_len(const struct minimask *minimask,
2189 const struct mf_field *mf)
2191 unsigned int nbits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
2192 uint8_t u32_ofs = mf->flow_be32ofs;
2193 uint8_t u32_end = u32_ofs + mf->n_bytes / 4;
2195 for (; u32_ofs < u32_end; ++u32_ofs) {
2197 mask = ntohl((OVS_FORCE ovs_be32)minimask_get(minimask, u32_ofs));
2199 /* Validate mask, count the mask length. */
2202 return 0; /* No bits allowed after mask ended. */
2205 if (~mask & (~mask + 1)) {
2206 return 0; /* Mask not contiguous. */
2208 mask_tz = ctz32(mask);
2209 nbits += 32 - mask_tz;
2217 * This is called only when mask prefix is known to be CIDR and non-zero.
2218 * Relies on the fact that the flow and mask have the same map, and since
2219 * the mask is CIDR, the storage for the flow field exists even if it
2220 * happened to be zeros.
2222 static const ovs_be32 *
2223 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
2225 return miniflow_get_be32_values(&match->flow) +
2226 count_1bits(match->flow.map & ((UINT64_C(1) << mf->flow_be32ofs) - 1));
2229 /* Insert rule in to the prefix tree.
2230 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2233 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2235 trie_insert_prefix(&trie->root,
2236 minimatch_get_prefix(&rule->match, trie->field), mlen);
2240 trie_insert_prefix(struct trie_node **edge, const ovs_be32 *prefix, int mlen)
2242 struct trie_node *node;
2245 /* Walk the tree. */
2246 for (; (node = *edge) != NULL;
2247 edge = trie_next_edge(node, prefix, ofs)) {
2248 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2250 if (eqbits < node->nbits) {
2251 /* Mismatch, new node needs to be inserted above. */
2252 int old_branch = get_bit_at(node->prefix, eqbits);
2254 /* New parent node. */
2255 *edge = trie_branch_create(prefix, ofs - eqbits, eqbits,
2256 ofs == mlen ? 1 : 0);
2258 /* Adjust old node for its new position in the tree. */
2259 node->prefix <<= eqbits;
2260 node->nbits -= eqbits;
2261 (*edge)->edges[old_branch] = node;
2263 /* Check if need a new branch for the new rule. */
2265 (*edge)->edges[!old_branch]
2266 = trie_branch_create(prefix, ofs, mlen - ofs, 1);
2270 /* Full match so far. */
2273 /* Full match at the current node, rule needs to be added here. */
2278 /* Must insert a new tree branch for the new rule. */
2279 *edge = trie_branch_create(prefix, ofs, mlen - ofs, 1);
2282 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2285 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2287 trie_remove_prefix(&trie->root,
2288 minimatch_get_prefix(&rule->match, trie->field), mlen);
2291 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2294 trie_remove_prefix(struct trie_node **root, const ovs_be32 *prefix, int mlen)
2296 struct trie_node *node;
2297 struct trie_node **edges[sizeof(union mf_value) * 8];
2298 int depth = 0, ofs = 0;
2300 /* Walk the tree. */
2301 for (edges[0] = root;
2302 (node = *edges[depth]) != NULL;
2303 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
2304 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2306 if (eqbits < node->nbits) {
2307 /* Mismatch, nothing to be removed. This should never happen, as
2308 * only rules in the classifier are ever removed. */
2309 break; /* Log a warning. */
2311 /* Full match so far. */
2315 /* Full prefix match at the current node, remove rule here. */
2316 if (!node->n_rules) {
2317 break; /* Log a warning. */
2321 /* Check if can prune the tree. */
2322 while (!node->n_rules && !(node->edges[0] && node->edges[1])) {
2323 /* No rules and at most one child node, remove this node. */
2324 struct trie_node *next;
2325 next = node->edges[0] ? node->edges[0] : node->edges[1];
2328 if (node->nbits + next->nbits > TRIE_PREFIX_BITS) {
2329 break; /* Cannot combine. */
2331 /* Combine node with next. */
2332 next->prefix = node->prefix | next->prefix >> node->nbits;
2333 next->nbits += node->nbits;
2335 trie_node_destroy(node);
2336 /* Update the parent's edge. */
2337 *edges[depth] = next;
2338 if (next || !depth) {
2339 /* Branch not pruned or at root, nothing more to do. */
2342 node = *edges[--depth];
2347 /* Cannot go deeper. This should never happen, since only rules
2348 * that actually exist in the classifier are ever removed. */
2349 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");