2 * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 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"
19 #include "classifier-private.h"
21 #include <netinet/in.h>
22 #include "byte-order.h"
23 #include "dynamic-string.h"
30 VLOG_DEFINE_THIS_MODULE(classifier);
34 /* Ports trie depends on both ports sharing the same ovs_be32. */
35 #define TP_PORTS_OFS32 (offsetof(struct flow, tp_src) / 4)
36 BUILD_ASSERT_DECL(TP_PORTS_OFS32 == offsetof(struct flow, tp_dst) / 4);
38 static struct cls_match *
39 cls_match_alloc(struct cls_rule *rule)
41 int count = count_1bits(rule->match.flow.map);
43 struct cls_match *cls_match
44 = xmalloc(sizeof *cls_match - sizeof cls_match->flow.inline_values
45 + MINIFLOW_VALUES_SIZE(count));
47 cls_match->cls_rule = rule;
48 miniflow_clone_inline(&cls_match->flow, &rule->match.flow, count);
49 cls_match->priority = rule->priority;
50 rule->cls_match = cls_match;
55 static struct cls_subtable *find_subtable(const struct classifier *cls,
56 const struct minimask *)
57 OVS_REQUIRES(cls->mutex);
58 static struct cls_subtable *insert_subtable(struct classifier *cls,
59 const struct minimask *)
60 OVS_REQUIRES(cls->mutex);
61 static void destroy_subtable(struct classifier *cls, struct cls_subtable *)
62 OVS_REQUIRES(cls->mutex);
63 static struct cls_match *insert_rule(struct classifier *cls,
64 struct cls_subtable *, struct cls_rule *)
65 OVS_REQUIRES(cls->mutex);
67 static struct cls_match *find_match_wc(const struct cls_subtable *,
68 const struct flow *, struct trie_ctx *,
70 struct flow_wildcards *);
71 static struct cls_match *find_equal(struct cls_subtable *,
72 const struct miniflow *, uint32_t hash);
74 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list.
75 * Classifier's mutex must be held while iterating, as the list is
76 * protoceted by it. */
77 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD) \
78 for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
79 #define FOR_EACH_RULE_IN_LIST_SAFE(RULE, NEXT, HEAD) \
80 for ((RULE) = (HEAD); \
81 (RULE) != NULL && ((NEXT) = next_rule_in_list(RULE), true); \
84 static struct cls_match *next_rule_in_list__(struct cls_match *);
85 static struct cls_match *next_rule_in_list(struct cls_match *);
87 static unsigned int minimask_get_prefix_len(const struct minimask *,
88 const struct mf_field *);
89 static void trie_init(struct classifier *cls, int trie_idx,
90 const struct mf_field *)
91 OVS_REQUIRES(cls->mutex);
92 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
93 union mf_value *plens);
94 static unsigned int trie_lookup_value(const rcu_trie_ptr *,
95 const ovs_be32 value[], ovs_be32 plens[],
96 unsigned int value_bits);
97 static void trie_destroy(rcu_trie_ptr *);
98 static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
99 static void trie_insert_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
101 static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
102 static void trie_remove_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
104 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
105 unsigned int n_bits);
106 static bool mask_prefix_bits_set(const struct flow_wildcards *,
107 uint8_t be32ofs, unsigned int n_bits);
111 /* Initializes 'rule' to match packets specified by 'match' at the given
112 * 'priority'. 'match' must satisfy the invariant described in the comment at
113 * the definition of struct match.
115 * The caller must eventually destroy 'rule' with cls_rule_destroy().
117 * Clients should not use priority INT_MIN. (OpenFlow uses priorities between
118 * 0 and UINT16_MAX, inclusive.) */
120 cls_rule_init(struct cls_rule *rule, const struct match *match, int priority)
122 minimatch_init(&rule->match, match);
123 rule->priority = priority;
124 rule->cls_match = NULL;
127 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
129 cls_rule_init_from_minimatch(struct cls_rule *rule,
130 const struct minimatch *match, int priority)
132 minimatch_clone(&rule->match, match);
133 rule->priority = priority;
134 rule->cls_match = NULL;
137 /* Initializes 'dst' as a copy of 'src'.
139 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
141 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
143 minimatch_clone(&dst->match, &src->match);
144 dst->priority = src->priority;
145 dst->cls_match = NULL;
148 /* Initializes 'dst' with the data in 'src', destroying 'src'.
150 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
152 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
154 minimatch_move(&dst->match, &src->match);
155 dst->priority = src->priority;
156 dst->cls_match = NULL;
159 /* Frees memory referenced by 'rule'. Doesn't free 'rule' itself (it's
160 * normally embedded into a larger structure).
162 * ('rule' must not currently be in a classifier.) */
164 cls_rule_destroy(struct cls_rule *rule)
166 ovs_assert(!rule->cls_match);
167 minimatch_destroy(&rule->match);
170 /* Returns true if 'a' and 'b' match the same packets at the same priority,
171 * false if they differ in some way. */
173 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
175 return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
178 /* Returns a hash value for 'rule', folding in 'basis'. */
180 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
182 return minimatch_hash(&rule->match, hash_int(rule->priority, basis));
185 /* Appends a string describing 'rule' to 's'. */
187 cls_rule_format(const struct cls_rule *rule, struct ds *s)
189 minimatch_format(&rule->match, s, rule->priority);
192 /* Returns true if 'rule' matches every packet, false otherwise. */
194 cls_rule_is_catchall(const struct cls_rule *rule)
196 return minimask_is_catchall(&rule->match.mask);
199 /* Initializes 'cls' as a classifier that initially contains no classification
202 classifier_init(struct classifier *cls, const uint8_t *flow_segments)
203 OVS_EXCLUDED(cls->mutex)
205 ovs_mutex_init(&cls->mutex);
206 ovs_mutex_lock(&cls->mutex);
208 cmap_init(&cls->subtables_map);
209 pvector_init(&cls->subtables);
210 cmap_init(&cls->partitions);
211 cls->n_flow_segments = 0;
213 while (cls->n_flow_segments < CLS_MAX_INDICES
214 && *flow_segments < FLOW_U32S) {
215 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
219 for (int i = 0; i < CLS_MAX_TRIES; i++) {
220 trie_init(cls, i, NULL);
222 ovs_mutex_unlock(&cls->mutex);
225 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
226 * caller's responsibility.
227 * May only be called after all the readers have been terminated. */
229 classifier_destroy(struct classifier *cls)
230 OVS_EXCLUDED(cls->mutex)
233 struct cls_partition *partition;
234 struct cls_subtable *subtable;
237 ovs_mutex_lock(&cls->mutex);
238 for (i = 0; i < cls->n_tries; i++) {
239 trie_destroy(&cls->tries[i].root);
242 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
243 destroy_subtable(cls, subtable);
245 cmap_destroy(&cls->subtables_map);
247 CMAP_FOR_EACH (partition, cmap_node, &cls->partitions) {
248 ovsrcu_postpone(free, partition);
250 cmap_destroy(&cls->partitions);
252 pvector_destroy(&cls->subtables);
253 ovs_mutex_unlock(&cls->mutex);
254 ovs_mutex_destroy(&cls->mutex);
258 /* Set the fields for which prefix lookup should be performed. */
260 classifier_set_prefix_fields(struct classifier *cls,
261 const enum mf_field_id *trie_fields,
262 unsigned int n_fields)
263 OVS_EXCLUDED(cls->mutex)
265 const struct mf_field * new_fields[CLS_MAX_TRIES];
266 struct mf_bitmap fields = MF_BITMAP_INITIALIZER;
268 bool changed = false;
270 ovs_mutex_lock(&cls->mutex);
271 for (i = 0; i < n_fields && n_tries < CLS_MAX_TRIES; i++) {
272 const struct mf_field *field = mf_from_id(trie_fields[i]);
273 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
274 /* Incompatible field. This is the only place where we
275 * enforce these requirements, but the rest of the trie code
276 * depends on the flow_be32ofs to be non-negative and the
277 * field length to be a multiple of 32 bits. */
281 if (bitmap_is_set(fields.bm, trie_fields[i])) {
282 /* Duplicate field, there is no need to build more than
283 * one index for any one field. */
286 bitmap_set1(fields.bm, trie_fields[i]);
288 new_fields[n_tries] = NULL;
289 if (n_tries >= cls->n_tries || field != cls->tries[n_tries].field) {
290 new_fields[n_tries] = field;
296 if (changed || n_tries < cls->n_tries) {
297 struct cls_subtable *subtable;
299 /* Trie configuration needs to change. Disable trie lookups
300 * for the tries that are changing and wait all the current readers
301 * with the old configuration to be done. */
303 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
304 for (i = 0; i < cls->n_tries; i++) {
305 if ((i < n_tries && new_fields[i]) || i >= n_tries) {
306 if (subtable->trie_plen[i]) {
307 subtable->trie_plen[i] = 0;
313 /* Synchronize if any readers were using tries. The readers may
314 * temporarily function without the trie lookup based optimizations. */
316 /* ovsrcu_synchronize() functions as a memory barrier, so it does
317 * not matter that subtable->trie_plen is not atomic. */
318 ovsrcu_synchronize();
321 /* Now set up the tries. */
322 for (i = 0; i < n_tries; i++) {
324 trie_init(cls, i, new_fields[i]);
327 /* Destroy the rest, if any. */
328 for (; i < cls->n_tries; i++) {
329 trie_init(cls, i, NULL);
332 cls->n_tries = n_tries;
333 ovs_mutex_unlock(&cls->mutex);
337 ovs_mutex_unlock(&cls->mutex);
338 return false; /* No change. */
342 trie_init(struct classifier *cls, int trie_idx, const struct mf_field *field)
343 OVS_REQUIRES(cls->mutex)
345 struct cls_trie *trie = &cls->tries[trie_idx];
346 struct cls_subtable *subtable;
348 if (trie_idx < cls->n_tries) {
349 trie_destroy(&trie->root);
351 ovsrcu_set_hidden(&trie->root, NULL);
355 /* Add existing rules to the new trie. */
356 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
359 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
361 struct cls_match *head;
363 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
364 struct cls_match *match;
366 FOR_EACH_RULE_IN_LIST (match, head) {
367 trie_insert(trie, match->cls_rule, plen);
371 /* Initialize subtable's prefix length on this field. This will
372 * allow readers to use the trie. */
373 atomic_thread_fence(memory_order_release);
374 subtable->trie_plen[trie_idx] = plen;
378 /* Returns true if 'cls' contains no classification rules, false otherwise.
379 * Checking the cmap requires no locking. */
381 classifier_is_empty(const struct classifier *cls)
383 return cmap_is_empty(&cls->subtables_map);
386 /* Returns the number of rules in 'cls'. */
388 classifier_count(const struct classifier *cls)
389 OVS_NO_THREAD_SAFETY_ANALYSIS
391 /* n_rules is an int, so in the presence of concurrent writers this will
392 * return either the old or a new value. */
397 hash_metadata(ovs_be64 metadata_)
399 uint64_t metadata = (OVS_FORCE uint64_t) metadata_;
400 return hash_uint64(metadata);
403 static struct cls_partition *
404 find_partition(const struct classifier *cls, ovs_be64 metadata, uint32_t hash)
406 struct cls_partition *partition;
408 CMAP_FOR_EACH_WITH_HASH (partition, cmap_node, hash, &cls->partitions) {
409 if (partition->metadata == metadata) {
417 static struct cls_partition *
418 create_partition(struct classifier *cls, struct cls_subtable *subtable,
420 OVS_REQUIRES(cls->mutex)
422 uint32_t hash = hash_metadata(metadata);
423 struct cls_partition *partition = find_partition(cls, metadata, hash);
425 partition = xmalloc(sizeof *partition);
426 partition->metadata = metadata;
428 tag_tracker_init(&partition->tracker);
429 cmap_insert(&cls->partitions, &partition->cmap_node, hash);
431 tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
435 static inline ovs_be32 minimatch_get_ports(const struct minimatch *match)
437 /* Could optimize to use the same map if needed for fast path. */
438 return MINIFLOW_GET_BE32(&match->flow, tp_src)
439 & MINIFLOW_GET_BE32(&match->mask.masks, tp_src);
442 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
443 * must not modify or free it.
445 * If 'cls' already contains an identical rule (including wildcards, values of
446 * fixed fields, and priority), replaces the old rule by 'rule' and returns the
447 * rule that was replaced. The caller takes ownership of the returned rule and
448 * is thus responsible for destroying it with cls_rule_destroy(), freeing the
449 * memory block in which it resides, etc., as necessary.
451 * Returns NULL if 'cls' does not contain a rule with an identical key, after
452 * inserting the new rule. In this case, no rules are displaced by the new
453 * rule, even rules that cannot have any effect because the new rule matches a
454 * superset of their flows and has higher priority. */
456 classifier_replace(struct classifier *cls, struct cls_rule *rule)
457 OVS_EXCLUDED(cls->mutex)
459 struct cls_match *old_rule;
460 struct cls_subtable *subtable;
461 struct cls_rule *old_cls_rule = NULL;
463 ovs_mutex_lock(&cls->mutex);
464 subtable = find_subtable(cls, &rule->match.mask);
466 subtable = insert_subtable(cls, &rule->match.mask);
469 old_rule = insert_rule(cls, subtable, rule);
473 rule->cls_match->partition = NULL;
474 if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
475 ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
476 rule->cls_match->partition = create_partition(cls, subtable,
482 for (int i = 0; i < cls->n_tries; i++) {
483 if (subtable->trie_plen[i]) {
484 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
489 if (subtable->ports_mask_len) {
490 /* We mask the value to be inserted to always have the wildcarded
491 * bits in known (zero) state, so we can include them in comparison
492 * and they will always match (== their original value does not
494 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
496 trie_insert_prefix(&subtable->ports_trie, &masked_ports,
497 subtable->ports_mask_len);
500 old_cls_rule = old_rule->cls_rule;
501 rule->cls_match->partition = old_rule->partition;
502 old_cls_rule->cls_match = NULL;
504 /* 'old_rule' contains a cmap_node, which may not be freed
506 ovsrcu_postpone(free, old_rule);
508 ovs_mutex_unlock(&cls->mutex);
512 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
513 * must not modify or free it.
515 * 'cls' must not contain an identical rule (including wildcards, values of
516 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
519 classifier_insert(struct classifier *cls, struct cls_rule *rule)
521 struct cls_rule *displaced_rule = classifier_replace(cls, rule);
522 ovs_assert(!displaced_rule);
525 /* Removes 'rule' from 'cls'. It is the caller's responsibility to destroy
526 * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
527 * resides, etc., as necessary.
529 * Does nothing if 'rule' has been already removed, or was never inserted.
531 * Returns the removed rule, or NULL, if it was already removed.
534 classifier_remove(struct classifier *cls, struct cls_rule *rule)
535 OVS_EXCLUDED(cls->mutex)
537 struct cls_partition *partition;
538 struct cls_match *cls_match;
539 struct cls_match *head;
540 struct cls_subtable *subtable;
542 uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
543 uint8_t prev_be32ofs = 0;
545 ovs_mutex_lock(&cls->mutex);
546 cls_match = rule->cls_match;
549 goto unlock; /* Already removed. */
552 subtable = find_subtable(cls, &rule->match.mask);
553 ovs_assert(subtable);
555 if (subtable->ports_mask_len) {
556 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
558 trie_remove_prefix(&subtable->ports_trie,
559 &masked_ports, subtable->ports_mask_len);
561 for (i = 0; i < cls->n_tries; i++) {
562 if (subtable->trie_plen[i]) {
563 trie_remove(&cls->tries[i], rule, subtable->trie_plen[i]);
567 /* Remove rule node from indices. */
568 for (i = 0; i < subtable->n_indices; i++) {
569 ihash[i] = minimatch_hash_range(&rule->match, prev_be32ofs,
570 subtable->index_ofs[i], &basis);
571 cmap_remove(&subtable->indices[i], &cls_match->index_nodes[i],
573 prev_be32ofs = subtable->index_ofs[i];
575 hash = minimatch_hash_range(&rule->match, prev_be32ofs, FLOW_U32S, &basis);
577 head = find_equal(subtable, &rule->match.flow, hash);
578 if (head != cls_match) {
579 list_remove(&cls_match->list);
580 } else if (list_is_empty(&cls_match->list)) {
581 cmap_remove(&subtable->rules, &cls_match->cmap_node, hash);
583 struct cls_match *next = CONTAINER_OF(cls_match->list.next,
584 struct cls_match, list);
586 list_remove(&cls_match->list);
587 cmap_replace(&subtable->rules, &cls_match->cmap_node,
588 &next->cmap_node, hash);
591 partition = cls_match->partition;
593 tag_tracker_subtract(&partition->tracker, &partition->tags,
595 if (!partition->tags) {
596 cmap_remove(&cls->partitions, &partition->cmap_node,
597 hash_metadata(partition->metadata));
598 ovsrcu_postpone(free, partition);
602 if (--subtable->n_rules == 0) {
603 destroy_subtable(cls, subtable);
604 } else if (subtable->max_priority == cls_match->priority
605 && --subtable->max_count == 0) {
606 /* Find the new 'max_priority' and 'max_count'. */
607 struct cls_match *head;
608 int max_priority = INT_MIN;
610 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
611 if (head->priority > max_priority) {
612 max_priority = head->priority;
613 subtable->max_count = 1;
614 } else if (head->priority == max_priority) {
615 ++subtable->max_count;
618 subtable->max_priority = max_priority;
619 pvector_change_priority(&cls->subtables, subtable, max_priority);
624 ovsrcu_postpone(free, cls_match);
625 rule->cls_match = NULL;
627 ovs_mutex_unlock(&cls->mutex);
632 /* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
633 * subtables which have a prefix match on the trie field, but whose prefix
634 * length is not indicated in 'match_plens'. For example, a subtable that
635 * has a 8-bit trie field prefix match can be skipped if
636 * !be_get_bit_at(&match_plens, 8 - 1). If skipped, 'maskbits' prefix bits
637 * must be unwildcarded to make datapath flow only match packets it should. */
639 const struct cls_trie *trie;
640 bool lookup_done; /* Status of the lookup. */
641 uint8_t be32ofs; /* U32 offset of the field in question. */
642 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
643 union mf_value match_plens; /* Bitmask of prefix lengths with possible
648 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
651 ctx->be32ofs = trie->field->flow_be32ofs;
652 ctx->lookup_done = false;
655 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
656 * Returns a null pointer if no rules in 'cls' match 'flow'. If multiple rules
657 * of equal priority match 'flow', returns one arbitrarily.
659 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
660 * set of bits that were significant in the lookup. At some point
661 * earlier, 'wc' should have been initialized (e.g., by
662 * flow_wildcards_init_catchall()). */
664 classifier_lookup(const struct classifier *cls, const struct flow *flow,
665 struct flow_wildcards *wc)
667 const struct cls_partition *partition;
669 int best_priority = INT_MIN;
670 const struct cls_match *best;
671 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
672 struct cls_subtable *subtable;
674 /* Synchronize for cls->n_tries and subtable->trie_plen. They can change
675 * when table configuration changes, which happens typically only on
677 atomic_thread_fence(memory_order_acquire);
679 /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
680 * then 'flow' cannot possibly match in 'subtable':
682 * - If flow->metadata maps to a given 'partition', then we can use
683 * 'tags' for 'partition->tags'.
685 * - If flow->metadata has no partition, then no rule in 'cls' has an
686 * exact-match for flow->metadata. That means that we don't need to
687 * search any subtable that includes flow->metadata in its mask.
689 * In either case, we always need to search any cls_subtables that do not
690 * include flow->metadata in its mask. One way to do that would be to
691 * check the "cls_subtable"s explicitly for that, but that would require an
692 * extra branch per subtable. Instead, we mark such a cls_subtable's
693 * 'tags' as TAG_ALL and make sure that 'tags' is never empty. This means
694 * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
695 * need a special case.
697 partition = (cmap_is_empty(&cls->partitions)
699 : find_partition(cls, flow->metadata,
700 hash_metadata(flow->metadata)));
701 tags = partition ? partition->tags : TAG_ARBITRARY;
703 /* Initialize trie contexts for find_match_wc(). */
704 for (int i = 0; i < cls->n_tries; i++) {
705 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
709 PVECTOR_FOR_EACH_PRIORITY(subtable, best_priority, 2,
710 sizeof(struct cls_subtable), &cls->subtables) {
711 struct cls_match *rule;
713 if (!tag_intersects(tags, subtable->tag)) {
717 rule = find_match_wc(subtable, flow, trie_ctx, cls->n_tries, wc);
718 if (rule && rule->priority > best_priority) {
719 best_priority = rule->priority;
724 return best ? best->cls_rule : NULL;
727 /* Finds and returns a rule in 'cls' with exactly the same priority and
728 * matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
729 * contain an exact match. */
731 classifier_find_rule_exactly(const struct classifier *cls,
732 const struct cls_rule *target)
733 OVS_EXCLUDED(cls->mutex)
735 struct cls_match *head, *rule;
736 struct cls_subtable *subtable;
738 ovs_mutex_lock(&cls->mutex);
739 subtable = find_subtable(cls, &target->match.mask);
744 /* Skip if there is no hope. */
745 if (target->priority > subtable->max_priority) {
749 head = find_equal(subtable, &target->match.flow,
750 miniflow_hash_in_minimask(&target->match.flow,
751 &target->match.mask, 0));
752 FOR_EACH_RULE_IN_LIST (rule, head) {
753 if (target->priority >= rule->priority) {
754 ovs_mutex_unlock(&cls->mutex);
755 return target->priority == rule->priority ? rule->cls_rule : NULL;
759 ovs_mutex_unlock(&cls->mutex);
763 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
764 * same matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
765 * contain an exact match. */
767 classifier_find_match_exactly(const struct classifier *cls,
768 const struct match *target, int priority)
770 struct cls_rule *retval;
773 cls_rule_init(&cr, target, priority);
774 retval = classifier_find_rule_exactly(cls, &cr);
775 cls_rule_destroy(&cr);
780 /* Checks if 'target' would overlap any other rule in 'cls'. Two rules are
781 * considered to overlap if both rules have the same priority and a packet
782 * could match both. */
784 classifier_rule_overlaps(const struct classifier *cls,
785 const struct cls_rule *target)
786 OVS_EXCLUDED(cls->mutex)
788 struct cls_subtable *subtable;
790 ovs_mutex_lock(&cls->mutex);
791 /* Iterate subtables in the descending max priority order. */
792 PVECTOR_FOR_EACH_PRIORITY (subtable, target->priority - 1, 2,
793 sizeof(struct cls_subtable), &cls->subtables) {
794 uint32_t storage[FLOW_U32S];
795 struct minimask mask;
796 struct cls_match *head;
798 minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
799 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
800 struct cls_match *rule;
802 FOR_EACH_RULE_IN_LIST (rule, head) {
803 if (rule->priority < target->priority) {
804 break; /* Rules in descending priority order. */
806 if (rule->priority == target->priority
807 && miniflow_equal_in_minimask(&target->match.flow,
808 &rule->flow, &mask)) {
809 ovs_mutex_unlock(&cls->mutex);
816 ovs_mutex_unlock(&cls->mutex);
820 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
821 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
822 * function returns true if, for every field:
824 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
827 * - 'criteria' wildcards the field,
829 * Conversely, 'rule' does not match 'criteria' and this function returns false
830 * if, for at least one field:
832 * - 'criteria' and 'rule' specify different values for the field, or
834 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
836 * Equivalently, the truth table for whether a field matches is:
841 * r +---------+---------+
842 * i wild | yes | yes |
844 * e +---------+---------+
845 * r exact | no |if values|
847 * a +---------+---------+
849 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
850 * commands and by OpenFlow 1.0 aggregate and flow stats.
852 * Ignores rule->priority. */
854 cls_rule_is_loose_match(const struct cls_rule *rule,
855 const struct minimatch *criteria)
857 return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
858 && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
865 rule_matches(const struct cls_match *rule, const struct cls_rule *target)
868 || miniflow_equal_in_minimask(&rule->flow,
870 &target->match.mask));
873 static struct cls_match *
874 search_subtable(const struct cls_subtable *subtable,
875 struct cls_cursor *cursor)
878 || !minimask_has_extra(&subtable->mask, &cursor->target->match.mask)) {
879 struct cls_match *rule;
881 CMAP_CURSOR_FOR_EACH (rule, cmap_node, &cursor->rules,
883 if (rule_matches(rule, cursor->target)) {
891 /* Initializes 'cursor' for iterating through rules in 'cls', and returns the
892 * first matching cls_rule via '*pnode', or NULL if there are no matches.
894 * - If 'target' is null, the cursor will visit every rule in 'cls'.
896 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
897 * such that cls_rule_is_loose_match(rule, target) returns true.
899 * Ignores target->priority. */
900 struct cls_cursor cls_cursor_start(const struct classifier *cls,
901 const struct cls_rule *target,
903 OVS_NO_THREAD_SAFETY_ANALYSIS
905 struct cls_cursor cursor;
906 struct cls_subtable *subtable;
910 cursor.target = target && !cls_rule_is_catchall(target) ? target : NULL;
913 /* Find first rule. */
914 ovs_mutex_lock(&cursor.cls->mutex);
915 CMAP_CURSOR_FOR_EACH (subtable, cmap_node, &cursor.subtables,
916 &cursor.cls->subtables_map) {
917 struct cls_match *rule = search_subtable(subtable, &cursor);
920 cursor.subtable = subtable;
921 cursor.rule = rule->cls_rule;
926 /* Leave locked if requested and have a rule. */
927 if (safe || !cursor.rule) {
928 ovs_mutex_unlock(&cursor.cls->mutex);
933 static struct cls_rule *
934 cls_cursor_next(struct cls_cursor *cursor)
935 OVS_NO_THREAD_SAFETY_ANALYSIS
937 struct cls_match *rule = cursor->rule->cls_match;
938 const struct cls_subtable *subtable;
939 struct cls_match *next;
941 next = next_rule_in_list__(rule);
942 if (next->priority < rule->priority) {
943 return next->cls_rule;
946 /* 'next' is the head of the list, that is, the rule that is included in
947 * the subtable's map. (This is important when the classifier contains
948 * rules that differ only in priority.) */
950 CMAP_CURSOR_FOR_EACH_CONTINUE (rule, cmap_node, &cursor->rules) {
951 if (rule_matches(rule, cursor->target)) {
952 return rule->cls_rule;
956 subtable = cursor->subtable;
957 CMAP_CURSOR_FOR_EACH_CONTINUE (subtable, cmap_node, &cursor->subtables) {
958 rule = search_subtable(subtable, cursor);
960 cursor->subtable = subtable;
961 return rule->cls_rule;
968 /* Sets 'cursor->rule' to the next matching cls_rule in 'cursor''s iteration,
969 * or to null if all matching rules have been visited. */
971 cls_cursor_advance(struct cls_cursor *cursor)
972 OVS_NO_THREAD_SAFETY_ANALYSIS
975 ovs_mutex_lock(&cursor->cls->mutex);
977 cursor->rule = cls_cursor_next(cursor);
978 if (cursor->safe || !cursor->rule) {
979 ovs_mutex_unlock(&cursor->cls->mutex);
983 static struct cls_subtable *
984 find_subtable(const struct classifier *cls, const struct minimask *mask)
985 OVS_REQUIRES(cls->mutex)
987 struct cls_subtable *subtable;
989 CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, minimask_hash(mask, 0),
990 &cls->subtables_map) {
991 if (minimask_equal(mask, &subtable->mask)) {
998 /* The new subtable will be visible to the readers only after this. */
999 static struct cls_subtable *
1000 insert_subtable(struct classifier *cls, const struct minimask *mask)
1001 OVS_REQUIRES(cls->mutex)
1003 uint32_t hash = minimask_hash(mask, 0);
1004 struct cls_subtable *subtable;
1006 struct flow_wildcards old, new;
1008 int count = count_1bits(mask->masks.map);
1010 subtable = xzalloc(sizeof *subtable - sizeof mask->masks.inline_values
1011 + MINIFLOW_VALUES_SIZE(count));
1012 cmap_init(&subtable->rules);
1013 miniflow_clone_inline(&subtable->mask.masks, &mask->masks, count);
1015 /* Init indices for segmented lookup, if any. */
1016 flow_wildcards_init_catchall(&new);
1019 for (i = 0; i < cls->n_flow_segments; i++) {
1020 flow_wildcards_fold_minimask_range(&new, mask, prev,
1021 cls->flow_segments[i]);
1022 /* Add an index if it adds mask bits. */
1023 if (!flow_wildcards_equal(&new, &old)) {
1024 cmap_init(&subtable->indices[index]);
1025 subtable->index_ofs[index] = cls->flow_segments[i];
1029 prev = cls->flow_segments[i];
1031 /* Check if the rest of the subtable's mask adds any bits,
1032 * and remove the last index if it doesn't. */
1034 flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U32S);
1035 if (flow_wildcards_equal(&new, &old)) {
1037 subtable->index_ofs[index] = 0;
1038 cmap_destroy(&subtable->indices[index]);
1041 subtable->n_indices = index;
1043 subtable->tag = (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1044 ? tag_create_deterministic(hash)
1047 for (i = 0; i < cls->n_tries; i++) {
1048 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1049 cls->tries[i].field);
1053 ovsrcu_set_hidden(&subtable->ports_trie, NULL);
1054 subtable->ports_mask_len
1055 = 32 - ctz32(ntohl(MINIFLOW_GET_BE32(&mask->masks, tp_src)));
1057 cmap_insert(&cls->subtables_map, &subtable->cmap_node, hash);
1063 destroy_subtable(struct classifier *cls, struct cls_subtable *subtable)
1064 OVS_REQUIRES(cls->mutex)
1068 pvector_remove(&cls->subtables, subtable);
1069 trie_destroy(&subtable->ports_trie);
1071 for (i = 0; i < subtable->n_indices; i++) {
1072 cmap_destroy(&subtable->indices[i]);
1074 cmap_remove(&cls->subtables_map, &subtable->cmap_node,
1075 minimask_hash(&subtable->mask, 0));
1076 minimask_destroy(&subtable->mask);
1077 cmap_destroy(&subtable->rules);
1078 ovsrcu_postpone(free, subtable);
1086 static unsigned int be_get_bit_at(const ovs_be32 value[], unsigned int ofs);
1088 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1089 * lookup results. */
1091 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1092 const unsigned int field_plen[CLS_MAX_TRIES],
1093 const struct range ofs, const struct flow *flow,
1094 struct flow_wildcards *wc)
1098 /* Check if we could avoid fully unwildcarding the next level of
1099 * fields using the prefix tries. The trie checks are done only as
1100 * needed to avoid folding in additional bits to the wildcards mask. */
1101 for (j = 0; j < n_tries; j++) {
1102 /* Is the trie field relevant for this subtable? */
1103 if (field_plen[j]) {
1104 struct trie_ctx *ctx = &trie_ctx[j];
1105 uint8_t be32ofs = ctx->be32ofs;
1107 /* Is the trie field within the current range of fields? */
1108 if (be32ofs >= ofs.start && be32ofs < ofs.end) {
1109 /* On-demand trie lookup. */
1110 if (!ctx->lookup_done) {
1111 memset(&ctx->match_plens, 0, sizeof ctx->match_plens);
1112 ctx->maskbits = trie_lookup(ctx->trie, flow,
1114 ctx->lookup_done = true;
1116 /* Possible to skip the rest of the subtable if subtable's
1117 * prefix on the field is not included in the lookup result. */
1118 if (!be_get_bit_at(&ctx->match_plens.be32, field_plen[j] - 1)) {
1119 /* We want the trie lookup to never result in unwildcarding
1120 * any bits that would not be unwildcarded otherwise.
1121 * Since the trie is shared by the whole classifier, it is
1122 * possible that the 'maskbits' contain bits that are
1123 * irrelevant for the partition relevant for the current
1124 * packet. Hence the checks below. */
1126 /* Check that the trie result will not unwildcard more bits
1127 * than this subtable would otherwise. */
1128 if (ctx->maskbits <= field_plen[j]) {
1129 /* Unwildcard the bits and skip the rest. */
1130 mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1131 /* Note: Prerequisite already unwildcarded, as the only
1132 * prerequisite of the supported trie lookup fields is
1133 * the ethertype, which is always unwildcarded. */
1136 /* Can skip if the field is already unwildcarded. */
1137 if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1147 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1148 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1149 * value has the correct value in 'target'.
1151 * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
1152 * target, mask) but this is faster because of the invariant that
1153 * flow->map and mask->masks.map are the same, and that this version
1154 * takes the 'wc'. */
1156 miniflow_and_mask_matches_flow(const struct miniflow *flow,
1157 const struct minimask *mask,
1158 const struct flow *target)
1160 const uint32_t *flowp = miniflow_get_u32_values(flow);
1161 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1164 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1165 uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & *maskp++;
1175 static inline struct cls_match *
1176 find_match(const struct cls_subtable *subtable, const struct flow *flow,
1179 struct cls_match *rule;
1181 CMAP_FOR_EACH_WITH_HASH (rule, cmap_node, hash, &subtable->rules) {
1182 if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
1191 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1192 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1193 * value has the correct value in 'target'.
1195 * This function is equivalent to miniflow_and_mask_matches_flow() but this
1196 * version fills in the mask bits in 'wc'. */
1198 miniflow_and_mask_matches_flow_wc(const struct miniflow *flow,
1199 const struct minimask *mask,
1200 const struct flow *target,
1201 struct flow_wildcards *wc)
1203 const uint32_t *flowp = miniflow_get_u32_values(flow);
1204 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1207 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1208 uint32_t mask = *maskp++;
1209 uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & mask;
1212 /* Only unwildcard if none of the differing bits is already
1214 if (!(flow_u32_value(&wc->masks, idx) & diff)) {
1215 /* Keep one bit of the difference. */
1216 *flow_u32_lvalue(&wc->masks, idx) |= rightmost_1bit(diff);
1220 /* Fill in the bits that were looked at. */
1221 *flow_u32_lvalue(&wc->masks, idx) |= mask;
1227 /* Unwildcard the fields looked up so far, if any. */
1229 fill_range_wc(const struct cls_subtable *subtable, struct flow_wildcards *wc,
1233 flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, to);
1237 static struct cls_match *
1238 find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
1239 struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1240 struct flow_wildcards *wc)
1242 uint32_t basis = 0, hash;
1243 struct cls_match *rule = NULL;
1247 if (OVS_UNLIKELY(!wc)) {
1248 return find_match(subtable, flow,
1249 flow_hash_in_minimask(flow, &subtable->mask, 0));
1253 /* Try to finish early by checking fields in segments. */
1254 for (i = 0; i < subtable->n_indices; i++) {
1255 const struct cmap_node *inode;
1257 ofs.end = subtable->index_ofs[i];
1259 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1261 /* 'wc' bits for the trie field set, now unwildcard the preceding
1262 * bits used so far. */
1263 fill_range_wc(subtable, wc, ofs.start);
1266 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1268 inode = cmap_find(&subtable->indices[i], hash);
1270 /* No match, can stop immediately, but must fold in the bits
1271 * used in lookup so far. */
1272 fill_range_wc(subtable, wc, ofs.end);
1276 /* If we have narrowed down to a single rule already, check whether
1277 * that rule matches. Either way, we're done.
1279 * (Rare) hash collisions may cause us to miss the opportunity for this
1281 if (!cmap_node_next(inode)) {
1282 ASSIGN_CONTAINER(rule, inode - i, index_nodes);
1283 if (miniflow_and_mask_matches_flow_wc(&rule->flow, &subtable->mask,
1289 ofs.start = ofs.end;
1291 ofs.end = FLOW_U32S;
1292 /* Trie check for the final range. */
1293 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1294 fill_range_wc(subtable, wc, ofs.start);
1297 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1299 rule = find_match(subtable, flow, hash);
1300 if (!rule && subtable->ports_mask_len) {
1301 /* Ports are always part of the final range, if any.
1302 * No match was found for the ports. Use the ports trie to figure out
1303 * which ports bits to unwildcard. */
1305 ovs_be32 value, plens, mask;
1307 mask = MINIFLOW_GET_BE32(&subtable->mask.masks, tp_src);
1308 value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
1309 mbits = trie_lookup_value(&subtable->ports_trie, &value, &plens, 32);
1311 ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
1312 mask & htonl(~0 << (32 - mbits));
1314 /* Unwildcard all bits in the mask upto the ports, as they were used
1315 * to determine there is no match. */
1316 fill_range_wc(subtable, wc, TP_PORTS_OFS32);
1320 /* Must unwildcard all the fields, as they were looked at. */
1321 flow_wildcards_fold_minimask(wc, &subtable->mask);
1325 static struct cls_match *
1326 find_equal(struct cls_subtable *subtable, const struct miniflow *flow,
1329 struct cls_match *head;
1331 CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1332 if (miniflow_equal(&head->flow, flow)) {
1340 * As the readers are operating concurrently with the modifications, a
1341 * concurrent reader may or may not see the new rule, depending on how
1342 * the concurrent events overlap with each other. This is no
1343 * different from the former locked behavior, but there the visibility
1344 * of the new rule only depended on the timing of the locking
1347 * The new rule is first added to the segment indices, so the readers
1348 * may find the rule in the indices before the rule is visible in the
1349 * subtables 'rules' map. This may result in us losing the
1350 * opportunity to quit lookups earlier, resulting in sub-optimal
1351 * wildcarding. This will be fixed by forthcoming revalidation always
1352 * scheduled after flow table changes.
1354 * Similar behavior may happen due to us removing the overlapping rule
1355 * (if any) from the indices only after the new rule has been added.
1357 * The subtable's max priority is updated only after the rule is
1358 * inserted, so the concurrent readers may not see the rule, as the
1359 * updated priority ordered subtable list will only be visible after
1360 * the subtable's max priority is updated.
1362 * Similarly, the classifier's partitions for new rules are updated by
1363 * the caller after this function, so the readers may keep skipping
1364 * the subtable until they see the updated partitions.
1366 static struct cls_match *
1367 insert_rule(struct classifier *cls, struct cls_subtable *subtable,
1368 struct cls_rule *new_rule)
1369 OVS_REQUIRES(cls->mutex)
1371 struct cls_match *old = NULL;
1372 struct cls_match *new = cls_match_alloc(new_rule);
1373 struct cls_match *head;
1375 uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
1376 uint8_t prev_be32ofs = 0;
1378 /* Add new node to segment indices. */
1379 for (i = 0; i < subtable->n_indices; i++) {
1380 ihash[i] = minimatch_hash_range(&new_rule->match, prev_be32ofs,
1381 subtable->index_ofs[i], &basis);
1382 cmap_insert(&subtable->indices[i], &new->index_nodes[i], ihash[i]);
1383 prev_be32ofs = subtable->index_ofs[i];
1385 hash = minimatch_hash_range(&new_rule->match, prev_be32ofs, FLOW_U32S,
1387 head = find_equal(subtable, &new_rule->match.flow, hash);
1389 cmap_insert(&subtable->rules, &new->cmap_node, hash);
1390 list_init(&new->list);
1393 /* Scan the list for the insertion point that will keep the list in
1394 * order of decreasing priority. */
1395 struct cls_match *rule;
1397 FOR_EACH_RULE_IN_LIST (rule, head) {
1398 if (new->priority >= rule->priority) {
1400 /* 'new' is the new highest-priority flow in the list. */
1401 cmap_replace(&subtable->rules, &rule->cmap_node,
1402 &new->cmap_node, hash);
1405 if (new->priority == rule->priority) {
1406 list_replace(&new->list, &rule->list);
1409 list_insert(&rule->list, &new->list);
1415 /* Insert 'new' at the end of the list. */
1416 list_push_back(&head->list, &new->list);
1421 subtable->n_rules++;
1423 /* Rule was added, not replaced. Update 'subtable's 'max_priority'
1424 * and 'max_count', if necessary. */
1425 if (subtable->n_rules == 1) {
1426 subtable->max_priority = new->priority;
1427 subtable->max_count = 1;
1428 pvector_insert(&cls->subtables, subtable, new->priority);
1429 } else if (subtable->max_priority == new->priority) {
1430 ++subtable->max_count;
1431 } else if (new->priority > subtable->max_priority) {
1432 subtable->max_priority = new->priority;
1433 subtable->max_count = 1;
1434 pvector_change_priority(&cls->subtables, subtable, new->priority);
1437 /* Remove old node from indices. */
1438 for (i = 0; i < subtable->n_indices; i++) {
1439 cmap_remove(&subtable->indices[i], &old->index_nodes[i], ihash[i]);
1445 static struct cls_match *
1446 next_rule_in_list__(struct cls_match *rule)
1447 OVS_NO_THREAD_SAFETY_ANALYSIS
1449 struct cls_match *next = NULL;
1450 next = OBJECT_CONTAINING(rule->list.next, next, list);
1454 static struct cls_match *
1455 next_rule_in_list(struct cls_match *rule)
1457 struct cls_match *next = next_rule_in_list__(rule);
1458 return next->priority < rule->priority ? next : NULL;
1461 /* A longest-prefix match tree. */
1463 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1464 * Prefixes are in the network byte order, and the offset 0 corresponds to
1465 * the most significant bit of the first byte. The offset can be read as
1466 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1468 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1472 pr += ofs / 32; /* Where to start. */
1473 ofs %= 32; /* How many bits to skip at 'pr'. */
1475 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1476 if (plen > 32 - ofs) { /* Need more than we have already? */
1477 prefix |= ntohl(*++pr) >> (32 - ofs);
1479 /* Return with possible unwanted bits at the end. */
1483 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1484 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1485 * corresponds to the most significant bit of the first byte. The offset can
1486 * be read as "how many bits to skip from the start of the prefix starting at
1489 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1494 if (plen > TRIE_PREFIX_BITS) {
1495 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1497 /* Return with unwanted bits cleared. */
1498 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1501 /* Return the number of equal bits in 'n_bits' of 'prefix's MSBs and a 'value'
1502 * starting at "MSB 0"-based offset 'ofs'. */
1504 prefix_equal_bits(uint32_t prefix, unsigned int n_bits, const ovs_be32 value[],
1507 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, n_bits);
1508 /* Set the bit after the relevant bits to limit the result. */
1509 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - n_bits));
1512 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1513 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1515 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1516 unsigned int ofs, unsigned int plen)
1518 return prefix_equal_bits(node->prefix, MIN(node->n_bits, plen - ofs),
1522 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1523 * be greater than 31. */
1525 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1527 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1530 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1531 * be between 0 and 31, inclusive. */
1533 get_bit_at(const uint32_t prefix, unsigned int ofs)
1535 return (prefix >> (31 - ofs)) & 1u;
1538 /* Create new branch. */
1539 static struct trie_node *
1540 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1541 unsigned int n_rules)
1543 struct trie_node *node = xmalloc(sizeof *node);
1545 node->prefix = trie_get_prefix(prefix, ofs, plen);
1547 if (plen <= TRIE_PREFIX_BITS) {
1548 node->n_bits = plen;
1549 ovsrcu_set_hidden(&node->edges[0], NULL);
1550 ovsrcu_set_hidden(&node->edges[1], NULL);
1551 node->n_rules = n_rules;
1552 } else { /* Need intermediate nodes. */
1553 struct trie_node *subnode = trie_branch_create(prefix,
1554 ofs + TRIE_PREFIX_BITS,
1555 plen - TRIE_PREFIX_BITS,
1557 int bit = get_bit_at(subnode->prefix, 0);
1558 node->n_bits = TRIE_PREFIX_BITS;
1559 ovsrcu_set_hidden(&node->edges[bit], subnode);
1560 ovsrcu_set_hidden(&node->edges[!bit], NULL);
1567 trie_node_destroy(const struct trie_node *node)
1569 ovsrcu_postpone(free, CONST_CAST(struct trie_node *, node));
1572 /* Copy a trie node for modification and postpone delete the old one. */
1573 static struct trie_node *
1574 trie_node_rcu_realloc(const struct trie_node *node)
1576 struct trie_node *new_node = xmalloc(sizeof *node);
1579 trie_node_destroy(node);
1584 /* May only be called while holding the classifier mutex. */
1586 trie_destroy(rcu_trie_ptr *trie)
1588 struct trie_node *node = ovsrcu_get_protected(struct trie_node *, trie);
1591 ovsrcu_set_hidden(trie, NULL);
1592 trie_destroy(&node->edges[0]);
1593 trie_destroy(&node->edges[1]);
1594 trie_node_destroy(node);
1599 trie_is_leaf(const struct trie_node *trie)
1602 return !ovsrcu_get(struct trie_node *, &trie->edges[0])
1603 && !ovsrcu_get(struct trie_node *, &trie->edges[1]);
1607 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1608 unsigned int n_bits)
1610 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1613 for (i = 0; i < n_bits / 32; i++) {
1614 mask[i] = OVS_BE32_MAX;
1617 mask[i] |= htonl(~0u << (32 - n_bits % 32));
1622 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
1623 unsigned int n_bits)
1625 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1627 ovs_be32 zeroes = 0;
1629 for (i = 0; i < n_bits / 32; i++) {
1633 zeroes |= ~mask[i] & htonl(~0u << (32 - n_bits % 32));
1636 return !zeroes; /* All 'n_bits' bits set. */
1639 static rcu_trie_ptr *
1640 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
1643 return node->edges + be_get_bit_at(value, ofs);
1646 static const struct trie_node *
1647 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
1650 return ovsrcu_get(struct trie_node *,
1651 &node->edges[be_get_bit_at(value, ofs)]);
1654 /* Set the bit at ("MSB 0"-based) offset 'ofs'. 'ofs' can be greater than 31.
1657 be_set_bit_at(ovs_be32 value[], unsigned int ofs)
1659 ((uint8_t *)value)[ofs / 8] |= 1u << (7 - ofs % 8);
1662 /* Returns the number of bits in the prefix mask necessary to determine a
1663 * mismatch, in case there are longer prefixes in the tree below the one that
1665 * '*plens' will have a bit set for each prefix length that may have matching
1666 * rules. The caller is responsible for clearing the '*plens' prior to
1670 trie_lookup_value(const rcu_trie_ptr *trie, const ovs_be32 value[],
1671 ovs_be32 plens[], unsigned int n_bits)
1673 const struct trie_node *prev = NULL;
1674 const struct trie_node *node = ovsrcu_get(struct trie_node *, trie);
1675 unsigned int match_len = 0; /* Number of matching bits. */
1677 for (; node; prev = node, node = trie_next_node(node, value, match_len)) {
1678 unsigned int eqbits;
1679 /* Check if this edge can be followed. */
1680 eqbits = prefix_equal_bits(node->prefix, node->n_bits, value,
1682 match_len += eqbits;
1683 if (eqbits < node->n_bits) { /* Mismatch, nothing more to be found. */
1684 /* Bit at offset 'match_len' differed. */
1685 return match_len + 1; /* Includes the first mismatching bit. */
1687 /* Full match, check if rules exist at this prefix length. */
1688 if (node->n_rules > 0) {
1689 be_set_bit_at(plens, match_len - 1);
1691 if (match_len >= n_bits) {
1692 return n_bits; /* Full prefix. */
1695 /* node == NULL. Full match so far, but we tried to follow an
1696 * non-existing branch. Need to exclude the other branch if it exists
1697 * (it does not if we were called on an empty trie or 'prev' is a leaf
1699 return !prev || trie_is_leaf(prev) ? match_len : match_len + 1;
1703 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
1704 union mf_value *plens)
1706 const struct mf_field *mf = trie->field;
1708 /* Check that current flow matches the prerequisites for the trie
1709 * field. Some match fields are used for multiple purposes, so we
1710 * must check that the trie is relevant for this flow. */
1711 if (mf_are_prereqs_ok(mf, flow)) {
1712 return trie_lookup_value(&trie->root,
1713 &((ovs_be32 *)flow)[mf->flow_be32ofs],
1714 &plens->be32, mf->n_bits);
1716 memset(plens, 0xff, sizeof *plens); /* All prefixes, no skipping. */
1717 return 0; /* Value not used in this case. */
1720 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
1721 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
1722 * 'miniflow_index' is not NULL. */
1724 minimask_get_prefix_len(const struct minimask *minimask,
1725 const struct mf_field *mf)
1727 unsigned int n_bits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
1728 uint8_t u32_ofs = mf->flow_be32ofs;
1729 uint8_t u32_end = u32_ofs + mf->n_bytes / 4;
1731 for (; u32_ofs < u32_end; ++u32_ofs) {
1733 mask = ntohl((OVS_FORCE ovs_be32)minimask_get(minimask, u32_ofs));
1735 /* Validate mask, count the mask length. */
1738 return 0; /* No bits allowed after mask ended. */
1741 if (~mask & (~mask + 1)) {
1742 return 0; /* Mask not contiguous. */
1744 mask_tz = ctz32(mask);
1745 n_bits += 32 - mask_tz;
1753 * This is called only when mask prefix is known to be CIDR and non-zero.
1754 * Relies on the fact that the flow and mask have the same map, and since
1755 * the mask is CIDR, the storage for the flow field exists even if it
1756 * happened to be zeros.
1758 static const ovs_be32 *
1759 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
1761 return miniflow_get_be32_values(&match->flow) +
1762 count_1bits(match->flow.map & ((UINT64_C(1) << mf->flow_be32ofs) - 1));
1765 /* Insert rule in to the prefix tree.
1766 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1769 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1771 trie_insert_prefix(&trie->root,
1772 minimatch_get_prefix(&rule->match, trie->field), mlen);
1776 trie_insert_prefix(rcu_trie_ptr *edge, const ovs_be32 *prefix, int mlen)
1778 struct trie_node *node;
1781 /* Walk the tree. */
1782 for (; (node = ovsrcu_get_protected(struct trie_node *, edge));
1783 edge = trie_next_edge(node, prefix, ofs)) {
1784 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1786 if (eqbits < node->n_bits) {
1787 /* Mismatch, new node needs to be inserted above. */
1788 int old_branch = get_bit_at(node->prefix, eqbits);
1789 struct trie_node *new_parent;
1791 new_parent = trie_branch_create(prefix, ofs - eqbits, eqbits,
1792 ofs == mlen ? 1 : 0);
1793 /* Copy the node to modify it. */
1794 node = trie_node_rcu_realloc(node);
1795 /* Adjust the new node for its new position in the tree. */
1796 node->prefix <<= eqbits;
1797 node->n_bits -= eqbits;
1798 ovsrcu_set_hidden(&new_parent->edges[old_branch], node);
1800 /* Check if need a new branch for the new rule. */
1802 ovsrcu_set_hidden(&new_parent->edges[!old_branch],
1803 trie_branch_create(prefix, ofs, mlen - ofs,
1806 ovsrcu_set(edge, new_parent); /* Publish changes. */
1809 /* Full match so far. */
1812 /* Full match at the current node, rule needs to be added here. */
1817 /* Must insert a new tree branch for the new rule. */
1818 ovsrcu_set(edge, trie_branch_create(prefix, ofs, mlen - ofs, 1));
1821 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1824 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1826 trie_remove_prefix(&trie->root,
1827 minimatch_get_prefix(&rule->match, trie->field), mlen);
1830 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1833 trie_remove_prefix(rcu_trie_ptr *root, const ovs_be32 *prefix, int mlen)
1835 struct trie_node *node;
1836 rcu_trie_ptr *edges[sizeof(union mf_value) * 8];
1837 int depth = 0, ofs = 0;
1839 /* Walk the tree. */
1840 for (edges[0] = root;
1841 (node = ovsrcu_get_protected(struct trie_node *, edges[depth]));
1842 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
1843 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1845 if (eqbits < node->n_bits) {
1846 /* Mismatch, nothing to be removed. This should never happen, as
1847 * only rules in the classifier are ever removed. */
1848 break; /* Log a warning. */
1850 /* Full match so far. */
1854 /* Full prefix match at the current node, remove rule here. */
1855 if (!node->n_rules) {
1856 break; /* Log a warning. */
1860 /* Check if can prune the tree. */
1861 while (!node->n_rules) {
1862 struct trie_node *next,
1863 *edge0 = ovsrcu_get_protected(struct trie_node *,
1865 *edge1 = ovsrcu_get_protected(struct trie_node *,
1868 if (edge0 && edge1) {
1869 break; /* A branching point, cannot prune. */
1872 /* Else have at most one child node, remove this node. */
1873 next = edge0 ? edge0 : edge1;
1876 if (node->n_bits + next->n_bits > TRIE_PREFIX_BITS) {
1877 break; /* Cannot combine. */
1879 next = trie_node_rcu_realloc(next); /* Modify. */
1881 /* Combine node with next. */
1882 next->prefix = node->prefix | next->prefix >> node->n_bits;
1883 next->n_bits += node->n_bits;
1885 /* Update the parent's edge. */
1886 ovsrcu_set(edges[depth], next); /* Publish changes. */
1887 trie_node_destroy(node);
1889 if (next || !depth) {
1890 /* Branch not pruned or at root, nothing more to do. */
1893 node = ovsrcu_get_protected(struct trie_node *,
1899 /* Cannot go deeper. This should never happen, since only rules
1900 * that actually exist in the classifier are ever removed. */
1901 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");