]> git.proxmox.com Git - mirror_ovs.git/blob - lib/classifier.c
cirrus: Use FreeBSD 12.2.
[mirror_ovs.git] / lib / classifier.c
1 /*
2 * Copyright (c) 2009-2017 Nicira, Inc.
3 *
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:
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17 #include <config.h>
18 #include "classifier.h"
19 #include "classifier-private.h"
20 #include <errno.h>
21 #include <sys/types.h>
22 #include <netinet/in.h>
23 #include "byte-order.h"
24 #include "openvswitch/dynamic-string.h"
25 #include "odp-util.h"
26 #include "packets.h"
27 #include "util.h"
28
29 struct trie_ctx;
30
31 /* A collection of "struct cls_conjunction"s currently embedded into a
32 * cls_match. */
33 struct cls_conjunction_set {
34 /* Link back to the cls_match.
35 *
36 * cls_conjunction_set is mostly used during classifier lookup, and, in
37 * turn, during classifier lookup the most used member of
38 * cls_conjunction_set is the rule's priority, so we cache it here for fast
39 * access. */
40 struct cls_match *match;
41 int priority; /* Cached copy of match->priority. */
42
43 /* Conjunction information.
44 *
45 * 'min_n_clauses' allows some optimization during classifier lookup. */
46 unsigned int n; /* Number of elements in 'conj'. */
47 unsigned int min_n_clauses; /* Smallest 'n' among elements of 'conj'. */
48 struct cls_conjunction conj[];
49 };
50
51 /* Ports trie depends on both ports sharing the same ovs_be32. */
52 #define TP_PORTS_OFS32 (offsetof(struct flow, tp_src) / 4)
53 BUILD_ASSERT_DECL(TP_PORTS_OFS32 == offsetof(struct flow, tp_dst) / 4);
54 BUILD_ASSERT_DECL(TP_PORTS_OFS32 % 2 == 0);
55 #define TP_PORTS_OFS64 (TP_PORTS_OFS32 / 2)
56
57 static size_t
58 cls_conjunction_set_size(size_t n)
59 {
60 return (sizeof(struct cls_conjunction_set)
61 + n * sizeof(struct cls_conjunction));
62 }
63
64 static struct cls_conjunction_set *
65 cls_conjunction_set_alloc(struct cls_match *match,
66 const struct cls_conjunction conj[], size_t n)
67 {
68 if (n) {
69 size_t min_n_clauses = conj[0].n_clauses;
70 for (size_t i = 1; i < n; i++) {
71 min_n_clauses = MIN(min_n_clauses, conj[i].n_clauses);
72 }
73
74 struct cls_conjunction_set *set = xmalloc(cls_conjunction_set_size(n));
75 set->match = match;
76 set->priority = match->priority;
77 set->n = n;
78 set->min_n_clauses = min_n_clauses;
79 memcpy(set->conj, conj, n * sizeof *conj);
80 return set;
81 } else {
82 return NULL;
83 }
84 }
85
86 static struct cls_match *
87 cls_match_alloc(const struct cls_rule *rule, ovs_version_t version,
88 const struct cls_conjunction conj[], size_t n)
89 {
90 size_t count = miniflow_n_values(rule->match.flow);
91
92 struct cls_match *cls_match
93 = xmalloc(sizeof *cls_match + MINIFLOW_VALUES_SIZE(count));
94
95 ovsrcu_init(&cls_match->next, NULL);
96 *CONST_CAST(const struct cls_rule **, &cls_match->cls_rule) = rule;
97 *CONST_CAST(int *, &cls_match->priority) = rule->priority;
98 /* Make rule initially invisible. */
99 cls_match->versions = VERSIONS_INITIALIZER(version, version);
100 miniflow_clone(CONST_CAST(struct miniflow *, &cls_match->flow),
101 rule->match.flow, count);
102 ovsrcu_set_hidden(&cls_match->conj_set,
103 cls_conjunction_set_alloc(cls_match, conj, n));
104
105 return cls_match;
106 }
107
108 static struct cls_subtable *find_subtable(const struct classifier *cls,
109 const struct minimask *);
110 static struct cls_subtable *insert_subtable(struct classifier *cls,
111 const struct minimask *);
112 static void destroy_subtable(struct classifier *cls, struct cls_subtable *);
113
114 static const struct cls_match *find_match_wc(const struct cls_subtable *,
115 ovs_version_t version,
116 const struct flow *,
117 struct trie_ctx *,
118 unsigned int n_tries,
119 struct flow_wildcards *);
120 static struct cls_match *find_equal(const struct cls_subtable *,
121 const struct miniflow *, uint32_t hash);
122
123 /* Return the next visible (lower-priority) rule in the list. Multiple
124 * identical rules with the same priority may exist transitionally, but when
125 * versioning is used at most one of them is ever visible for lookups on any
126 * given 'version'. */
127 static inline const struct cls_match *
128 next_visible_rule_in_list(const struct cls_match *rule, ovs_version_t version)
129 {
130 do {
131 rule = cls_match_next(rule);
132 } while (rule && !cls_match_visible_in_version(rule, version));
133
134 return rule;
135 }
136
137 /* Type with maximum supported prefix length. */
138 union trie_prefix {
139 struct in6_addr ipv6; /* For sizing. */
140 ovs_be32 be32; /* For access. */
141 };
142
143 static unsigned int minimask_get_prefix_len(const struct minimask *,
144 const struct mf_field *);
145 static void trie_init(struct classifier *cls, int trie_idx,
146 const struct mf_field *);
147 static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
148 union trie_prefix *plens);
149 static unsigned int trie_lookup_value(const rcu_trie_ptr *,
150 const ovs_be32 value[], ovs_be32 plens[],
151 unsigned int value_bits);
152 static void trie_destroy(rcu_trie_ptr *);
153 static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
154 static void trie_insert_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
155 int mlen);
156 static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
157 static void trie_remove_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
158 int mlen);
159 static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
160 unsigned int n_bits);
161 static bool mask_prefix_bits_set(const struct flow_wildcards *,
162 uint8_t be32ofs, unsigned int n_bits);
163 \f
164 /* cls_rule. */
165
166 static inline void
167 cls_rule_init__(struct cls_rule *rule, unsigned int priority)
168 {
169 rculist_init(&rule->node);
170 *CONST_CAST(int *, &rule->priority) = priority;
171 ovsrcu_init(&rule->cls_match, NULL);
172 }
173
174 /* Initializes 'rule' to match packets specified by 'match' at the given
175 * 'priority'. 'match' must satisfy the invariant described in the comment at
176 * the definition of struct match.
177 *
178 * The caller must eventually destroy 'rule' with cls_rule_destroy().
179 *
180 * Clients should not use priority INT_MIN. (OpenFlow uses priorities between
181 * 0 and UINT16_MAX, inclusive.) */
182 void
183 cls_rule_init(struct cls_rule *rule, const struct match *match, int priority)
184 {
185 cls_rule_init__(rule, priority);
186 minimatch_init(CONST_CAST(struct minimatch *, &rule->match), match);
187 }
188
189 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
190 void
191 cls_rule_init_from_minimatch(struct cls_rule *rule,
192 const struct minimatch *match, int priority)
193 {
194 cls_rule_init__(rule, priority);
195 minimatch_clone(CONST_CAST(struct minimatch *, &rule->match), match);
196 }
197
198 /* Initializes 'dst' as a copy of 'src'.
199 *
200 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
201 void
202 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
203 {
204 cls_rule_init__(dst, src->priority);
205 minimatch_clone(CONST_CAST(struct minimatch *, &dst->match), &src->match);
206 }
207
208 /* Initializes 'dst' with the data in 'src', destroying 'src'.
209 *
210 * 'src' must be a cls_rule NOT in a classifier.
211 *
212 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
213 void
214 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
215 {
216 cls_rule_init__(dst, src->priority);
217 minimatch_move(CONST_CAST(struct minimatch *, &dst->match),
218 CONST_CAST(struct minimatch *, &src->match));
219 }
220
221 /* Frees memory referenced by 'rule'. Doesn't free 'rule' itself (it's
222 * normally embedded into a larger structure).
223 *
224 * ('rule' must not currently be in a classifier.) */
225 void
226 cls_rule_destroy(struct cls_rule *rule)
227 OVS_NO_THREAD_SAFETY_ANALYSIS
228 {
229 /* Must not be in a classifier. */
230 ovs_assert(!get_cls_match_protected(rule));
231
232 /* Check that the rule has been properly removed from the classifier. */
233 ovs_assert(rule->node.prev == RCULIST_POISON
234 || rculist_is_empty(&rule->node));
235 rculist_poison__(&rule->node); /* Poisons also the next pointer. */
236
237 minimatch_destroy(CONST_CAST(struct minimatch *, &rule->match));
238 }
239
240 /* This may only be called by the exclusive writer. */
241 void
242 cls_rule_set_conjunctions(struct cls_rule *cr,
243 const struct cls_conjunction *conj, size_t n)
244 {
245 struct cls_match *match = get_cls_match_protected(cr);
246 struct cls_conjunction_set *old
247 = ovsrcu_get_protected(struct cls_conjunction_set *, &match->conj_set);
248 struct cls_conjunction *old_conj = old ? old->conj : NULL;
249 unsigned int old_n = old ? old->n : 0;
250
251 if (old_n != n || (n && memcmp(old_conj, conj, n * sizeof *conj))) {
252 if (old) {
253 ovsrcu_postpone(free, old);
254 }
255 ovsrcu_set(&match->conj_set,
256 cls_conjunction_set_alloc(match, conj, n));
257 }
258 }
259
260
261 /* Returns true if 'a' and 'b' match the same packets at the same priority,
262 * false if they differ in some way. */
263 bool
264 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
265 {
266 return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
267 }
268
269 /* Appends a string describing 'rule' to 's'. */
270 void
271 cls_rule_format(const struct cls_rule *rule, const struct tun_table *tun_table,
272 const struct ofputil_port_map *port_map, struct ds *s)
273 {
274 minimatch_format(&rule->match, tun_table, port_map, s, rule->priority);
275 }
276
277 /* Returns true if 'rule' matches every packet, false otherwise. */
278 bool
279 cls_rule_is_catchall(const struct cls_rule *rule)
280 {
281 return minimask_is_catchall(rule->match.mask);
282 }
283
284 /* Makes 'rule' invisible in 'remove_version'. Once that version is used in
285 * lookups, the caller should remove 'rule' via ovsrcu_postpone().
286 *
287 * 'rule' must be in a classifier.
288 * This may only be called by the exclusive writer. */
289 void
290 cls_rule_make_invisible_in_version(const struct cls_rule *rule,
291 ovs_version_t remove_version)
292 {
293 struct cls_match *cls_match = get_cls_match_protected(rule);
294
295 ovs_assert(remove_version >= cls_match->versions.add_version);
296
297 cls_match_set_remove_version(cls_match, remove_version);
298 }
299
300 /* This undoes the change made by cls_rule_make_invisible_in_version().
301 *
302 * 'rule' must be in a classifier.
303 * This may only be called by the exclusive writer. */
304 void
305 cls_rule_restore_visibility(const struct cls_rule *rule)
306 {
307 cls_match_set_remove_version(get_cls_match_protected(rule),
308 OVS_VERSION_NOT_REMOVED);
309 }
310
311 /* Return true if 'rule' is visible in 'version'.
312 *
313 * 'rule' must be in a classifier. */
314 bool
315 cls_rule_visible_in_version(const struct cls_rule *rule, ovs_version_t version)
316 {
317 struct cls_match *cls_match = get_cls_match(rule);
318
319 return cls_match && cls_match_visible_in_version(cls_match, version);
320 }
321 \f
322 /* Initializes 'cls' as a classifier that initially contains no classification
323 * rules. */
324 void
325 classifier_init(struct classifier *cls, const uint8_t *flow_segments)
326 {
327 cls->n_rules = 0;
328 cmap_init(&cls->subtables_map);
329 pvector_init(&cls->subtables);
330 cls->n_flow_segments = 0;
331 if (flow_segments) {
332 while (cls->n_flow_segments < CLS_MAX_INDICES
333 && *flow_segments < FLOW_U64S) {
334 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
335 }
336 }
337 cls->n_tries = 0;
338 for (int i = 0; i < CLS_MAX_TRIES; i++) {
339 trie_init(cls, i, NULL);
340 }
341 cls->publish = true;
342 }
343
344 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
345 * caller's responsibility.
346 * May only be called after all the readers have been terminated. */
347 void
348 classifier_destroy(struct classifier *cls)
349 {
350 if (cls) {
351 struct cls_subtable *subtable;
352 int i;
353
354 for (i = 0; i < cls->n_tries; i++) {
355 trie_destroy(&cls->tries[i].root);
356 }
357
358 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
359 destroy_subtable(cls, subtable);
360 }
361 cmap_destroy(&cls->subtables_map);
362
363 pvector_destroy(&cls->subtables);
364 }
365 }
366
367 /* Set the fields for which prefix lookup should be performed. */
368 bool
369 classifier_set_prefix_fields(struct classifier *cls,
370 const enum mf_field_id *trie_fields,
371 unsigned int n_fields)
372 {
373 const struct mf_field * new_fields[CLS_MAX_TRIES];
374 struct mf_bitmap fields = MF_BITMAP_INITIALIZER;
375 int i, n_tries = 0;
376 bool changed = false;
377
378 for (i = 0; i < n_fields && n_tries < CLS_MAX_TRIES; i++) {
379 const struct mf_field *field = mf_from_id(trie_fields[i]);
380 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
381 /* Incompatible field. This is the only place where we
382 * enforce these requirements, but the rest of the trie code
383 * depends on the flow_be32ofs to be non-negative and the
384 * field length to be a multiple of 32 bits. */
385 continue;
386 }
387
388 if (bitmap_is_set(fields.bm, trie_fields[i])) {
389 /* Duplicate field, there is no need to build more than
390 * one index for any one field. */
391 continue;
392 }
393 bitmap_set1(fields.bm, trie_fields[i]);
394
395 new_fields[n_tries] = NULL;
396 const struct mf_field *cls_field
397 = ovsrcu_get(struct mf_field *, &cls->tries[n_tries].field);
398 if (n_tries >= cls->n_tries || field != cls_field) {
399 new_fields[n_tries] = field;
400 changed = true;
401 }
402 n_tries++;
403 }
404
405 if (changed || n_tries < cls->n_tries) {
406 struct cls_subtable *subtable;
407
408 /* Trie configuration needs to change. Disable trie lookups
409 * for the tries that are changing and wait all the current readers
410 * with the old configuration to be done. */
411 changed = false;
412 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
413 for (i = 0; i < cls->n_tries; i++) {
414 if ((i < n_tries && new_fields[i]) || i >= n_tries) {
415 if (subtable->trie_plen[i]) {
416 subtable->trie_plen[i] = 0;
417 changed = true;
418 }
419 }
420 }
421 }
422 /* Synchronize if any readers were using tries. The readers may
423 * temporarily function without the trie lookup based optimizations. */
424 if (changed) {
425 /* ovsrcu_synchronize() functions as a memory barrier, so it does
426 * not matter that subtable->trie_plen is not atomic. */
427 ovsrcu_synchronize();
428 }
429
430 /* Now set up the tries. */
431 for (i = 0; i < n_tries; i++) {
432 if (new_fields[i]) {
433 trie_init(cls, i, new_fields[i]);
434 }
435 }
436 /* Destroy the rest, if any. */
437 for (; i < cls->n_tries; i++) {
438 trie_init(cls, i, NULL);
439 }
440
441 cls->n_tries = n_tries;
442 return true;
443 }
444
445 return false; /* No change. */
446 }
447
448 static void
449 trie_init(struct classifier *cls, int trie_idx, const struct mf_field *field)
450 {
451 struct cls_trie *trie = &cls->tries[trie_idx];
452 struct cls_subtable *subtable;
453
454 if (trie_idx < cls->n_tries) {
455 trie_destroy(&trie->root);
456 } else {
457 ovsrcu_set_hidden(&trie->root, NULL);
458 }
459 ovsrcu_set_hidden(&trie->field, CONST_CAST(struct mf_field *, field));
460
461 /* Add existing rules to the new trie. */
462 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
463 unsigned int plen;
464
465 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
466 if (plen) {
467 struct cls_match *head;
468
469 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
470 trie_insert(trie, head->cls_rule, plen);
471 }
472 }
473 /* Initialize subtable's prefix length on this field. This will
474 * allow readers to use the trie. */
475 atomic_thread_fence(memory_order_release);
476 subtable->trie_plen[trie_idx] = plen;
477 }
478 }
479
480 /* Returns true if 'cls' contains no classification rules, false otherwise.
481 * Checking the cmap requires no locking. */
482 bool
483 classifier_is_empty(const struct classifier *cls)
484 {
485 return cmap_is_empty(&cls->subtables_map);
486 }
487
488 /* Returns the number of rules in 'cls'. */
489 int
490 classifier_count(const struct classifier *cls)
491 {
492 /* n_rules is an int, so in the presence of concurrent writers this will
493 * return either the old or a new value. */
494 return cls->n_rules;
495 }
496
497 static inline ovs_be32 minimatch_get_ports(const struct minimatch *match)
498 {
499 /* Could optimize to use the same map if needed for fast path. */
500 return (miniflow_get_ports(match->flow)
501 & miniflow_get_ports(&match->mask->masks));
502 }
503
504 /* Inserts 'rule' into 'cls' in 'version'. Until 'rule' is removed from 'cls',
505 * the caller must not modify or free it.
506 *
507 * If 'cls' already contains an identical rule (including wildcards, values of
508 * fixed fields, and priority) that is visible in 'version', replaces the old
509 * rule by 'rule' and returns the rule that was replaced. The caller takes
510 * ownership of the returned rule and is thus responsible for destroying it
511 * with cls_rule_destroy(), after RCU grace period has passed (see
512 * ovsrcu_postpone()).
513 *
514 * Returns NULL if 'cls' does not contain a rule with an identical key, after
515 * inserting the new rule. In this case, no rules are displaced by the new
516 * rule, even rules that cannot have any effect because the new rule matches a
517 * superset of their flows and has higher priority.
518 */
519 const struct cls_rule *
520 classifier_replace(struct classifier *cls, const struct cls_rule *rule,
521 ovs_version_t version,
522 const struct cls_conjunction *conjs, size_t n_conjs)
523 {
524 struct cls_match *new;
525 struct cls_subtable *subtable;
526 uint32_t ihash[CLS_MAX_INDICES];
527 struct cls_match *head;
528 unsigned int mask_offset;
529 size_t n_rules = 0;
530 uint32_t basis;
531 uint32_t hash;
532 unsigned int i;
533
534 /* 'new' is initially invisible to lookups. */
535 new = cls_match_alloc(rule, version, conjs, n_conjs);
536 ovsrcu_set(&CONST_CAST(struct cls_rule *, rule)->cls_match, new);
537
538 subtable = find_subtable(cls, rule->match.mask);
539 if (!subtable) {
540 subtable = insert_subtable(cls, rule->match.mask);
541 }
542
543 /* Compute hashes in segments. */
544 basis = 0;
545 mask_offset = 0;
546 for (i = 0; i < subtable->n_indices; i++) {
547 ihash[i] = minimatch_hash_range(&rule->match, subtable->index_maps[i],
548 &mask_offset, &basis);
549 }
550 hash = minimatch_hash_range(&rule->match, subtable->index_maps[i],
551 &mask_offset, &basis);
552
553 head = find_equal(subtable, rule->match.flow, hash);
554 if (!head) {
555 /* Add rule to tries.
556 *
557 * Concurrent readers might miss seeing the rule until this update,
558 * which might require being fixed up by revalidation later. */
559 for (i = 0; i < cls->n_tries; i++) {
560 if (subtable->trie_plen[i]) {
561 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
562 }
563 }
564
565 /* Add rule to ports trie. */
566 if (subtable->ports_mask_len) {
567 /* We mask the value to be inserted to always have the wildcarded
568 * bits in known (zero) state, so we can include them in comparison
569 * and they will always match (== their original value does not
570 * matter). */
571 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
572
573 trie_insert_prefix(&subtable->ports_trie, &masked_ports,
574 subtable->ports_mask_len);
575 }
576
577 /* Add new node to segment indices. */
578 for (i = 0; i < subtable->n_indices; i++) {
579 ccmap_inc(&subtable->indices[i], ihash[i]);
580 }
581 n_rules = cmap_insert(&subtable->rules, &new->cmap_node, hash);
582 } else { /* Equal rules exist in the classifier already. */
583 struct cls_match *prev, *iter;
584
585 /* Scan the list for the insertion point that will keep the list in
586 * order of decreasing priority. Insert after rules marked invisible
587 * in any version of the same priority. */
588 FOR_EACH_RULE_IN_LIST_PROTECTED (iter, prev, head) {
589 if (rule->priority > iter->priority
590 || (rule->priority == iter->priority
591 && !cls_match_is_eventually_invisible(iter))) {
592 break;
593 }
594 }
595
596 /* Replace 'iter' with 'new' or insert 'new' between 'prev' and
597 * 'iter'. */
598 if (iter) {
599 struct cls_rule *old;
600
601 if (rule->priority == iter->priority) {
602 cls_match_replace(prev, iter, new);
603 old = CONST_CAST(struct cls_rule *, iter->cls_rule);
604 } else {
605 cls_match_insert(prev, iter, new);
606 old = NULL;
607 }
608
609 /* Replace the existing head in data structures, if rule is the new
610 * head. */
611 if (iter == head) {
612 cmap_replace(&subtable->rules, &head->cmap_node,
613 &new->cmap_node, hash);
614 }
615
616 if (old) {
617 struct cls_conjunction_set *conj_set;
618
619 conj_set = ovsrcu_get_protected(struct cls_conjunction_set *,
620 &iter->conj_set);
621 if (conj_set) {
622 ovsrcu_postpone(free, conj_set);
623 }
624
625 ovsrcu_set(&old->cls_match, NULL); /* Marks old rule as removed
626 * from the classifier. */
627 ovsrcu_postpone(cls_match_free_cb, iter);
628
629 /* No change in subtable's max priority or max count. */
630
631 /* Make 'new' visible to lookups in the appropriate version. */
632 cls_match_set_remove_version(new, OVS_VERSION_NOT_REMOVED);
633
634 /* Make rule visible to iterators (immediately). */
635 rculist_replace(CONST_CAST(struct rculist *, &rule->node),
636 &old->node);
637
638 /* Return displaced rule. Caller is responsible for keeping it
639 * around until all threads quiesce. */
640 return old;
641 }
642 } else {
643 /* 'new' is new node after 'prev' */
644 cls_match_insert(prev, iter, new);
645 }
646 }
647
648 /* Make 'new' visible to lookups in the appropriate version. */
649 cls_match_set_remove_version(new, OVS_VERSION_NOT_REMOVED);
650
651 /* Make rule visible to iterators (immediately). */
652 rculist_push_back(&subtable->rules_list,
653 CONST_CAST(struct rculist *, &rule->node));
654
655 /* Rule was added, not replaced. Update 'subtable's 'max_priority' and
656 * 'max_count', if necessary.
657 *
658 * The rule was already inserted, but concurrent readers may not see the
659 * rule yet as the subtables vector is not updated yet. This will have to
660 * be fixed by revalidation later. */
661 if (n_rules == 1) {
662 subtable->max_priority = rule->priority;
663 subtable->max_count = 1;
664 pvector_insert(&cls->subtables, subtable, rule->priority);
665 } else if (rule->priority == subtable->max_priority) {
666 ++subtable->max_count;
667 } else if (rule->priority > subtable->max_priority) {
668 subtable->max_priority = rule->priority;
669 subtable->max_count = 1;
670 pvector_change_priority(&cls->subtables, subtable, rule->priority);
671 }
672
673 /* Nothing was replaced. */
674 cls->n_rules++;
675
676 if (cls->publish) {
677 pvector_publish(&cls->subtables);
678 }
679
680 return NULL;
681 }
682
683 /* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
684 * must not modify or free it.
685 *
686 * 'cls' must not contain an identical rule (including wildcards, values of
687 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
688 * such a rule. */
689 void
690 classifier_insert(struct classifier *cls, const struct cls_rule *rule,
691 ovs_version_t version, const struct cls_conjunction conj[],
692 size_t n_conj)
693 {
694 const struct cls_rule *displaced_rule
695 = classifier_replace(cls, rule, version, conj, n_conj);
696 ovs_assert(!displaced_rule);
697 }
698
699 /* If 'rule' is in 'cls', removes 'rule' from 'cls' and returns true. It is
700 * the caller's responsibility to destroy 'rule' with cls_rule_destroy(),
701 * freeing the memory block in which 'rule' resides, etc., as necessary.
702 *
703 * If 'rule' is not in any classifier, returns false without making any
704 * changes.
705 *
706 * 'rule' must not be in some classifier other than 'cls'.
707 */
708 bool
709 classifier_remove(struct classifier *cls, const struct cls_rule *cls_rule)
710 {
711 struct cls_match *rule, *prev, *next, *head;
712 struct cls_conjunction_set *conj_set;
713 struct cls_subtable *subtable;
714 uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
715 unsigned int mask_offset;
716 size_t n_rules;
717 unsigned int i;
718
719 rule = get_cls_match_protected(cls_rule);
720 if (!rule) {
721 return false;
722 }
723 /* Mark as removed. */
724 ovsrcu_set(&CONST_CAST(struct cls_rule *, cls_rule)->cls_match, NULL);
725
726 /* Remove 'cls_rule' from the subtable's rules list. */
727 rculist_remove(CONST_CAST(struct rculist *, &cls_rule->node));
728
729 subtable = find_subtable(cls, cls_rule->match.mask);
730 ovs_assert(subtable);
731
732 mask_offset = 0;
733 for (i = 0; i < subtable->n_indices; i++) {
734 ihash[i] = minimatch_hash_range(&cls_rule->match,
735 subtable->index_maps[i],
736 &mask_offset, &basis);
737 }
738 hash = minimatch_hash_range(&cls_rule->match, subtable->index_maps[i],
739 &mask_offset, &basis);
740
741 head = find_equal(subtable, cls_rule->match.flow, hash);
742
743 /* Check if the rule is not the head rule. */
744 if (rule != head) {
745 struct cls_match *iter;
746
747 /* Not the head rule, but potentially one with the same priority. */
748 /* Remove from the list of equal rules. */
749 FOR_EACH_RULE_IN_LIST_PROTECTED (iter, prev, head) {
750 if (rule == iter) {
751 break;
752 }
753 }
754 ovs_assert(iter == rule);
755
756 cls_match_remove(prev, rule);
757
758 goto check_priority;
759 }
760
761 /* 'rule' is the head rule. Check if there is another rule to
762 * replace 'rule' in the data structures. */
763 next = cls_match_next_protected(rule);
764 if (next) {
765 cmap_replace(&subtable->rules, &rule->cmap_node, &next->cmap_node,
766 hash);
767 goto check_priority;
768 }
769
770 /* 'rule' is last of the kind in the classifier, must remove from all the
771 * data structures. */
772
773 if (subtable->ports_mask_len) {
774 ovs_be32 masked_ports = minimatch_get_ports(&cls_rule->match);
775
776 trie_remove_prefix(&subtable->ports_trie,
777 &masked_ports, subtable->ports_mask_len);
778 }
779 for (i = 0; i < cls->n_tries; i++) {
780 if (subtable->trie_plen[i]) {
781 trie_remove(&cls->tries[i], cls_rule, subtable->trie_plen[i]);
782 }
783 }
784
785 /* Remove rule node from indices. */
786 for (i = 0; i < subtable->n_indices; i++) {
787 ccmap_dec(&subtable->indices[i], ihash[i]);
788 }
789 n_rules = cmap_remove(&subtable->rules, &rule->cmap_node, hash);
790
791 if (n_rules == 0) {
792 destroy_subtable(cls, subtable);
793 } else {
794 check_priority:
795 if (subtable->max_priority == rule->priority
796 && --subtable->max_count == 0) {
797 /* Find the new 'max_priority' and 'max_count'. */
798 int max_priority = INT_MIN;
799 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
800 if (head->priority > max_priority) {
801 max_priority = head->priority;
802 subtable->max_count = 1;
803 } else if (head->priority == max_priority) {
804 ++subtable->max_count;
805 }
806 }
807 subtable->max_priority = max_priority;
808 pvector_change_priority(&cls->subtables, subtable, max_priority);
809 }
810 }
811
812 if (cls->publish) {
813 pvector_publish(&cls->subtables);
814 }
815
816 /* free the rule. */
817 conj_set = ovsrcu_get_protected(struct cls_conjunction_set *,
818 &rule->conj_set);
819 if (conj_set) {
820 ovsrcu_postpone(free, conj_set);
821 }
822 ovsrcu_postpone(cls_match_free_cb, rule);
823 cls->n_rules--;
824
825 return true;
826 }
827
828 void
829 classifier_remove_assert(struct classifier *cls,
830 const struct cls_rule *cls_rule)
831 {
832 ovs_assert(classifier_remove(cls, cls_rule));
833 }
834
835 /* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
836 * subtables which have a prefix match on the trie field, but whose prefix
837 * length is not indicated in 'match_plens'. For example, a subtable that
838 * has a 8-bit trie field prefix match can be skipped if
839 * !be_get_bit_at(&match_plens, 8 - 1). If skipped, 'maskbits' prefix bits
840 * must be unwildcarded to make datapath flow only match packets it should. */
841 struct trie_ctx {
842 const struct cls_trie *trie;
843 bool lookup_done; /* Status of the lookup. */
844 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
845 union trie_prefix match_plens; /* Bitmask of prefix lengths with possible
846 * matches. */
847 };
848
849 static void
850 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
851 {
852 ctx->trie = trie;
853 ctx->lookup_done = false;
854 }
855
856 struct conjunctive_match {
857 struct hmap_node hmap_node;
858 uint32_t id;
859 uint64_t clauses;
860 };
861
862 static struct conjunctive_match *
863 find_conjunctive_match__(struct hmap *matches, uint64_t id, uint32_t hash)
864 {
865 struct conjunctive_match *m;
866
867 HMAP_FOR_EACH_IN_BUCKET (m, hmap_node, hash, matches) {
868 if (m->id == id) {
869 return m;
870 }
871 }
872 return NULL;
873 }
874
875 static bool
876 find_conjunctive_match(const struct cls_conjunction_set *set,
877 unsigned int max_n_clauses, struct hmap *matches,
878 struct conjunctive_match *cm_stubs, size_t n_cm_stubs,
879 uint32_t *idp)
880 {
881 const struct cls_conjunction *c;
882
883 if (max_n_clauses < set->min_n_clauses) {
884 return false;
885 }
886
887 for (c = set->conj; c < &set->conj[set->n]; c++) {
888 struct conjunctive_match *cm;
889 uint32_t hash;
890
891 if (c->n_clauses > max_n_clauses) {
892 continue;
893 }
894
895 hash = hash_int(c->id, 0);
896 cm = find_conjunctive_match__(matches, c->id, hash);
897 if (!cm) {
898 size_t n = hmap_count(matches);
899
900 cm = n < n_cm_stubs ? &cm_stubs[n] : xmalloc(sizeof *cm);
901 hmap_insert(matches, &cm->hmap_node, hash);
902 cm->id = c->id;
903 cm->clauses = UINT64_MAX << (c->n_clauses & 63);
904 }
905 cm->clauses |= UINT64_C(1) << c->clause;
906 if (cm->clauses == UINT64_MAX) {
907 *idp = cm->id;
908 return true;
909 }
910 }
911 return false;
912 }
913
914 static void
915 free_conjunctive_matches(struct hmap *matches,
916 struct conjunctive_match *cm_stubs, size_t n_cm_stubs)
917 {
918 if (hmap_count(matches) > n_cm_stubs) {
919 struct conjunctive_match *cm, *next;
920
921 HMAP_FOR_EACH_SAFE (cm, next, hmap_node, matches) {
922 if (!(cm >= cm_stubs && cm < &cm_stubs[n_cm_stubs])) {
923 free(cm);
924 }
925 }
926 }
927 hmap_destroy(matches);
928 }
929
930 /* Like classifier_lookup(), except that support for conjunctive matches can be
931 * configured with 'allow_conjunctive_matches'. That feature is not exposed
932 * externally because turning off conjunctive matches is only useful to avoid
933 * recursion within this function itself.
934 *
935 * 'flow' is non-const to allow for temporary modifications during the lookup.
936 * Any changes are restored before returning. */
937 static const struct cls_rule *
938 classifier_lookup__(const struct classifier *cls, ovs_version_t version,
939 struct flow *flow, struct flow_wildcards *wc,
940 bool allow_conjunctive_matches)
941 {
942 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
943 const struct cls_match *match;
944 /* Highest-priority flow in 'cls' that certainly matches 'flow'. */
945 const struct cls_match *hard = NULL;
946 int hard_pri = INT_MIN; /* hard ? hard->priority : INT_MIN. */
947
948 /* Highest-priority conjunctive flows in 'cls' matching 'flow'. Since
949 * these are (components of) conjunctive flows, we can only know whether
950 * the full conjunctive flow matches after seeing multiple of them. Thus,
951 * we refer to these as "soft matches". */
952 struct cls_conjunction_set *soft_stub[64];
953 struct cls_conjunction_set **soft = soft_stub;
954 size_t n_soft = 0, allocated_soft = ARRAY_SIZE(soft_stub);
955 int soft_pri = INT_MIN; /* n_soft ? MAX(soft[*]->priority) : INT_MIN. */
956
957 /* Synchronize for cls->n_tries and subtable->trie_plen. They can change
958 * when table configuration changes, which happens typically only on
959 * startup. */
960 atomic_thread_fence(memory_order_acquire);
961
962 /* Initialize trie contexts for find_match_wc(). */
963 for (int i = 0; i < cls->n_tries; i++) {
964 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
965 }
966
967 /* Main loop. */
968 struct cls_subtable *subtable;
969 PVECTOR_FOR_EACH_PRIORITY (subtable, hard_pri + 1, 2, sizeof *subtable,
970 &cls->subtables) {
971 struct cls_conjunction_set *conj_set;
972
973 /* Skip subtables with no match, or where the match is lower-priority
974 * than some certain match we've already found. */
975 match = find_match_wc(subtable, version, flow, trie_ctx, cls->n_tries,
976 wc);
977 if (!match || match->priority <= hard_pri) {
978 continue;
979 }
980
981 conj_set = ovsrcu_get(struct cls_conjunction_set *, &match->conj_set);
982 if (!conj_set) {
983 /* 'match' isn't part of a conjunctive match. It's the best
984 * certain match we've got so far, since we know that it's
985 * higher-priority than hard_pri.
986 *
987 * (There might be a higher-priority conjunctive match. We can't
988 * tell yet.) */
989 hard = match;
990 hard_pri = hard->priority;
991 } else if (allow_conjunctive_matches) {
992 /* 'match' is part of a conjunctive match. Add it to the list. */
993 if (OVS_UNLIKELY(n_soft >= allocated_soft)) {
994 struct cls_conjunction_set **old_soft = soft;
995
996 allocated_soft *= 2;
997 soft = xmalloc(allocated_soft * sizeof *soft);
998 memcpy(soft, old_soft, n_soft * sizeof *soft);
999 if (old_soft != soft_stub) {
1000 free(old_soft);
1001 }
1002 }
1003 soft[n_soft++] = conj_set;
1004
1005 /* Keep track of the highest-priority soft match. */
1006 if (soft_pri < match->priority) {
1007 soft_pri = match->priority;
1008 }
1009 }
1010 }
1011
1012 /* In the common case, at this point we have no soft matches and we can
1013 * return immediately. (We do the same thing if we have potential soft
1014 * matches but none of them are higher-priority than our hard match.) */
1015 if (hard_pri >= soft_pri) {
1016 if (soft != soft_stub) {
1017 free(soft);
1018 }
1019 return hard ? hard->cls_rule : NULL;
1020 }
1021
1022 /* At this point, we have some soft matches. We might also have a hard
1023 * match; if so, its priority is lower than the highest-priority soft
1024 * match. */
1025
1026 /* Soft match loop.
1027 *
1028 * Check whether soft matches are real matches. */
1029 for (;;) {
1030 /* Delete soft matches that are null. This only happens in second and
1031 * subsequent iterations of the soft match loop, when we drop back from
1032 * a high-priority soft match to a lower-priority one.
1033 *
1034 * Also, delete soft matches whose priority is less than or equal to
1035 * the hard match's priority. In the first iteration of the soft
1036 * match, these can be in 'soft' because the earlier main loop found
1037 * the soft match before the hard match. In second and later iteration
1038 * of the soft match loop, these can be in 'soft' because we dropped
1039 * back from a high-priority soft match to a lower-priority soft match.
1040 *
1041 * It is tempting to delete soft matches that cannot be satisfied
1042 * because there are fewer soft matches than required to satisfy any of
1043 * their conjunctions, but we cannot do that because there might be
1044 * lower priority soft or hard matches with otherwise identical
1045 * matches. (We could special case those here, but there's no
1046 * need--we'll do so at the bottom of the soft match loop anyway and
1047 * this duplicates less code.)
1048 *
1049 * It's also tempting to break out of the soft match loop if 'n_soft ==
1050 * 1' but that would also miss lower-priority hard matches. We could
1051 * special case that also but again there's no need. */
1052 for (int i = 0; i < n_soft; ) {
1053 if (!soft[i] || soft[i]->priority <= hard_pri) {
1054 soft[i] = soft[--n_soft];
1055 } else {
1056 i++;
1057 }
1058 }
1059 if (!n_soft) {
1060 break;
1061 }
1062
1063 /* Find the highest priority among the soft matches. (We know this
1064 * must be higher than the hard match's priority; otherwise we would
1065 * have deleted all of the soft matches in the previous loop.) Count
1066 * the number of soft matches that have that priority. */
1067 soft_pri = INT_MIN;
1068 int n_soft_pri = 0;
1069 for (int i = 0; i < n_soft; i++) {
1070 if (soft[i]->priority > soft_pri) {
1071 soft_pri = soft[i]->priority;
1072 n_soft_pri = 1;
1073 } else if (soft[i]->priority == soft_pri) {
1074 n_soft_pri++;
1075 }
1076 }
1077 ovs_assert(soft_pri > hard_pri);
1078
1079 /* Look for a real match among the highest-priority soft matches.
1080 *
1081 * It's unusual to have many conjunctive matches, so we use stubs to
1082 * avoid calling malloc() in the common case. An hmap has a built-in
1083 * stub for up to 2 hmap_nodes; possibly, we would benefit a variant
1084 * with a bigger stub. */
1085 struct conjunctive_match cm_stubs[16];
1086 struct hmap matches;
1087
1088 hmap_init(&matches);
1089 for (int i = 0; i < n_soft; i++) {
1090 uint32_t id;
1091
1092 if (soft[i]->priority == soft_pri
1093 && find_conjunctive_match(soft[i], n_soft_pri, &matches,
1094 cm_stubs, ARRAY_SIZE(cm_stubs),
1095 &id)) {
1096 uint32_t saved_conj_id = flow->conj_id;
1097 const struct cls_rule *rule;
1098
1099 flow->conj_id = id;
1100 rule = classifier_lookup__(cls, version, flow, wc, false);
1101 flow->conj_id = saved_conj_id;
1102
1103 if (rule) {
1104 free_conjunctive_matches(&matches,
1105 cm_stubs, ARRAY_SIZE(cm_stubs));
1106 if (soft != soft_stub) {
1107 free(soft);
1108 }
1109 return rule;
1110 }
1111 }
1112 }
1113 free_conjunctive_matches(&matches, cm_stubs, ARRAY_SIZE(cm_stubs));
1114
1115 /* There's no real match among the highest-priority soft matches.
1116 * However, if any of those soft matches has a lower-priority but
1117 * otherwise identical flow match, then we need to consider those for
1118 * soft or hard matches.
1119 *
1120 * The next iteration of the soft match loop will delete any null
1121 * pointers we put into 'soft' (and some others too). */
1122 for (int i = 0; i < n_soft; i++) {
1123 if (soft[i]->priority != soft_pri) {
1124 continue;
1125 }
1126
1127 /* Find next-lower-priority flow with identical flow match. */
1128 match = next_visible_rule_in_list(soft[i]->match, version);
1129 if (match) {
1130 soft[i] = ovsrcu_get(struct cls_conjunction_set *,
1131 &match->conj_set);
1132 if (!soft[i]) {
1133 /* The flow is a hard match; don't treat as a soft
1134 * match. */
1135 if (match->priority > hard_pri) {
1136 hard = match;
1137 hard_pri = hard->priority;
1138 }
1139 }
1140 } else {
1141 /* No such lower-priority flow (probably the common case). */
1142 soft[i] = NULL;
1143 }
1144 }
1145 }
1146
1147 if (soft != soft_stub) {
1148 free(soft);
1149 }
1150 return hard ? hard->cls_rule : NULL;
1151 }
1152
1153 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow' and
1154 * that is visible in 'version'. Returns a null pointer if no rules in 'cls'
1155 * match 'flow'. If multiple rules of equal priority match 'flow', returns one
1156 * arbitrarily.
1157 *
1158 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
1159 * set of bits that were significant in the lookup. At some point
1160 * earlier, 'wc' should have been initialized (e.g., by
1161 * flow_wildcards_init_catchall()).
1162 *
1163 * 'flow' is non-const to allow for temporary modifications during the lookup.
1164 * Any changes are restored before returning. */
1165 const struct cls_rule *
1166 classifier_lookup(const struct classifier *cls, ovs_version_t version,
1167 struct flow *flow, struct flow_wildcards *wc)
1168 {
1169 return classifier_lookup__(cls, version, flow, wc, true);
1170 }
1171
1172 /* Finds and returns a rule in 'cls' with exactly the same priority and
1173 * matching criteria as 'target', and that is visible in 'version'.
1174 * Only one such rule may ever exist. Returns a null pointer if 'cls' doesn't
1175 * contain an exact match. */
1176 const struct cls_rule *
1177 classifier_find_rule_exactly(const struct classifier *cls,
1178 const struct cls_rule *target,
1179 ovs_version_t version)
1180 {
1181 const struct cls_match *head, *rule;
1182 const struct cls_subtable *subtable;
1183
1184 subtable = find_subtable(cls, target->match.mask);
1185 if (!subtable) {
1186 return NULL;
1187 }
1188
1189 head = find_equal(subtable, target->match.flow,
1190 miniflow_hash_in_minimask(target->match.flow,
1191 target->match.mask, 0));
1192 if (!head) {
1193 return NULL;
1194 }
1195 CLS_MATCH_FOR_EACH (rule, head) {
1196 if (rule->priority < target->priority) {
1197 break; /* Not found. */
1198 }
1199 if (rule->priority == target->priority
1200 && cls_match_visible_in_version(rule, version)) {
1201 return rule->cls_rule;
1202 }
1203 }
1204 return NULL;
1205 }
1206
1207 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
1208 * same matching criteria as 'target', and that is visible in 'version'.
1209 * Returns a null pointer if 'cls' doesn't contain an exact match visible in
1210 * 'version'. */
1211 const struct cls_rule *
1212 classifier_find_match_exactly(const struct classifier *cls,
1213 const struct match *target, int priority,
1214 ovs_version_t version)
1215 {
1216 const struct cls_rule *retval;
1217 struct cls_rule cr;
1218
1219 cls_rule_init(&cr, target, priority);
1220 retval = classifier_find_rule_exactly(cls, &cr, version);
1221 cls_rule_destroy(&cr);
1222
1223 return retval;
1224 }
1225
1226 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
1227 * same matching criteria as 'target', and that is visible in 'version'.
1228 * Returns a null pointer if 'cls' doesn't contain an exact match visible in
1229 * 'version'. */
1230 const struct cls_rule *
1231 classifier_find_minimatch_exactly(const struct classifier *cls,
1232 const struct minimatch *target, int priority,
1233 ovs_version_t version)
1234 {
1235 const struct cls_rule *retval;
1236 struct cls_rule cr;
1237
1238 cls_rule_init_from_minimatch(&cr, target, priority);
1239 retval = classifier_find_rule_exactly(cls, &cr, version);
1240 cls_rule_destroy(&cr);
1241
1242 return retval;
1243 }
1244
1245 /* Checks if 'target' would overlap any other rule in 'cls' in 'version'. Two
1246 * rules are considered to overlap if both rules have the same priority and a
1247 * packet could match both, and if both rules are visible in the same version.
1248 *
1249 * A trivial example of overlapping rules is two rules matching disjoint sets
1250 * of fields. E.g., if one rule matches only on port number, while another only
1251 * on dl_type, any packet from that specific port and with that specific
1252 * dl_type could match both, if the rules also have the same priority. */
1253 bool
1254 classifier_rule_overlaps(const struct classifier *cls,
1255 const struct cls_rule *target, ovs_version_t version)
1256 {
1257 struct cls_subtable *subtable;
1258
1259 /* Iterate subtables in the descending max priority order. */
1260 PVECTOR_FOR_EACH_PRIORITY (subtable, target->priority, 2,
1261 sizeof(struct cls_subtable), &cls->subtables) {
1262 struct {
1263 struct minimask mask;
1264 uint64_t storage[FLOW_U64S];
1265 } m;
1266 const struct cls_rule *rule;
1267
1268 minimask_combine(&m.mask, target->match.mask, &subtable->mask,
1269 m.storage);
1270
1271 RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
1272 if (rule->priority == target->priority
1273 && miniflow_equal_in_minimask(target->match.flow,
1274 rule->match.flow, &m.mask)
1275 && cls_rule_visible_in_version(rule, version)) {
1276 return true;
1277 }
1278 }
1279 }
1280 return false;
1281 }
1282
1283 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
1284 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
1285 * function returns true if, for every field:
1286 *
1287 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
1288 * field, or
1289 *
1290 * - 'criteria' wildcards the field,
1291 *
1292 * Conversely, 'rule' does not match 'criteria' and this function returns false
1293 * if, for at least one field:
1294 *
1295 * - 'criteria' and 'rule' specify different values for the field, or
1296 *
1297 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
1298 *
1299 * Equivalently, the truth table for whether a field matches is:
1300 *
1301 * rule
1302 *
1303 * c wildcard exact
1304 * r +---------+---------+
1305 * i wild | yes | yes |
1306 * t card | | |
1307 * e +---------+---------+
1308 * r exact | no |if values|
1309 * i | |are equal|
1310 * a +---------+---------+
1311 *
1312 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
1313 * commands and by OpenFlow 1.0 aggregate and flow stats.
1314 *
1315 * Ignores rule->priority. */
1316 bool
1317 cls_rule_is_loose_match(const struct cls_rule *rule,
1318 const struct minimatch *criteria)
1319 {
1320 return (!minimask_has_extra(rule->match.mask, criteria->mask)
1321 && miniflow_equal_in_minimask(rule->match.flow, criteria->flow,
1322 criteria->mask));
1323 }
1324 \f
1325 /* Iteration. */
1326
1327 static bool
1328 rule_matches(const struct cls_rule *rule, const struct cls_rule *target,
1329 ovs_version_t version)
1330 {
1331 /* Rule may only match a target if it is visible in target's version. */
1332 return cls_rule_visible_in_version(rule, version)
1333 && (!target || miniflow_equal_in_minimask(rule->match.flow,
1334 target->match.flow,
1335 target->match.mask));
1336 }
1337
1338 static const struct cls_rule *
1339 search_subtable(const struct cls_subtable *subtable,
1340 struct cls_cursor *cursor)
1341 {
1342 if (!cursor->target
1343 || !minimask_has_extra(&subtable->mask, cursor->target->match.mask)) {
1344 const struct cls_rule *rule;
1345
1346 RCULIST_FOR_EACH (rule, node, &subtable->rules_list) {
1347 if (rule_matches(rule, cursor->target, cursor->version)) {
1348 return rule;
1349 }
1350 }
1351 }
1352 return NULL;
1353 }
1354
1355 /* Initializes 'cursor' for iterating through rules in 'cls', and returns the
1356 * cursor.
1357 *
1358 * - If 'target' is null, or if the 'target' is a catchall target, the
1359 * cursor will visit every rule in 'cls' that is visible in 'version'.
1360 *
1361 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1362 * such that cls_rule_is_loose_match(rule, target) returns true and that
1363 * the rule is visible in 'version'.
1364 *
1365 * Ignores target->priority. */
1366 struct cls_cursor
1367 cls_cursor_start(const struct classifier *cls, const struct cls_rule *target,
1368 ovs_version_t version)
1369 {
1370 struct cls_cursor cursor;
1371 struct cls_subtable *subtable;
1372
1373 memset(&cursor, 0x0, sizeof cursor);
1374 cursor.cls = cls;
1375 cursor.target = target && !cls_rule_is_catchall(target) ? target : NULL;
1376 cursor.version = version;
1377 cursor.rule = NULL;
1378
1379 /* Find first rule. */
1380 PVECTOR_CURSOR_FOR_EACH (subtable, &cursor.subtables,
1381 &cursor.cls->subtables) {
1382 const struct cls_rule *rule = search_subtable(subtable, &cursor);
1383
1384 if (rule) {
1385 cursor.subtable = subtable;
1386 cursor.rule = rule;
1387 break;
1388 }
1389 }
1390
1391 return cursor;
1392 }
1393
1394 static const struct cls_rule *
1395 cls_cursor_next(struct cls_cursor *cursor)
1396 {
1397 const struct cls_rule *rule;
1398 const struct cls_subtable *subtable;
1399
1400 rule = cursor->rule;
1401 subtable = cursor->subtable;
1402 RCULIST_FOR_EACH_CONTINUE (rule, node, &subtable->rules_list) {
1403 if (rule_matches(rule, cursor->target, cursor->version)) {
1404 return rule;
1405 }
1406 }
1407
1408 PVECTOR_CURSOR_FOR_EACH_CONTINUE (subtable, &cursor->subtables) {
1409 rule = search_subtable(subtable, cursor);
1410 if (rule) {
1411 cursor->subtable = subtable;
1412 return rule;
1413 }
1414 }
1415
1416 return NULL;
1417 }
1418
1419 /* Sets 'cursor->rule' to the next matching cls_rule in 'cursor''s iteration,
1420 * or to null if all matching rules have been visited. */
1421 void
1422 cls_cursor_advance(struct cls_cursor *cursor)
1423 {
1424 cursor->rule = cls_cursor_next(cursor);
1425 }
1426 \f
1427 static struct cls_subtable *
1428 find_subtable(const struct classifier *cls, const struct minimask *mask)
1429 {
1430 struct cls_subtable *subtable;
1431
1432 CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, minimask_hash(mask, 0),
1433 &cls->subtables_map) {
1434 if (minimask_equal(mask, &subtable->mask)) {
1435 return subtable;
1436 }
1437 }
1438 return NULL;
1439 }
1440
1441 /* Initializes 'map' with a subset of 'miniflow''s maps that includes only the
1442 * portions with u64-offset 'i' such that 'start' <= i < 'end'. Does not copy
1443 * any data from 'miniflow' to 'map'. */
1444 static struct flowmap
1445 miniflow_get_map_in_range(const struct miniflow *miniflow, uint8_t start,
1446 uint8_t end)
1447 {
1448 struct flowmap map;
1449 size_t ofs = 0;
1450
1451 map = miniflow->map;
1452
1453 /* Clear the bits before 'start'. */
1454 while (start >= MAP_T_BITS) {
1455 start -= MAP_T_BITS;
1456 ofs += MAP_T_BITS;
1457 map.bits[start / MAP_T_BITS] = 0;
1458 }
1459 if (start > 0) {
1460 flowmap_clear(&map, ofs, start);
1461 }
1462
1463 /* Clear the bits starting at 'end'. */
1464 if (end < FLOW_U64S) {
1465 /* flowmap_clear() can handle at most MAP_T_BITS at a time. */
1466 ovs_assert(FLOW_U64S - end <= MAP_T_BITS);
1467 flowmap_clear(&map, end, FLOW_U64S - end);
1468 }
1469 return map;
1470 }
1471
1472 static void
1473 subtable_destroy_cb(struct cls_subtable *subtable)
1474 {
1475 int i;
1476
1477 ovs_assert(ovsrcu_get_protected(struct trie_node *, &subtable->ports_trie)
1478 == NULL);
1479 ovs_assert(cmap_is_empty(&subtable->rules));
1480 ovs_assert(rculist_is_empty(&subtable->rules_list));
1481
1482 for (i = 0; i < subtable->n_indices; i++) {
1483 ccmap_destroy(&subtable->indices[i]);
1484 }
1485 cmap_destroy(&subtable->rules);
1486
1487 ovsrcu_postpone(free, subtable);
1488 }
1489
1490 /* The new subtable will be visible to the readers only after this. */
1491 static struct cls_subtable *
1492 insert_subtable(struct classifier *cls, const struct minimask *mask)
1493 {
1494 uint32_t hash = minimask_hash(mask, 0);
1495 struct cls_subtable *subtable;
1496 int i, index = 0;
1497 struct flowmap stage_map;
1498 uint8_t prev;
1499 size_t count = miniflow_n_values(&mask->masks);
1500
1501 subtable = xzalloc(sizeof *subtable + MINIFLOW_VALUES_SIZE(count));
1502 cmap_init(&subtable->rules);
1503 miniflow_clone(CONST_CAST(struct miniflow *, &subtable->mask.masks),
1504 &mask->masks, count);
1505
1506 /* Init indices for segmented lookup, if any. */
1507 prev = 0;
1508 for (i = 0; i < cls->n_flow_segments; i++) {
1509 stage_map = miniflow_get_map_in_range(&mask->masks, prev,
1510 cls->flow_segments[i]);
1511 /* Add an index if it adds mask bits. */
1512 if (!flowmap_is_empty(stage_map)) {
1513 ccmap_init(&subtable->indices[index]);
1514 *CONST_CAST(struct flowmap *, &subtable->index_maps[index])
1515 = stage_map;
1516 index++;
1517 }
1518 prev = cls->flow_segments[i];
1519 }
1520 /* Map for the final stage. */
1521 *CONST_CAST(struct flowmap *, &subtable->index_maps[index])
1522 = miniflow_get_map_in_range(&mask->masks, prev, FLOW_U64S);
1523 /* Check if the final stage adds any bits. */
1524 if (index > 0) {
1525 if (flowmap_is_empty(subtable->index_maps[index])) {
1526 /* Remove the last index, as it has the same fields as the rules
1527 * map. */
1528 --index;
1529 ccmap_destroy(&subtable->indices[index]);
1530 }
1531 }
1532 *CONST_CAST(uint8_t *, &subtable->n_indices) = index;
1533
1534 for (i = 0; i < cls->n_tries; i++) {
1535 const struct mf_field *field
1536 = ovsrcu_get(struct mf_field *, &cls->tries[i].field);
1537 subtable->trie_plen[i]
1538 = field ? minimask_get_prefix_len(mask, field) : 0;
1539 }
1540
1541 /* Ports trie. */
1542 ovsrcu_set_hidden(&subtable->ports_trie, NULL);
1543 *CONST_CAST(int *, &subtable->ports_mask_len)
1544 = 32 - ctz32(ntohl(miniflow_get_ports(&mask->masks)));
1545
1546 /* List of rules. */
1547 rculist_init(&subtable->rules_list);
1548
1549 cmap_insert(&cls->subtables_map, &subtable->cmap_node, hash);
1550
1551 return subtable;
1552 }
1553
1554 /* RCU readers may still access the subtable before it is actually freed. */
1555 static void
1556 destroy_subtable(struct classifier *cls, struct cls_subtable *subtable)
1557 {
1558 pvector_remove(&cls->subtables, subtable);
1559 cmap_remove(&cls->subtables_map, &subtable->cmap_node,
1560 minimask_hash(&subtable->mask, 0));
1561
1562 ovsrcu_postpone(subtable_destroy_cb, subtable);
1563 }
1564
1565 static unsigned int be_get_bit_at(const ovs_be32 value[], unsigned int ofs);
1566
1567 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1568 * lookup results. */
1569 static inline bool
1570 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1571 const unsigned int field_plen[CLS_MAX_TRIES],
1572 const struct flowmap range_map, const struct flow *flow,
1573 struct flow_wildcards *wc)
1574 {
1575 int j;
1576
1577 /* Check if we could avoid fully unwildcarding the next level of
1578 * fields using the prefix tries. The trie checks are done only as
1579 * needed to avoid folding in additional bits to the wildcards mask. */
1580 for (j = 0; j < n_tries; j++) {
1581 /* Is the trie field relevant for this subtable? */
1582 if (field_plen[j]) {
1583 struct trie_ctx *ctx = &trie_ctx[j];
1584 const struct mf_field *ctx_field
1585 = ovsrcu_get(struct mf_field *, &ctx->trie->field);
1586
1587 /* Is the trie field within the current range of fields? */
1588 if (!ctx_field
1589 || !flowmap_is_set(&range_map, ctx_field->flow_be32ofs / 2)) {
1590 continue;
1591 }
1592
1593 /* On-demand trie lookup. */
1594 if (!ctx->lookup_done) {
1595 memset(&ctx->match_plens, 0, sizeof ctx->match_plens);
1596 ctx->maskbits = trie_lookup(ctx->trie, flow, &ctx->match_plens);
1597 ctx->lookup_done = true;
1598 }
1599 /* Possible to skip the rest of the subtable if subtable's
1600 * prefix on the field is not included in the lookup result. */
1601 if (!be_get_bit_at(&ctx->match_plens.be32, field_plen[j] - 1)) {
1602 /* We want the trie lookup to never result in unwildcarding
1603 * any bits that would not be unwildcarded otherwise.
1604 * Since the trie is shared by the whole classifier, it is
1605 * possible that the 'maskbits' contain bits that are
1606 * irrelevant for the partition relevant for the current
1607 * packet. Hence the checks below. */
1608
1609 /* Check that the trie result will not unwildcard more bits
1610 * than this subtable would otherwise. */
1611 if (ctx->maskbits <= field_plen[j]) {
1612 /* Unwildcard the bits and skip the rest. */
1613 mask_set_prefix_bits(wc, ctx_field->flow_be32ofs,
1614 ctx->maskbits);
1615 /* Note: Prerequisite already unwildcarded, as the only
1616 * prerequisite of the supported trie lookup fields is
1617 * the ethertype, which is always unwildcarded. */
1618 return true;
1619 }
1620 /* Can skip if the field is already unwildcarded. */
1621 if (mask_prefix_bits_set(wc, ctx_field->flow_be32ofs,
1622 ctx->maskbits)) {
1623 return true;
1624 }
1625 }
1626 }
1627 }
1628 return false;
1629 }
1630
1631 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1632 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1633 * value has the correct value in 'target'.
1634 *
1635 * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
1636 * target, mask) but this is faster because of the invariant that
1637 * flow->map and mask->masks.map are the same, and that this version
1638 * takes the 'wc'. */
1639 static inline bool
1640 miniflow_and_mask_matches_flow(const struct miniflow *flow,
1641 const struct minimask *mask,
1642 const struct flow *target)
1643 {
1644 const uint64_t *flowp = miniflow_get_values(flow);
1645 const uint64_t *maskp = miniflow_get_values(&mask->masks);
1646 const uint64_t *target_u64 = (const uint64_t *)target;
1647 map_t map;
1648
1649 FLOWMAP_FOR_EACH_MAP (map, mask->masks.map) {
1650 size_t idx;
1651
1652 MAP_FOR_EACH_INDEX (idx, map) {
1653 if ((*flowp++ ^ target_u64[idx]) & *maskp++) {
1654 return false;
1655 }
1656 }
1657 target_u64 += MAP_T_BITS;
1658 }
1659 return true;
1660 }
1661
1662 static inline const struct cls_match *
1663 find_match(const struct cls_subtable *subtable, ovs_version_t version,
1664 const struct flow *flow, uint32_t hash)
1665 {
1666 const struct cls_match *head, *rule;
1667
1668 CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1669 if (OVS_LIKELY(miniflow_and_mask_matches_flow(&head->flow,
1670 &subtable->mask,
1671 flow))) {
1672 /* Return highest priority rule that is visible. */
1673 CLS_MATCH_FOR_EACH (rule, head) {
1674 if (OVS_LIKELY(cls_match_visible_in_version(rule, version))) {
1675 return rule;
1676 }
1677 }
1678 }
1679 }
1680
1681 return NULL;
1682 }
1683
1684 static const struct cls_match *
1685 find_match_wc(const struct cls_subtable *subtable, ovs_version_t version,
1686 const struct flow *flow, struct trie_ctx trie_ctx[CLS_MAX_TRIES],
1687 unsigned int n_tries, struct flow_wildcards *wc)
1688 {
1689 if (OVS_UNLIKELY(!wc)) {
1690 return find_match(subtable, version, flow,
1691 flow_hash_in_minimask(flow, &subtable->mask, 0));
1692 }
1693
1694 uint32_t basis = 0, hash;
1695 const struct cls_match *rule = NULL;
1696 struct flowmap stages_map = FLOWMAP_EMPTY_INITIALIZER;
1697 unsigned int mask_offset = 0;
1698 int i;
1699
1700 /* Try to finish early by checking fields in segments. */
1701 for (i = 0; i < subtable->n_indices; i++) {
1702 if (check_tries(trie_ctx, n_tries, subtable->trie_plen,
1703 subtable->index_maps[i], flow, wc)) {
1704 /* 'wc' bits for the trie field set, now unwildcard the preceding
1705 * bits used so far. */
1706 goto no_match;
1707 }
1708
1709 /* Accumulate the map used so far. */
1710 stages_map = flowmap_or(stages_map, subtable->index_maps[i]);
1711
1712 hash = flow_hash_in_minimask_range(flow, &subtable->mask,
1713 subtable->index_maps[i],
1714 &mask_offset, &basis);
1715
1716 if (!ccmap_find(&subtable->indices[i], hash)) {
1717 goto no_match;
1718 }
1719 }
1720 /* Trie check for the final range. */
1721 if (check_tries(trie_ctx, n_tries, subtable->trie_plen,
1722 subtable->index_maps[i], flow, wc)) {
1723 goto no_match;
1724 }
1725 hash = flow_hash_in_minimask_range(flow, &subtable->mask,
1726 subtable->index_maps[i],
1727 &mask_offset, &basis);
1728 rule = find_match(subtable, version, flow, hash);
1729 if (!rule && subtable->ports_mask_len) {
1730 /* The final stage had ports, but there was no match. Instead of
1731 * unwildcarding all the ports bits, use the ports trie to figure out a
1732 * smaller set of bits to unwildcard. */
1733 unsigned int mbits;
1734 ovs_be32 value, plens, mask;
1735
1736 mask = miniflow_get_ports(&subtable->mask.masks);
1737 value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
1738 mbits = trie_lookup_value(&subtable->ports_trie, &value, &plens, 32);
1739
1740 ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
1741 mask & be32_prefix_mask(mbits);
1742
1743 goto no_match;
1744 }
1745
1746 /* Must unwildcard all the fields, as they were looked at. */
1747 flow_wildcards_fold_minimask(wc, &subtable->mask);
1748 return rule;
1749
1750 no_match:
1751 /* Unwildcard the bits in stages so far, as they were used in determining
1752 * there is no match. */
1753 flow_wildcards_fold_minimask_in_map(wc, &subtable->mask, stages_map);
1754 return NULL;
1755 }
1756
1757 static struct cls_match *
1758 find_equal(const struct cls_subtable *subtable, const struct miniflow *flow,
1759 uint32_t hash)
1760 {
1761 struct cls_match *head;
1762
1763 CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1764 if (miniflow_equal(&head->flow, flow)) {
1765 return head;
1766 }
1767 }
1768 return NULL;
1769 }
1770 \f
1771 /* A longest-prefix match tree. */
1772
1773 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1774 * Prefixes are in the network byte order, and the offset 0 corresponds to
1775 * the most significant bit of the first byte. The offset can be read as
1776 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1777 static uint32_t
1778 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1779 {
1780 uint32_t prefix;
1781
1782 pr += ofs / 32; /* Where to start. */
1783 ofs %= 32; /* How many bits to skip at 'pr'. */
1784
1785 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1786 if (plen > 32 - ofs) { /* Need more than we have already? */
1787 prefix |= ntohl(*++pr) >> (32 - ofs);
1788 }
1789 /* Return with possible unwanted bits at the end. */
1790 return prefix;
1791 }
1792
1793 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1794 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1795 * corresponds to the most significant bit of the first byte. The offset can
1796 * be read as "how many bits to skip from the start of the prefix starting at
1797 * 'pr'". */
1798 static uint32_t
1799 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1800 {
1801 if (!plen) {
1802 return 0;
1803 }
1804 if (plen > TRIE_PREFIX_BITS) {
1805 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1806 }
1807 /* Return with unwanted bits cleared. */
1808 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1809 }
1810
1811 /* Return the number of equal bits in 'n_bits' of 'prefix's MSBs and a 'value'
1812 * starting at "MSB 0"-based offset 'ofs'. */
1813 static unsigned int
1814 prefix_equal_bits(uint32_t prefix, unsigned int n_bits, const ovs_be32 value[],
1815 unsigned int ofs)
1816 {
1817 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, n_bits);
1818 /* Set the bit after the relevant bits to limit the result. */
1819 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - n_bits));
1820 }
1821
1822 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1823 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1824 static unsigned int
1825 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1826 unsigned int ofs, unsigned int plen)
1827 {
1828 return prefix_equal_bits(node->prefix, MIN(node->n_bits, plen - ofs),
1829 prefix, ofs);
1830 }
1831
1832 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1833 * be greater than 31. */
1834 static unsigned int
1835 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1836 {
1837 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1838 }
1839
1840 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1841 * be between 0 and 31, inclusive. */
1842 static unsigned int
1843 get_bit_at(const uint32_t prefix, unsigned int ofs)
1844 {
1845 return (prefix >> (31 - ofs)) & 1u;
1846 }
1847
1848 /* Create new branch. */
1849 static struct trie_node *
1850 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1851 unsigned int n_rules)
1852 {
1853 struct trie_node *node = xmalloc(sizeof *node);
1854
1855 node->prefix = trie_get_prefix(prefix, ofs, plen);
1856
1857 if (plen <= TRIE_PREFIX_BITS) {
1858 node->n_bits = plen;
1859 ovsrcu_set_hidden(&node->edges[0], NULL);
1860 ovsrcu_set_hidden(&node->edges[1], NULL);
1861 node->n_rules = n_rules;
1862 } else { /* Need intermediate nodes. */
1863 struct trie_node *subnode = trie_branch_create(prefix,
1864 ofs + TRIE_PREFIX_BITS,
1865 plen - TRIE_PREFIX_BITS,
1866 n_rules);
1867 int bit = get_bit_at(subnode->prefix, 0);
1868 node->n_bits = TRIE_PREFIX_BITS;
1869 ovsrcu_set_hidden(&node->edges[bit], subnode);
1870 ovsrcu_set_hidden(&node->edges[!bit], NULL);
1871 node->n_rules = 0;
1872 }
1873 return node;
1874 }
1875
1876 static void
1877 trie_node_destroy(const struct trie_node *node)
1878 {
1879 ovsrcu_postpone(free, CONST_CAST(struct trie_node *, node));
1880 }
1881
1882 /* Copy a trie node for modification and postpone delete the old one. */
1883 static struct trie_node *
1884 trie_node_rcu_realloc(const struct trie_node *node)
1885 {
1886 struct trie_node *new_node = xmalloc(sizeof *node);
1887
1888 *new_node = *node;
1889 trie_node_destroy(node);
1890
1891 return new_node;
1892 }
1893
1894 static void
1895 trie_destroy(rcu_trie_ptr *trie)
1896 {
1897 struct trie_node *node = ovsrcu_get_protected(struct trie_node *, trie);
1898
1899 if (node) {
1900 ovsrcu_set_hidden(trie, NULL);
1901 trie_destroy(&node->edges[0]);
1902 trie_destroy(&node->edges[1]);
1903 trie_node_destroy(node);
1904 }
1905 }
1906
1907 static bool
1908 trie_is_leaf(const struct trie_node *trie)
1909 {
1910 /* No children? */
1911 return !ovsrcu_get(struct trie_node *, &trie->edges[0])
1912 && !ovsrcu_get(struct trie_node *, &trie->edges[1]);
1913 }
1914
1915 static void
1916 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1917 unsigned int n_bits)
1918 {
1919 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1920 unsigned int i;
1921
1922 for (i = 0; i < n_bits / 32; i++) {
1923 mask[i] = OVS_BE32_MAX;
1924 }
1925 if (n_bits % 32) {
1926 mask[i] |= htonl(~0u << (32 - n_bits % 32));
1927 }
1928 }
1929
1930 static bool
1931 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
1932 unsigned int n_bits)
1933 {
1934 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1935 unsigned int i;
1936 ovs_be32 zeroes = 0;
1937
1938 for (i = 0; i < n_bits / 32; i++) {
1939 zeroes |= ~mask[i];
1940 }
1941 if (n_bits % 32) {
1942 zeroes |= ~mask[i] & htonl(~0u << (32 - n_bits % 32));
1943 }
1944
1945 return !zeroes; /* All 'n_bits' bits set. */
1946 }
1947
1948 static rcu_trie_ptr *
1949 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
1950 unsigned int ofs)
1951 {
1952 return node->edges + be_get_bit_at(value, ofs);
1953 }
1954
1955 static const struct trie_node *
1956 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
1957 unsigned int ofs)
1958 {
1959 return ovsrcu_get(struct trie_node *,
1960 &node->edges[be_get_bit_at(value, ofs)]);
1961 }
1962
1963 /* Set the bit at ("MSB 0"-based) offset 'ofs'. 'ofs' can be greater than 31.
1964 */
1965 static void
1966 be_set_bit_at(ovs_be32 value[], unsigned int ofs)
1967 {
1968 ((uint8_t *)value)[ofs / 8] |= 1u << (7 - ofs % 8);
1969 }
1970
1971 /* Returns the number of bits in the prefix mask necessary to determine a
1972 * mismatch, in case there are longer prefixes in the tree below the one that
1973 * matched.
1974 * '*plens' will have a bit set for each prefix length that may have matching
1975 * rules. The caller is responsible for clearing the '*plens' prior to
1976 * calling this.
1977 */
1978 static unsigned int
1979 trie_lookup_value(const rcu_trie_ptr *trie, const ovs_be32 value[],
1980 ovs_be32 plens[], unsigned int n_bits)
1981 {
1982 const struct trie_node *prev = NULL;
1983 const struct trie_node *node = ovsrcu_get(struct trie_node *, trie);
1984 unsigned int match_len = 0; /* Number of matching bits. */
1985
1986 for (; node; prev = node, node = trie_next_node(node, value, match_len)) {
1987 unsigned int eqbits;
1988 /* Check if this edge can be followed. */
1989 eqbits = prefix_equal_bits(node->prefix, node->n_bits, value,
1990 match_len);
1991 match_len += eqbits;
1992 if (eqbits < node->n_bits) { /* Mismatch, nothing more to be found. */
1993 /* Bit at offset 'match_len' differed. */
1994 return match_len + 1; /* Includes the first mismatching bit. */
1995 }
1996 /* Full match, check if rules exist at this prefix length. */
1997 if (node->n_rules > 0) {
1998 be_set_bit_at(plens, match_len - 1);
1999 }
2000 if (match_len >= n_bits) {
2001 return n_bits; /* Full prefix. */
2002 }
2003 }
2004 /* node == NULL. Full match so far, but we tried to follow an
2005 * non-existing branch. Need to exclude the other branch if it exists
2006 * (it does not if we were called on an empty trie or 'prev' is a leaf
2007 * node). */
2008 return !prev || trie_is_leaf(prev) ? match_len : match_len + 1;
2009 }
2010
2011 static unsigned int
2012 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
2013 union trie_prefix *plens)
2014 {
2015 const struct mf_field *mf = ovsrcu_get(struct mf_field *, &trie->field);
2016
2017 /* Check that current flow matches the prerequisites for the trie
2018 * field. Some match fields are used for multiple purposes, so we
2019 * must check that the trie is relevant for this flow. */
2020 if (mf && mf_are_prereqs_ok(mf, flow, NULL)) {
2021 return trie_lookup_value(&trie->root,
2022 &((ovs_be32 *)flow)[mf->flow_be32ofs],
2023 &plens->be32, mf->n_bits);
2024 }
2025 memset(plens, 0xff, sizeof *plens); /* All prefixes, no skipping. */
2026 return 0; /* Value not used in this case. */
2027 }
2028
2029 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
2030 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
2031 * 'miniflow_index' is not NULL. */
2032 static unsigned int
2033 minimask_get_prefix_len(const struct minimask *minimask,
2034 const struct mf_field *mf)
2035 {
2036 unsigned int n_bits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
2037 uint8_t be32_ofs = mf->flow_be32ofs;
2038 uint8_t be32_end = be32_ofs + mf->n_bytes / 4;
2039
2040 for (; be32_ofs < be32_end; ++be32_ofs) {
2041 uint32_t mask = ntohl(minimask_get_be32(minimask, be32_ofs));
2042
2043 /* Validate mask, count the mask length. */
2044 if (mask_tz) {
2045 if (mask) {
2046 return 0; /* No bits allowed after mask ended. */
2047 }
2048 } else {
2049 if (~mask & (~mask + 1)) {
2050 return 0; /* Mask not contiguous. */
2051 }
2052 mask_tz = ctz32(mask);
2053 n_bits += 32 - mask_tz;
2054 }
2055 }
2056
2057 return n_bits;
2058 }
2059
2060 /*
2061 * This is called only when mask prefix is known to be CIDR and non-zero.
2062 * Relies on the fact that the flow and mask have the same map, and since
2063 * the mask is CIDR, the storage for the flow field exists even if it
2064 * happened to be zeros.
2065 */
2066 static const ovs_be32 *
2067 minimatch_get_prefix(const struct minimatch *match, rcu_field_ptr *field)
2068 {
2069 struct mf_field *mf = ovsrcu_get_protected(struct mf_field *, field);
2070 size_t u64_ofs = mf->flow_be32ofs / 2;
2071
2072 return (OVS_FORCE const ovs_be32 *)miniflow_get__(match->flow, u64_ofs)
2073 + (mf->flow_be32ofs & 1);
2074 }
2075
2076 /* Insert rule in to the prefix tree.
2077 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2078 * in 'rule'. */
2079 static void
2080 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2081 {
2082 trie_insert_prefix(&trie->root,
2083 minimatch_get_prefix(&rule->match, &trie->field), mlen);
2084 }
2085
2086 static void
2087 trie_insert_prefix(rcu_trie_ptr *edge, const ovs_be32 *prefix, int mlen)
2088 {
2089 struct trie_node *node;
2090 int ofs = 0;
2091
2092 /* Walk the tree. */
2093 for (; (node = ovsrcu_get_protected(struct trie_node *, edge));
2094 edge = trie_next_edge(node, prefix, ofs)) {
2095 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2096 ofs += eqbits;
2097 if (eqbits < node->n_bits) {
2098 /* Mismatch, new node needs to be inserted above. */
2099 int old_branch = get_bit_at(node->prefix, eqbits);
2100 struct trie_node *new_parent;
2101
2102 new_parent = trie_branch_create(prefix, ofs - eqbits, eqbits,
2103 ofs == mlen ? 1 : 0);
2104 /* Copy the node to modify it. */
2105 node = trie_node_rcu_realloc(node);
2106 /* Adjust the new node for its new position in the tree. */
2107 node->prefix <<= eqbits;
2108 node->n_bits -= eqbits;
2109 ovsrcu_set_hidden(&new_parent->edges[old_branch], node);
2110
2111 /* Check if need a new branch for the new rule. */
2112 if (ofs < mlen) {
2113 ovsrcu_set_hidden(&new_parent->edges[!old_branch],
2114 trie_branch_create(prefix, ofs, mlen - ofs,
2115 1));
2116 }
2117 ovsrcu_set(edge, new_parent); /* Publish changes. */
2118 return;
2119 }
2120 /* Full match so far. */
2121
2122 if (ofs == mlen) {
2123 /* Full match at the current node, rule needs to be added here. */
2124 node->n_rules++;
2125 return;
2126 }
2127 }
2128 /* Must insert a new tree branch for the new rule. */
2129 ovsrcu_set(edge, trie_branch_create(prefix, ofs, mlen - ofs, 1));
2130 }
2131
2132 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2133 * in 'rule'. */
2134 static void
2135 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2136 {
2137 trie_remove_prefix(&trie->root,
2138 minimatch_get_prefix(&rule->match, &trie->field), mlen);
2139 }
2140
2141 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2142 * in 'rule'. */
2143 static void
2144 trie_remove_prefix(rcu_trie_ptr *root, const ovs_be32 *prefix, int mlen)
2145 {
2146 struct trie_node *node;
2147 rcu_trie_ptr *edges[sizeof(union trie_prefix) * CHAR_BIT];
2148 int depth = 0, ofs = 0;
2149
2150 /* Walk the tree. */
2151 for (edges[0] = root;
2152 (node = ovsrcu_get_protected(struct trie_node *, edges[depth]));
2153 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
2154 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2155
2156 if (eqbits < node->n_bits) {
2157 /* Mismatch, nothing to be removed. This should never happen, as
2158 * only rules in the classifier are ever removed. */
2159 break; /* Log a warning. */
2160 }
2161 /* Full match so far. */
2162 ofs += eqbits;
2163
2164 if (ofs == mlen) {
2165 /* Full prefix match at the current node, remove rule here. */
2166 if (!node->n_rules) {
2167 break; /* Log a warning. */
2168 }
2169 node->n_rules--;
2170
2171 /* Check if can prune the tree. */
2172 while (!node->n_rules) {
2173 struct trie_node *next,
2174 *edge0 = ovsrcu_get_protected(struct trie_node *,
2175 &node->edges[0]),
2176 *edge1 = ovsrcu_get_protected(struct trie_node *,
2177 &node->edges[1]);
2178
2179 if (edge0 && edge1) {
2180 break; /* A branching point, cannot prune. */
2181 }
2182
2183 /* Else have at most one child node, remove this node. */
2184 next = edge0 ? edge0 : edge1;
2185
2186 if (next) {
2187 if (node->n_bits + next->n_bits > TRIE_PREFIX_BITS) {
2188 break; /* Cannot combine. */
2189 }
2190 next = trie_node_rcu_realloc(next); /* Modify. */
2191
2192 /* Combine node with next. */
2193 next->prefix = node->prefix | next->prefix >> node->n_bits;
2194 next->n_bits += node->n_bits;
2195 }
2196 /* Update the parent's edge. */
2197 ovsrcu_set(edges[depth], next); /* Publish changes. */
2198 trie_node_destroy(node);
2199
2200 if (next || !depth) {
2201 /* Branch not pruned or at root, nothing more to do. */
2202 break;
2203 }
2204 node = ovsrcu_get_protected(struct trie_node *,
2205 edges[--depth]);
2206 }
2207 return;
2208 }
2209 }
2210 /* Cannot go deeper. This should never happen, since only rules
2211 * that actually exist in the classifier are ever removed. */
2212 }
2213 \f
2214
2215 #define CLS_MATCH_POISON (struct cls_match *)(UINTPTR_MAX / 0xf * 0xb)
2216
2217 void
2218 cls_match_free_cb(struct cls_match *rule)
2219 {
2220 ovsrcu_set_hidden(&rule->next, CLS_MATCH_POISON);
2221 free(rule);
2222 }