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