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 static inline struct cls_match *
75 next_rule_in_list__(struct cls_match *rule)
76 OVS_NO_THREAD_SAFETY_ANALYSIS
78 struct cls_match *next = NULL;
79 next = OBJECT_CONTAINING(rculist_next(&rule->list), next, list);
83 static inline struct cls_match *
84 next_rule_in_list(struct cls_match *rule)
86 struct cls_match *next = next_rule_in_list__(rule);
87 return next->priority < rule->priority ? next : NULL;
90 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list.
91 * Classifier's mutex must be held while iterating, as the list is
92 * protoceted by it. */
93 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD) \
94 for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
95 #define FOR_EACH_RULE_IN_LIST_SAFE(RULE, NEXT, HEAD) \
96 for ((RULE) = (HEAD); \
97 (RULE) != NULL && ((NEXT) = next_rule_in_list(RULE), true); \
100 static struct cls_match *next_rule_in_list__(struct cls_match *);
101 static struct cls_match *next_rule_in_list(struct cls_match *);
103 static unsigned int minimask_get_prefix_len(const struct minimask *,
104 const struct mf_field *);
105 static void trie_init(struct classifier *cls, int trie_idx,
106 const struct mf_field *)
107 OVS_REQUIRES(cls->mutex);
108 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
109 union mf_value *plens);
110 static unsigned int trie_lookup_value(const rcu_trie_ptr *,
111 const ovs_be32 value[], ovs_be32 plens[],
112 unsigned int value_bits);
113 static void trie_destroy(rcu_trie_ptr *);
114 static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
115 static void trie_insert_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
117 static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
118 static void trie_remove_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
120 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
121 unsigned int n_bits);
122 static bool mask_prefix_bits_set(const struct flow_wildcards *,
123 uint8_t be32ofs, unsigned int n_bits);
127 /* Initializes 'rule' to match packets specified by 'match' at the given
128 * 'priority'. 'match' must satisfy the invariant described in the comment at
129 * the definition of struct match.
131 * The caller must eventually destroy 'rule' with cls_rule_destroy().
133 * Clients should not use priority INT_MIN. (OpenFlow uses priorities between
134 * 0 and UINT16_MAX, inclusive.) */
136 cls_rule_init(struct cls_rule *rule, const struct match *match, int priority)
138 minimatch_init(&rule->match, match);
139 rule->priority = priority;
140 rule->cls_match = NULL;
143 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
145 cls_rule_init_from_minimatch(struct cls_rule *rule,
146 const struct minimatch *match, int priority)
148 minimatch_clone(&rule->match, match);
149 rule->priority = priority;
150 rule->cls_match = NULL;
153 /* Initializes 'dst' as a copy of 'src'.
155 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
157 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
159 minimatch_clone(&dst->match, &src->match);
160 dst->priority = src->priority;
161 dst->cls_match = NULL;
164 /* Initializes 'dst' with the data in 'src', destroying 'src'.
166 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
168 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
170 minimatch_move(&dst->match, &src->match);
171 dst->priority = src->priority;
172 dst->cls_match = NULL;
175 /* Frees memory referenced by 'rule'. Doesn't free 'rule' itself (it's
176 * normally embedded into a larger structure).
178 * ('rule' must not currently be in a classifier.) */
180 cls_rule_destroy(struct cls_rule *rule)
182 ovs_assert(!rule->cls_match);
183 minimatch_destroy(&rule->match);
186 /* Returns true if 'a' and 'b' match the same packets at the same priority,
187 * false if they differ in some way. */
189 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
191 return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
194 /* Returns a hash value for 'rule', folding in 'basis'. */
196 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
198 return minimatch_hash(&rule->match, hash_int(rule->priority, basis));
201 /* Appends a string describing 'rule' to 's'. */
203 cls_rule_format(const struct cls_rule *rule, struct ds *s)
205 minimatch_format(&rule->match, s, rule->priority);
208 /* Returns true if 'rule' matches every packet, false otherwise. */
210 cls_rule_is_catchall(const struct cls_rule *rule)
212 return minimask_is_catchall(&rule->match.mask);
215 /* Initializes 'cls' as a classifier that initially contains no classification
218 classifier_init(struct classifier *cls, const uint8_t *flow_segments)
219 OVS_EXCLUDED(cls->mutex)
221 ovs_mutex_init(&cls->mutex);
222 ovs_mutex_lock(&cls->mutex);
224 cmap_init(&cls->subtables_map);
225 pvector_init(&cls->subtables);
226 cmap_init(&cls->partitions);
227 cls->n_flow_segments = 0;
229 while (cls->n_flow_segments < CLS_MAX_INDICES
230 && *flow_segments < FLOW_U32S) {
231 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
235 for (int i = 0; i < CLS_MAX_TRIES; i++) {
236 trie_init(cls, i, NULL);
238 ovs_mutex_unlock(&cls->mutex);
241 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
242 * caller's responsibility.
243 * May only be called after all the readers have been terminated. */
245 classifier_destroy(struct classifier *cls)
246 OVS_EXCLUDED(cls->mutex)
249 struct cls_partition *partition;
250 struct cls_subtable *subtable;
253 ovs_mutex_lock(&cls->mutex);
254 for (i = 0; i < cls->n_tries; i++) {
255 trie_destroy(&cls->tries[i].root);
258 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
259 destroy_subtable(cls, subtable);
261 cmap_destroy(&cls->subtables_map);
263 CMAP_FOR_EACH (partition, cmap_node, &cls->partitions) {
264 ovsrcu_postpone(free, partition);
266 cmap_destroy(&cls->partitions);
268 pvector_destroy(&cls->subtables);
269 ovs_mutex_unlock(&cls->mutex);
270 ovs_mutex_destroy(&cls->mutex);
274 /* Set the fields for which prefix lookup should be performed. */
276 classifier_set_prefix_fields(struct classifier *cls,
277 const enum mf_field_id *trie_fields,
278 unsigned int n_fields)
279 OVS_EXCLUDED(cls->mutex)
281 const struct mf_field * new_fields[CLS_MAX_TRIES];
282 struct mf_bitmap fields = MF_BITMAP_INITIALIZER;
284 bool changed = false;
286 ovs_mutex_lock(&cls->mutex);
287 for (i = 0; i < n_fields && n_tries < CLS_MAX_TRIES; i++) {
288 const struct mf_field *field = mf_from_id(trie_fields[i]);
289 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
290 /* Incompatible field. This is the only place where we
291 * enforce these requirements, but the rest of the trie code
292 * depends on the flow_be32ofs to be non-negative and the
293 * field length to be a multiple of 32 bits. */
297 if (bitmap_is_set(fields.bm, trie_fields[i])) {
298 /* Duplicate field, there is no need to build more than
299 * one index for any one field. */
302 bitmap_set1(fields.bm, trie_fields[i]);
304 new_fields[n_tries] = NULL;
305 if (n_tries >= cls->n_tries || field != cls->tries[n_tries].field) {
306 new_fields[n_tries] = field;
312 if (changed || n_tries < cls->n_tries) {
313 struct cls_subtable *subtable;
315 /* Trie configuration needs to change. Disable trie lookups
316 * for the tries that are changing and wait all the current readers
317 * with the old configuration to be done. */
319 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
320 for (i = 0; i < cls->n_tries; i++) {
321 if ((i < n_tries && new_fields[i]) || i >= n_tries) {
322 if (subtable->trie_plen[i]) {
323 subtable->trie_plen[i] = 0;
329 /* Synchronize if any readers were using tries. The readers may
330 * temporarily function without the trie lookup based optimizations. */
332 /* ovsrcu_synchronize() functions as a memory barrier, so it does
333 * not matter that subtable->trie_plen is not atomic. */
334 ovsrcu_synchronize();
337 /* Now set up the tries. */
338 for (i = 0; i < n_tries; i++) {
340 trie_init(cls, i, new_fields[i]);
343 /* Destroy the rest, if any. */
344 for (; i < cls->n_tries; i++) {
345 trie_init(cls, i, NULL);
348 cls->n_tries = n_tries;
349 ovs_mutex_unlock(&cls->mutex);
353 ovs_mutex_unlock(&cls->mutex);
354 return false; /* No change. */
358 trie_init(struct classifier *cls, int trie_idx, const struct mf_field *field)
359 OVS_REQUIRES(cls->mutex)
361 struct cls_trie *trie = &cls->tries[trie_idx];
362 struct cls_subtable *subtable;
364 if (trie_idx < cls->n_tries) {
365 trie_destroy(&trie->root);
367 ovsrcu_set_hidden(&trie->root, NULL);
371 /* Add existing rules to the new trie. */
372 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
375 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
377 struct cls_match *head;
379 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
380 struct cls_match *match;
382 FOR_EACH_RULE_IN_LIST (match, head) {
383 trie_insert(trie, match->cls_rule, plen);
387 /* Initialize subtable's prefix length on this field. This will
388 * allow readers to use the trie. */
389 atomic_thread_fence(memory_order_release);
390 subtable->trie_plen[trie_idx] = plen;
394 /* Returns true if 'cls' contains no classification rules, false otherwise.
395 * Checking the cmap requires no locking. */
397 classifier_is_empty(const struct classifier *cls)
399 return cmap_is_empty(&cls->subtables_map);
402 /* Returns the number of rules in 'cls'. */
404 classifier_count(const struct classifier *cls)
405 OVS_NO_THREAD_SAFETY_ANALYSIS
407 /* n_rules is an int, so in the presence of concurrent writers this will
408 * return either the old or a new value. */
413 hash_metadata(ovs_be64 metadata_)
415 uint64_t metadata = (OVS_FORCE uint64_t) metadata_;
416 return hash_uint64(metadata);
419 static struct cls_partition *
420 find_partition(const struct classifier *cls, ovs_be64 metadata, uint32_t hash)
422 struct cls_partition *partition;
424 CMAP_FOR_EACH_WITH_HASH (partition, cmap_node, hash, &cls->partitions) {
425 if (partition->metadata == metadata) {
433 static struct cls_partition *
434 create_partition(struct classifier *cls, struct cls_subtable *subtable,
436 OVS_REQUIRES(cls->mutex)
438 uint32_t hash = hash_metadata(metadata);
439 struct cls_partition *partition = find_partition(cls, metadata, hash);
441 partition = xmalloc(sizeof *partition);
442 partition->metadata = metadata;
444 tag_tracker_init(&partition->tracker);
445 cmap_insert(&cls->partitions, &partition->cmap_node, hash);
447 tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
451 static inline ovs_be32 minimatch_get_ports(const struct minimatch *match)
453 /* Could optimize to use the same map if needed for fast path. */
454 return MINIFLOW_GET_BE32(&match->flow, tp_src)
455 & MINIFLOW_GET_BE32(&match->mask.masks, tp_src);
458 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
459 * must not modify or free it.
461 * If 'cls' already contains an identical rule (including wildcards, values of
462 * fixed fields, and priority), replaces the old rule by 'rule' and returns the
463 * rule that was replaced. The caller takes ownership of the returned rule and
464 * is thus responsible for destroying it with cls_rule_destroy(), freeing the
465 * memory block in which it resides, etc., as necessary.
467 * Returns NULL if 'cls' does not contain a rule with an identical key, after
468 * inserting the new rule. In this case, no rules are displaced by the new
469 * rule, even rules that cannot have any effect because the new rule matches a
470 * superset of their flows and has higher priority. */
472 classifier_replace(struct classifier *cls, struct cls_rule *rule)
473 OVS_EXCLUDED(cls->mutex)
475 struct cls_match *old_rule;
476 struct cls_subtable *subtable;
477 struct cls_rule *old_cls_rule = NULL;
479 ovs_mutex_lock(&cls->mutex);
480 subtable = find_subtable(cls, &rule->match.mask);
482 subtable = insert_subtable(cls, &rule->match.mask);
485 old_rule = insert_rule(cls, subtable, rule);
489 rule->cls_match->partition = NULL;
490 if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
491 ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
492 rule->cls_match->partition = create_partition(cls, subtable,
498 for (int i = 0; i < cls->n_tries; i++) {
499 if (subtable->trie_plen[i]) {
500 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
505 if (subtable->ports_mask_len) {
506 /* We mask the value to be inserted to always have the wildcarded
507 * bits in known (zero) state, so we can include them in comparison
508 * and they will always match (== their original value does not
510 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
512 trie_insert_prefix(&subtable->ports_trie, &masked_ports,
513 subtable->ports_mask_len);
516 old_cls_rule = old_rule->cls_rule;
517 rule->cls_match->partition = old_rule->partition;
518 old_cls_rule->cls_match = NULL;
520 /* 'old_rule' contains a cmap_node, which may not be freed
522 ovsrcu_postpone(free, old_rule);
524 ovs_mutex_unlock(&cls->mutex);
528 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
529 * must not modify or free it.
531 * 'cls' must not contain an identical rule (including wildcards, values of
532 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
535 classifier_insert(struct classifier *cls, struct cls_rule *rule)
537 struct cls_rule *displaced_rule = classifier_replace(cls, rule);
538 ovs_assert(!displaced_rule);
541 /* Removes 'rule' from 'cls'. It is the caller's responsibility to destroy
542 * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
543 * resides, etc., as necessary.
545 * Does nothing if 'rule' has been already removed, or was never inserted.
547 * Returns the removed rule, or NULL, if it was already removed.
550 classifier_remove(struct classifier *cls, struct cls_rule *rule)
551 OVS_EXCLUDED(cls->mutex)
553 struct cls_partition *partition;
554 struct cls_match *cls_match;
555 struct cls_match *head;
556 struct cls_subtable *subtable;
558 uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
559 uint8_t prev_be32ofs = 0;
561 ovs_mutex_lock(&cls->mutex);
562 cls_match = rule->cls_match;
565 goto unlock; /* Already removed. */
568 subtable = find_subtable(cls, &rule->match.mask);
569 ovs_assert(subtable);
571 if (subtable->ports_mask_len) {
572 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
574 trie_remove_prefix(&subtable->ports_trie,
575 &masked_ports, subtable->ports_mask_len);
577 for (i = 0; i < cls->n_tries; i++) {
578 if (subtable->trie_plen[i]) {
579 trie_remove(&cls->tries[i], rule, subtable->trie_plen[i]);
583 /* Remove rule node from indices. */
584 for (i = 0; i < subtable->n_indices; i++) {
585 ihash[i] = minimatch_hash_range(&rule->match, prev_be32ofs,
586 subtable->index_ofs[i], &basis);
587 cmap_remove(&subtable->indices[i], &cls_match->index_nodes[i],
589 prev_be32ofs = subtable->index_ofs[i];
591 hash = minimatch_hash_range(&rule->match, prev_be32ofs, FLOW_U32S, &basis);
593 head = find_equal(subtable, &rule->match.flow, hash);
594 if (head != cls_match) {
595 rculist_remove(&cls_match->list);
596 } else if (rculist_is_empty(&cls_match->list)) {
597 cmap_remove(&subtable->rules, &cls_match->cmap_node, hash);
599 struct cls_match *next = next_rule_in_list(cls_match);
601 rculist_remove(&cls_match->list);
602 cmap_replace(&subtable->rules, &cls_match->cmap_node,
603 &next->cmap_node, hash);
606 partition = cls_match->partition;
608 tag_tracker_subtract(&partition->tracker, &partition->tags,
610 if (!partition->tags) {
611 cmap_remove(&cls->partitions, &partition->cmap_node,
612 hash_metadata(partition->metadata));
613 ovsrcu_postpone(free, partition);
617 if (--subtable->n_rules == 0) {
618 destroy_subtable(cls, subtable);
619 } else if (subtable->max_priority == cls_match->priority
620 && --subtable->max_count == 0) {
621 /* Find the new 'max_priority' and 'max_count'. */
622 struct cls_match *head;
623 int max_priority = INT_MIN;
625 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
626 if (head->priority > max_priority) {
627 max_priority = head->priority;
628 subtable->max_count = 1;
629 } else if (head->priority == max_priority) {
630 ++subtable->max_count;
633 subtable->max_priority = max_priority;
634 pvector_change_priority(&cls->subtables, subtable, max_priority);
639 ovsrcu_postpone(free, cls_match);
640 rule->cls_match = NULL;
642 ovs_mutex_unlock(&cls->mutex);
647 /* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
648 * subtables which have a prefix match on the trie field, but whose prefix
649 * length is not indicated in 'match_plens'. For example, a subtable that
650 * has a 8-bit trie field prefix match can be skipped if
651 * !be_get_bit_at(&match_plens, 8 - 1). If skipped, 'maskbits' prefix bits
652 * must be unwildcarded to make datapath flow only match packets it should. */
654 const struct cls_trie *trie;
655 bool lookup_done; /* Status of the lookup. */
656 uint8_t be32ofs; /* U32 offset of the field in question. */
657 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
658 union mf_value match_plens; /* Bitmask of prefix lengths with possible
663 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
666 ctx->be32ofs = trie->field->flow_be32ofs;
667 ctx->lookup_done = false;
670 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
671 * Returns a null pointer if no rules in 'cls' match 'flow'. If multiple rules
672 * of equal priority match 'flow', returns one arbitrarily.
674 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
675 * set of bits that were significant in the lookup. At some point
676 * earlier, 'wc' should have been initialized (e.g., by
677 * flow_wildcards_init_catchall()). */
679 classifier_lookup(const struct classifier *cls, const struct flow *flow,
680 struct flow_wildcards *wc)
682 const struct cls_partition *partition;
684 int best_priority = INT_MIN;
685 const struct cls_match *best;
686 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
687 struct cls_subtable *subtable;
689 /* Synchronize for cls->n_tries and subtable->trie_plen. They can change
690 * when table configuration changes, which happens typically only on
692 atomic_thread_fence(memory_order_acquire);
694 /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
695 * then 'flow' cannot possibly match in 'subtable':
697 * - If flow->metadata maps to a given 'partition', then we can use
698 * 'tags' for 'partition->tags'.
700 * - If flow->metadata has no partition, then no rule in 'cls' has an
701 * exact-match for flow->metadata. That means that we don't need to
702 * search any subtable that includes flow->metadata in its mask.
704 * In either case, we always need to search any cls_subtables that do not
705 * include flow->metadata in its mask. One way to do that would be to
706 * check the "cls_subtable"s explicitly for that, but that would require an
707 * extra branch per subtable. Instead, we mark such a cls_subtable's
708 * 'tags' as TAG_ALL and make sure that 'tags' is never empty. This means
709 * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
710 * need a special case.
712 partition = (cmap_is_empty(&cls->partitions)
714 : find_partition(cls, flow->metadata,
715 hash_metadata(flow->metadata)));
716 tags = partition ? partition->tags : TAG_ARBITRARY;
718 /* Initialize trie contexts for find_match_wc(). */
719 for (int i = 0; i < cls->n_tries; i++) {
720 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
724 PVECTOR_FOR_EACH_PRIORITY(subtable, best_priority, 2,
725 sizeof(struct cls_subtable), &cls->subtables) {
726 struct cls_match *rule;
728 if (!tag_intersects(tags, subtable->tag)) {
732 rule = find_match_wc(subtable, flow, trie_ctx, cls->n_tries, wc);
733 if (rule && rule->priority > best_priority) {
734 best_priority = rule->priority;
739 return best ? best->cls_rule : NULL;
742 /* Finds and returns a rule in 'cls' with exactly the same priority and
743 * matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
744 * contain an exact match. */
746 classifier_find_rule_exactly(const struct classifier *cls,
747 const struct cls_rule *target)
748 OVS_EXCLUDED(cls->mutex)
750 struct cls_match *head, *rule;
751 struct cls_subtable *subtable;
753 ovs_mutex_lock(&cls->mutex);
754 subtable = find_subtable(cls, &target->match.mask);
759 /* Skip if there is no hope. */
760 if (target->priority > subtable->max_priority) {
764 head = find_equal(subtable, &target->match.flow,
765 miniflow_hash_in_minimask(&target->match.flow,
766 &target->match.mask, 0));
767 FOR_EACH_RULE_IN_LIST (rule, head) {
768 if (target->priority >= rule->priority) {
769 ovs_mutex_unlock(&cls->mutex);
770 return target->priority == rule->priority ? rule->cls_rule : NULL;
774 ovs_mutex_unlock(&cls->mutex);
778 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
779 * same matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
780 * contain an exact match. */
782 classifier_find_match_exactly(const struct classifier *cls,
783 const struct match *target, int priority)
785 struct cls_rule *retval;
788 cls_rule_init(&cr, target, priority);
789 retval = classifier_find_rule_exactly(cls, &cr);
790 cls_rule_destroy(&cr);
795 /* Checks if 'target' would overlap any other rule in 'cls'. Two rules are
796 * considered to overlap if both rules have the same priority and a packet
797 * could match both. */
799 classifier_rule_overlaps(const struct classifier *cls,
800 const struct cls_rule *target)
801 OVS_EXCLUDED(cls->mutex)
803 struct cls_subtable *subtable;
805 ovs_mutex_lock(&cls->mutex);
806 /* Iterate subtables in the descending max priority order. */
807 PVECTOR_FOR_EACH_PRIORITY (subtable, target->priority - 1, 2,
808 sizeof(struct cls_subtable), &cls->subtables) {
809 uint32_t storage[FLOW_U32S];
810 struct minimask mask;
811 struct cls_match *head;
813 minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
814 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
815 struct cls_match *rule;
817 FOR_EACH_RULE_IN_LIST (rule, head) {
818 if (rule->priority < target->priority) {
819 break; /* Rules in descending priority order. */
821 if (rule->priority == target->priority
822 && miniflow_equal_in_minimask(&target->match.flow,
823 &rule->flow, &mask)) {
824 ovs_mutex_unlock(&cls->mutex);
831 ovs_mutex_unlock(&cls->mutex);
835 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
836 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
837 * function returns true if, for every field:
839 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
842 * - 'criteria' wildcards the field,
844 * Conversely, 'rule' does not match 'criteria' and this function returns false
845 * if, for at least one field:
847 * - 'criteria' and 'rule' specify different values for the field, or
849 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
851 * Equivalently, the truth table for whether a field matches is:
856 * r +---------+---------+
857 * i wild | yes | yes |
859 * e +---------+---------+
860 * r exact | no |if values|
862 * a +---------+---------+
864 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
865 * commands and by OpenFlow 1.0 aggregate and flow stats.
867 * Ignores rule->priority. */
869 cls_rule_is_loose_match(const struct cls_rule *rule,
870 const struct minimatch *criteria)
872 return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
873 && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
880 rule_matches(const struct cls_match *rule, const struct cls_rule *target)
883 || miniflow_equal_in_minimask(&rule->flow,
885 &target->match.mask));
888 static struct cls_match *
889 search_subtable(const struct cls_subtable *subtable,
890 struct cls_cursor *cursor)
893 || !minimask_has_extra(&subtable->mask, &cursor->target->match.mask)) {
894 struct cls_match *rule;
896 CMAP_CURSOR_FOR_EACH (rule, cmap_node, &cursor->rules,
898 if (rule_matches(rule, cursor->target)) {
906 /* Initializes 'cursor' for iterating through rules in 'cls', and returns the
907 * first matching cls_rule via '*pnode', or NULL if there are no matches.
909 * - If 'target' is null, the cursor will visit every rule in 'cls'.
911 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
912 * such that cls_rule_is_loose_match(rule, target) returns true.
914 * Ignores target->priority. */
915 struct cls_cursor cls_cursor_start(const struct classifier *cls,
916 const struct cls_rule *target,
918 OVS_NO_THREAD_SAFETY_ANALYSIS
920 struct cls_cursor cursor;
921 struct cls_subtable *subtable;
925 cursor.target = target && !cls_rule_is_catchall(target) ? target : NULL;
928 /* Find first rule. */
929 ovs_mutex_lock(&cursor.cls->mutex);
930 CMAP_CURSOR_FOR_EACH (subtable, cmap_node, &cursor.subtables,
931 &cursor.cls->subtables_map) {
932 struct cls_match *rule = search_subtable(subtable, &cursor);
935 cursor.subtable = subtable;
936 cursor.rule = rule->cls_rule;
941 /* Leave locked if requested and have a rule. */
942 if (safe || !cursor.rule) {
943 ovs_mutex_unlock(&cursor.cls->mutex);
948 static struct cls_rule *
949 cls_cursor_next(struct cls_cursor *cursor)
950 OVS_NO_THREAD_SAFETY_ANALYSIS
952 struct cls_match *rule = cursor->rule->cls_match;
953 const struct cls_subtable *subtable;
954 struct cls_match *next;
956 next = next_rule_in_list__(rule);
957 if (next->priority < rule->priority) {
958 return next->cls_rule;
961 /* 'next' is the head of the list, that is, the rule that is included in
962 * the subtable's map. (This is important when the classifier contains
963 * rules that differ only in priority.) */
965 CMAP_CURSOR_FOR_EACH_CONTINUE (rule, cmap_node, &cursor->rules) {
966 if (rule_matches(rule, cursor->target)) {
967 return rule->cls_rule;
971 subtable = cursor->subtable;
972 CMAP_CURSOR_FOR_EACH_CONTINUE (subtable, cmap_node, &cursor->subtables) {
973 rule = search_subtable(subtable, cursor);
975 cursor->subtable = subtable;
976 return rule->cls_rule;
983 /* Sets 'cursor->rule' to the next matching cls_rule in 'cursor''s iteration,
984 * or to null if all matching rules have been visited. */
986 cls_cursor_advance(struct cls_cursor *cursor)
987 OVS_NO_THREAD_SAFETY_ANALYSIS
990 ovs_mutex_lock(&cursor->cls->mutex);
992 cursor->rule = cls_cursor_next(cursor);
993 if (cursor->safe || !cursor->rule) {
994 ovs_mutex_unlock(&cursor->cls->mutex);
998 static struct cls_subtable *
999 find_subtable(const struct classifier *cls, const struct minimask *mask)
1000 OVS_REQUIRES(cls->mutex)
1002 struct cls_subtable *subtable;
1004 CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, minimask_hash(mask, 0),
1005 &cls->subtables_map) {
1006 if (minimask_equal(mask, &subtable->mask)) {
1013 /* The new subtable will be visible to the readers only after this. */
1014 static struct cls_subtable *
1015 insert_subtable(struct classifier *cls, const struct minimask *mask)
1016 OVS_REQUIRES(cls->mutex)
1018 uint32_t hash = minimask_hash(mask, 0);
1019 struct cls_subtable *subtable;
1021 struct flow_wildcards old, new;
1023 int count = count_1bits(mask->masks.map);
1025 subtable = xzalloc(sizeof *subtable - sizeof mask->masks.inline_values
1026 + MINIFLOW_VALUES_SIZE(count));
1027 cmap_init(&subtable->rules);
1028 miniflow_clone_inline(&subtable->mask.masks, &mask->masks, count);
1030 /* Init indices for segmented lookup, if any. */
1031 flow_wildcards_init_catchall(&new);
1034 for (i = 0; i < cls->n_flow_segments; i++) {
1035 flow_wildcards_fold_minimask_range(&new, mask, prev,
1036 cls->flow_segments[i]);
1037 /* Add an index if it adds mask bits. */
1038 if (!flow_wildcards_equal(&new, &old)) {
1039 cmap_init(&subtable->indices[index]);
1040 subtable->index_ofs[index] = cls->flow_segments[i];
1044 prev = cls->flow_segments[i];
1046 /* Check if the rest of the subtable's mask adds any bits,
1047 * and remove the last index if it doesn't. */
1049 flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U32S);
1050 if (flow_wildcards_equal(&new, &old)) {
1052 subtable->index_ofs[index] = 0;
1053 cmap_destroy(&subtable->indices[index]);
1056 subtable->n_indices = index;
1058 subtable->tag = (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1059 ? tag_create_deterministic(hash)
1062 for (i = 0; i < cls->n_tries; i++) {
1063 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1064 cls->tries[i].field);
1068 ovsrcu_set_hidden(&subtable->ports_trie, NULL);
1069 subtable->ports_mask_len
1070 = 32 - ctz32(ntohl(MINIFLOW_GET_BE32(&mask->masks, tp_src)));
1072 cmap_insert(&cls->subtables_map, &subtable->cmap_node, hash);
1078 destroy_subtable(struct classifier *cls, struct cls_subtable *subtable)
1079 OVS_REQUIRES(cls->mutex)
1083 pvector_remove(&cls->subtables, subtable);
1084 trie_destroy(&subtable->ports_trie);
1086 for (i = 0; i < subtable->n_indices; i++) {
1087 cmap_destroy(&subtable->indices[i]);
1089 cmap_remove(&cls->subtables_map, &subtable->cmap_node,
1090 minimask_hash(&subtable->mask, 0));
1091 minimask_destroy(&subtable->mask);
1092 cmap_destroy(&subtable->rules);
1093 ovsrcu_postpone(free, subtable);
1101 static unsigned int be_get_bit_at(const ovs_be32 value[], unsigned int ofs);
1103 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1104 * lookup results. */
1106 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1107 const unsigned int field_plen[CLS_MAX_TRIES],
1108 const struct range ofs, const struct flow *flow,
1109 struct flow_wildcards *wc)
1113 /* Check if we could avoid fully unwildcarding the next level of
1114 * fields using the prefix tries. The trie checks are done only as
1115 * needed to avoid folding in additional bits to the wildcards mask. */
1116 for (j = 0; j < n_tries; j++) {
1117 /* Is the trie field relevant for this subtable? */
1118 if (field_plen[j]) {
1119 struct trie_ctx *ctx = &trie_ctx[j];
1120 uint8_t be32ofs = ctx->be32ofs;
1122 /* Is the trie field within the current range of fields? */
1123 if (be32ofs >= ofs.start && be32ofs < ofs.end) {
1124 /* On-demand trie lookup. */
1125 if (!ctx->lookup_done) {
1126 memset(&ctx->match_plens, 0, sizeof ctx->match_plens);
1127 ctx->maskbits = trie_lookup(ctx->trie, flow,
1129 ctx->lookup_done = true;
1131 /* Possible to skip the rest of the subtable if subtable's
1132 * prefix on the field is not included in the lookup result. */
1133 if (!be_get_bit_at(&ctx->match_plens.be32, field_plen[j] - 1)) {
1134 /* We want the trie lookup to never result in unwildcarding
1135 * any bits that would not be unwildcarded otherwise.
1136 * Since the trie is shared by the whole classifier, it is
1137 * possible that the 'maskbits' contain bits that are
1138 * irrelevant for the partition relevant for the current
1139 * packet. Hence the checks below. */
1141 /* Check that the trie result will not unwildcard more bits
1142 * than this subtable would otherwise. */
1143 if (ctx->maskbits <= field_plen[j]) {
1144 /* Unwildcard the bits and skip the rest. */
1145 mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1146 /* Note: Prerequisite already unwildcarded, as the only
1147 * prerequisite of the supported trie lookup fields is
1148 * the ethertype, which is always unwildcarded. */
1151 /* Can skip if the field is already unwildcarded. */
1152 if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1162 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1163 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1164 * value has the correct value in 'target'.
1166 * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
1167 * target, mask) but this is faster because of the invariant that
1168 * flow->map and mask->masks.map are the same, and that this version
1169 * takes the 'wc'. */
1171 miniflow_and_mask_matches_flow(const struct miniflow *flow,
1172 const struct minimask *mask,
1173 const struct flow *target)
1175 const uint32_t *flowp = miniflow_get_u32_values(flow);
1176 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1179 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1180 uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & *maskp++;
1190 static inline struct cls_match *
1191 find_match(const struct cls_subtable *subtable, const struct flow *flow,
1194 struct cls_match *rule;
1196 CMAP_FOR_EACH_WITH_HASH (rule, cmap_node, hash, &subtable->rules) {
1197 if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
1206 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1207 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1208 * value has the correct value in 'target'.
1210 * This function is equivalent to miniflow_and_mask_matches_flow() but this
1211 * version fills in the mask bits in 'wc'. */
1213 miniflow_and_mask_matches_flow_wc(const struct miniflow *flow,
1214 const struct minimask *mask,
1215 const struct flow *target,
1216 struct flow_wildcards *wc)
1218 const uint32_t *flowp = miniflow_get_u32_values(flow);
1219 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1222 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1223 uint32_t mask = *maskp++;
1224 uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & mask;
1227 /* Only unwildcard if none of the differing bits is already
1229 if (!(flow_u32_value(&wc->masks, idx) & diff)) {
1230 /* Keep one bit of the difference. */
1231 *flow_u32_lvalue(&wc->masks, idx) |= rightmost_1bit(diff);
1235 /* Fill in the bits that were looked at. */
1236 *flow_u32_lvalue(&wc->masks, idx) |= mask;
1242 /* Unwildcard the fields looked up so far, if any. */
1244 fill_range_wc(const struct cls_subtable *subtable, struct flow_wildcards *wc,
1248 flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, to);
1252 static struct cls_match *
1253 find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
1254 struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1255 struct flow_wildcards *wc)
1257 uint32_t basis = 0, hash;
1258 struct cls_match *rule = NULL;
1262 if (OVS_UNLIKELY(!wc)) {
1263 return find_match(subtable, flow,
1264 flow_hash_in_minimask(flow, &subtable->mask, 0));
1268 /* Try to finish early by checking fields in segments. */
1269 for (i = 0; i < subtable->n_indices; i++) {
1270 const struct cmap_node *inode;
1272 ofs.end = subtable->index_ofs[i];
1274 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1276 /* 'wc' bits for the trie field set, now unwildcard the preceding
1277 * bits used so far. */
1278 fill_range_wc(subtable, wc, ofs.start);
1281 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1283 inode = cmap_find(&subtable->indices[i], hash);
1285 /* No match, can stop immediately, but must fold in the bits
1286 * used in lookup so far. */
1287 fill_range_wc(subtable, wc, ofs.end);
1291 /* If we have narrowed down to a single rule already, check whether
1292 * that rule matches. Either way, we're done.
1294 * (Rare) hash collisions may cause us to miss the opportunity for this
1296 if (!cmap_node_next(inode)) {
1297 ASSIGN_CONTAINER(rule, inode - i, index_nodes);
1298 if (miniflow_and_mask_matches_flow_wc(&rule->flow, &subtable->mask,
1304 ofs.start = ofs.end;
1306 ofs.end = FLOW_U32S;
1307 /* Trie check for the final range. */
1308 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1309 fill_range_wc(subtable, wc, ofs.start);
1312 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1314 rule = find_match(subtable, flow, hash);
1315 if (!rule && subtable->ports_mask_len) {
1316 /* Ports are always part of the final range, if any.
1317 * No match was found for the ports. Use the ports trie to figure out
1318 * which ports bits to unwildcard. */
1320 ovs_be32 value, plens, mask;
1322 mask = MINIFLOW_GET_BE32(&subtable->mask.masks, tp_src);
1323 value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
1324 mbits = trie_lookup_value(&subtable->ports_trie, &value, &plens, 32);
1326 ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
1327 mask & htonl(~0 << (32 - mbits));
1329 /* Unwildcard all bits in the mask upto the ports, as they were used
1330 * to determine there is no match. */
1331 fill_range_wc(subtable, wc, TP_PORTS_OFS32);
1335 /* Must unwildcard all the fields, as they were looked at. */
1336 flow_wildcards_fold_minimask(wc, &subtable->mask);
1340 static struct cls_match *
1341 find_equal(struct cls_subtable *subtable, const struct miniflow *flow,
1344 struct cls_match *head;
1346 CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1347 if (miniflow_equal(&head->flow, flow)) {
1355 * As the readers are operating concurrently with the modifications, a
1356 * concurrent reader may or may not see the new rule, depending on how
1357 * the concurrent events overlap with each other. This is no
1358 * different from the former locked behavior, but there the visibility
1359 * of the new rule only depended on the timing of the locking
1362 * The new rule is first added to the segment indices, so the readers
1363 * may find the rule in the indices before the rule is visible in the
1364 * subtables 'rules' map. This may result in us losing the
1365 * opportunity to quit lookups earlier, resulting in sub-optimal
1366 * wildcarding. This will be fixed by forthcoming revalidation always
1367 * scheduled after flow table changes.
1369 * Similar behavior may happen due to us removing the overlapping rule
1370 * (if any) from the indices only after the new rule has been added.
1372 * The subtable's max priority is updated only after the rule is
1373 * inserted, so the concurrent readers may not see the rule, as the
1374 * updated priority ordered subtable list will only be visible after
1375 * the subtable's max priority is updated.
1377 * Similarly, the classifier's partitions for new rules are updated by
1378 * the caller after this function, so the readers may keep skipping
1379 * the subtable until they see the updated partitions.
1381 static struct cls_match *
1382 insert_rule(struct classifier *cls, struct cls_subtable *subtable,
1383 struct cls_rule *new_rule)
1384 OVS_REQUIRES(cls->mutex)
1386 struct cls_match *old = NULL;
1387 struct cls_match *new = cls_match_alloc(new_rule);
1388 struct cls_match *head;
1390 uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
1391 uint8_t prev_be32ofs = 0;
1393 /* Add new node to segment indices. */
1394 for (i = 0; i < subtable->n_indices; i++) {
1395 ihash[i] = minimatch_hash_range(&new_rule->match, prev_be32ofs,
1396 subtable->index_ofs[i], &basis);
1397 cmap_insert(&subtable->indices[i], &new->index_nodes[i], ihash[i]);
1398 prev_be32ofs = subtable->index_ofs[i];
1400 hash = minimatch_hash_range(&new_rule->match, prev_be32ofs, FLOW_U32S,
1402 head = find_equal(subtable, &new_rule->match.flow, hash);
1404 cmap_insert(&subtable->rules, &new->cmap_node, hash);
1405 rculist_init(&new->list);
1408 /* Scan the list for the insertion point that will keep the list in
1409 * order of decreasing priority. */
1410 struct cls_match *rule;
1412 FOR_EACH_RULE_IN_LIST (rule, head) {
1413 if (new->priority >= rule->priority) {
1415 /* 'new' is the new highest-priority flow in the list. */
1416 cmap_replace(&subtable->rules, &rule->cmap_node,
1417 &new->cmap_node, hash);
1420 if (new->priority == rule->priority) {
1421 rculist_replace(&new->list, &rule->list);
1424 rculist_insert(&rule->list, &new->list);
1430 /* Insert 'new' at the end of the list. */
1431 rculist_push_back(&head->list, &new->list);
1436 subtable->n_rules++;
1438 /* Rule was added, not replaced. Update 'subtable's 'max_priority'
1439 * and 'max_count', if necessary. */
1440 if (subtable->n_rules == 1) {
1441 subtable->max_priority = new->priority;
1442 subtable->max_count = 1;
1443 pvector_insert(&cls->subtables, subtable, new->priority);
1444 } else if (subtable->max_priority == new->priority) {
1445 ++subtable->max_count;
1446 } else if (new->priority > subtable->max_priority) {
1447 subtable->max_priority = new->priority;
1448 subtable->max_count = 1;
1449 pvector_change_priority(&cls->subtables, subtable, new->priority);
1452 /* Remove old node from indices. */
1453 for (i = 0; i < subtable->n_indices; i++) {
1454 cmap_remove(&subtable->indices[i], &old->index_nodes[i], ihash[i]);
1460 /* A longest-prefix match tree. */
1462 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1463 * Prefixes are in the network byte order, and the offset 0 corresponds to
1464 * the most significant bit of the first byte. The offset can be read as
1465 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1467 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1471 pr += ofs / 32; /* Where to start. */
1472 ofs %= 32; /* How many bits to skip at 'pr'. */
1474 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1475 if (plen > 32 - ofs) { /* Need more than we have already? */
1476 prefix |= ntohl(*++pr) >> (32 - ofs);
1478 /* Return with possible unwanted bits at the end. */
1482 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1483 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1484 * corresponds to the most significant bit of the first byte. The offset can
1485 * be read as "how many bits to skip from the start of the prefix starting at
1488 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1493 if (plen > TRIE_PREFIX_BITS) {
1494 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1496 /* Return with unwanted bits cleared. */
1497 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1500 /* Return the number of equal bits in 'n_bits' of 'prefix's MSBs and a 'value'
1501 * starting at "MSB 0"-based offset 'ofs'. */
1503 prefix_equal_bits(uint32_t prefix, unsigned int n_bits, const ovs_be32 value[],
1506 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, n_bits);
1507 /* Set the bit after the relevant bits to limit the result. */
1508 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - n_bits));
1511 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1512 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1514 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1515 unsigned int ofs, unsigned int plen)
1517 return prefix_equal_bits(node->prefix, MIN(node->n_bits, plen - ofs),
1521 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1522 * be greater than 31. */
1524 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1526 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1529 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1530 * be between 0 and 31, inclusive. */
1532 get_bit_at(const uint32_t prefix, unsigned int ofs)
1534 return (prefix >> (31 - ofs)) & 1u;
1537 /* Create new branch. */
1538 static struct trie_node *
1539 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1540 unsigned int n_rules)
1542 struct trie_node *node = xmalloc(sizeof *node);
1544 node->prefix = trie_get_prefix(prefix, ofs, plen);
1546 if (plen <= TRIE_PREFIX_BITS) {
1547 node->n_bits = plen;
1548 ovsrcu_set_hidden(&node->edges[0], NULL);
1549 ovsrcu_set_hidden(&node->edges[1], NULL);
1550 node->n_rules = n_rules;
1551 } else { /* Need intermediate nodes. */
1552 struct trie_node *subnode = trie_branch_create(prefix,
1553 ofs + TRIE_PREFIX_BITS,
1554 plen - TRIE_PREFIX_BITS,
1556 int bit = get_bit_at(subnode->prefix, 0);
1557 node->n_bits = TRIE_PREFIX_BITS;
1558 ovsrcu_set_hidden(&node->edges[bit], subnode);
1559 ovsrcu_set_hidden(&node->edges[!bit], NULL);
1566 trie_node_destroy(const struct trie_node *node)
1568 ovsrcu_postpone(free, CONST_CAST(struct trie_node *, node));
1571 /* Copy a trie node for modification and postpone delete the old one. */
1572 static struct trie_node *
1573 trie_node_rcu_realloc(const struct trie_node *node)
1575 struct trie_node *new_node = xmalloc(sizeof *node);
1578 trie_node_destroy(node);
1583 /* May only be called while holding the classifier mutex. */
1585 trie_destroy(rcu_trie_ptr *trie)
1587 struct trie_node *node = ovsrcu_get_protected(struct trie_node *, trie);
1590 ovsrcu_set_hidden(trie, NULL);
1591 trie_destroy(&node->edges[0]);
1592 trie_destroy(&node->edges[1]);
1593 trie_node_destroy(node);
1598 trie_is_leaf(const struct trie_node *trie)
1601 return !ovsrcu_get(struct trie_node *, &trie->edges[0])
1602 && !ovsrcu_get(struct trie_node *, &trie->edges[1]);
1606 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1607 unsigned int n_bits)
1609 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1612 for (i = 0; i < n_bits / 32; i++) {
1613 mask[i] = OVS_BE32_MAX;
1616 mask[i] |= htonl(~0u << (32 - n_bits % 32));
1621 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
1622 unsigned int n_bits)
1624 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1626 ovs_be32 zeroes = 0;
1628 for (i = 0; i < n_bits / 32; i++) {
1632 zeroes |= ~mask[i] & htonl(~0u << (32 - n_bits % 32));
1635 return !zeroes; /* All 'n_bits' bits set. */
1638 static rcu_trie_ptr *
1639 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
1642 return node->edges + be_get_bit_at(value, ofs);
1645 static const struct trie_node *
1646 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
1649 return ovsrcu_get(struct trie_node *,
1650 &node->edges[be_get_bit_at(value, ofs)]);
1653 /* Set the bit at ("MSB 0"-based) offset 'ofs'. 'ofs' can be greater than 31.
1656 be_set_bit_at(ovs_be32 value[], unsigned int ofs)
1658 ((uint8_t *)value)[ofs / 8] |= 1u << (7 - ofs % 8);
1661 /* Returns the number of bits in the prefix mask necessary to determine a
1662 * mismatch, in case there are longer prefixes in the tree below the one that
1664 * '*plens' will have a bit set for each prefix length that may have matching
1665 * rules. The caller is responsible for clearing the '*plens' prior to
1669 trie_lookup_value(const rcu_trie_ptr *trie, const ovs_be32 value[],
1670 ovs_be32 plens[], unsigned int n_bits)
1672 const struct trie_node *prev = NULL;
1673 const struct trie_node *node = ovsrcu_get(struct trie_node *, trie);
1674 unsigned int match_len = 0; /* Number of matching bits. */
1676 for (; node; prev = node, node = trie_next_node(node, value, match_len)) {
1677 unsigned int eqbits;
1678 /* Check if this edge can be followed. */
1679 eqbits = prefix_equal_bits(node->prefix, node->n_bits, value,
1681 match_len += eqbits;
1682 if (eqbits < node->n_bits) { /* Mismatch, nothing more to be found. */
1683 /* Bit at offset 'match_len' differed. */
1684 return match_len + 1; /* Includes the first mismatching bit. */
1686 /* Full match, check if rules exist at this prefix length. */
1687 if (node->n_rules > 0) {
1688 be_set_bit_at(plens, match_len - 1);
1690 if (match_len >= n_bits) {
1691 return n_bits; /* Full prefix. */
1694 /* node == NULL. Full match so far, but we tried to follow an
1695 * non-existing branch. Need to exclude the other branch if it exists
1696 * (it does not if we were called on an empty trie or 'prev' is a leaf
1698 return !prev || trie_is_leaf(prev) ? match_len : match_len + 1;
1702 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
1703 union mf_value *plens)
1705 const struct mf_field *mf = trie->field;
1707 /* Check that current flow matches the prerequisites for the trie
1708 * field. Some match fields are used for multiple purposes, so we
1709 * must check that the trie is relevant for this flow. */
1710 if (mf_are_prereqs_ok(mf, flow)) {
1711 return trie_lookup_value(&trie->root,
1712 &((ovs_be32 *)flow)[mf->flow_be32ofs],
1713 &plens->be32, mf->n_bits);
1715 memset(plens, 0xff, sizeof *plens); /* All prefixes, no skipping. */
1716 return 0; /* Value not used in this case. */
1719 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
1720 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
1721 * 'miniflow_index' is not NULL. */
1723 minimask_get_prefix_len(const struct minimask *minimask,
1724 const struct mf_field *mf)
1726 unsigned int n_bits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
1727 uint8_t u32_ofs = mf->flow_be32ofs;
1728 uint8_t u32_end = u32_ofs + mf->n_bytes / 4;
1730 for (; u32_ofs < u32_end; ++u32_ofs) {
1732 mask = ntohl((OVS_FORCE ovs_be32)minimask_get(minimask, u32_ofs));
1734 /* Validate mask, count the mask length. */
1737 return 0; /* No bits allowed after mask ended. */
1740 if (~mask & (~mask + 1)) {
1741 return 0; /* Mask not contiguous. */
1743 mask_tz = ctz32(mask);
1744 n_bits += 32 - mask_tz;
1752 * This is called only when mask prefix is known to be CIDR and non-zero.
1753 * Relies on the fact that the flow and mask have the same map, and since
1754 * the mask is CIDR, the storage for the flow field exists even if it
1755 * happened to be zeros.
1757 static const ovs_be32 *
1758 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
1760 return miniflow_get_be32_values(&match->flow) +
1761 count_1bits(match->flow.map & ((UINT64_C(1) << mf->flow_be32ofs) - 1));
1764 /* Insert rule in to the prefix tree.
1765 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1768 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1770 trie_insert_prefix(&trie->root,
1771 minimatch_get_prefix(&rule->match, trie->field), mlen);
1775 trie_insert_prefix(rcu_trie_ptr *edge, const ovs_be32 *prefix, int mlen)
1777 struct trie_node *node;
1780 /* Walk the tree. */
1781 for (; (node = ovsrcu_get_protected(struct trie_node *, edge));
1782 edge = trie_next_edge(node, prefix, ofs)) {
1783 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1785 if (eqbits < node->n_bits) {
1786 /* Mismatch, new node needs to be inserted above. */
1787 int old_branch = get_bit_at(node->prefix, eqbits);
1788 struct trie_node *new_parent;
1790 new_parent = trie_branch_create(prefix, ofs - eqbits, eqbits,
1791 ofs == mlen ? 1 : 0);
1792 /* Copy the node to modify it. */
1793 node = trie_node_rcu_realloc(node);
1794 /* Adjust the new node for its new position in the tree. */
1795 node->prefix <<= eqbits;
1796 node->n_bits -= eqbits;
1797 ovsrcu_set_hidden(&new_parent->edges[old_branch], node);
1799 /* Check if need a new branch for the new rule. */
1801 ovsrcu_set_hidden(&new_parent->edges[!old_branch],
1802 trie_branch_create(prefix, ofs, mlen - ofs,
1805 ovsrcu_set(edge, new_parent); /* Publish changes. */
1808 /* Full match so far. */
1811 /* Full match at the current node, rule needs to be added here. */
1816 /* Must insert a new tree branch for the new rule. */
1817 ovsrcu_set(edge, trie_branch_create(prefix, ofs, mlen - ofs, 1));
1820 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1823 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1825 trie_remove_prefix(&trie->root,
1826 minimatch_get_prefix(&rule->match, trie->field), mlen);
1829 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1832 trie_remove_prefix(rcu_trie_ptr *root, const ovs_be32 *prefix, int mlen)
1834 struct trie_node *node;
1835 rcu_trie_ptr *edges[sizeof(union mf_value) * 8];
1836 int depth = 0, ofs = 0;
1838 /* Walk the tree. */
1839 for (edges[0] = root;
1840 (node = ovsrcu_get_protected(struct trie_node *, edges[depth]));
1841 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
1842 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1844 if (eqbits < node->n_bits) {
1845 /* Mismatch, nothing to be removed. This should never happen, as
1846 * only rules in the classifier are ever removed. */
1847 break; /* Log a warning. */
1849 /* Full match so far. */
1853 /* Full prefix match at the current node, remove rule here. */
1854 if (!node->n_rules) {
1855 break; /* Log a warning. */
1859 /* Check if can prune the tree. */
1860 while (!node->n_rules) {
1861 struct trie_node *next,
1862 *edge0 = ovsrcu_get_protected(struct trie_node *,
1864 *edge1 = ovsrcu_get_protected(struct trie_node *,
1867 if (edge0 && edge1) {
1868 break; /* A branching point, cannot prune. */
1871 /* Else have at most one child node, remove this node. */
1872 next = edge0 ? edge0 : edge1;
1875 if (node->n_bits + next->n_bits > TRIE_PREFIX_BITS) {
1876 break; /* Cannot combine. */
1878 next = trie_node_rcu_realloc(next); /* Modify. */
1880 /* Combine node with next. */
1881 next->prefix = node->prefix | next->prefix >> node->n_bits;
1882 next->n_bits += node->n_bits;
1884 /* Update the parent's edge. */
1885 ovsrcu_set(edges[depth], next); /* Publish changes. */
1886 trie_node_destroy(node);
1888 if (next || !depth) {
1889 /* Branch not pruned or at root, nothing more to do. */
1892 node = ovsrcu_get_protected(struct trie_node *,
1898 /* Cannot go deeper. This should never happen, since only rules
1899 * that actually exist in the classifier are ever removed. */
1900 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");