]> git.proxmox.com Git - ovs.git/blame - lib/classifier.c
datapath-windows: Remove all duplicate checks for NULL.
[ovs.git] / lib / classifier.c
CommitLineData
064af421 1/*
78c8df12 2 * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
064af421 3 *
a14bc59f
BP
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:
064af421 7 *
a14bc59f
BP
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.
064af421
BP
15 */
16
17#include <config.h>
18#include "classifier.h"
38c449e0 19#include "classifier-private.h"
064af421
BP
20#include <errno.h>
21#include <netinet/in.h>
844dff32 22#include "byte-order.h"
68d1c8c3 23#include "dynamic-string.h"
07b37e8f 24#include "odp-util.h"
d8ae4d67 25#include "ofp-util.h"
13751fd8 26#include "packets.h"
52054c15 27#include "util.h"
13751fd8
JR
28#include "vlog.h"
29
30VLOG_DEFINE_THIS_MODULE(classifier);
064af421 31
69d6040e
JR
32struct trie_ctx;
33
34/* Ports trie depends on both ports sharing the same ovs_be32. */
35#define TP_PORTS_OFS32 (offsetof(struct flow, tp_src) / 4)
36BUILD_ASSERT_DECL(TP_PORTS_OFS32 == offsetof(struct flow, tp_dst) / 4);
cabd4c43 37
627fb667
JR
38static struct cls_match *
39cls_match_alloc(struct cls_rule *rule)
40{
3016f3e4
JR
41 int count = count_1bits(rule->match.flow.map);
42
43 struct cls_match *cls_match
44 = xmalloc(sizeof *cls_match - sizeof cls_match->flow.inline_values
45 + MINIFLOW_VALUES_SIZE(count));
627fb667 46
f80028fe
JR
47 *CONST_CAST(const struct cls_rule **, &cls_match->cls_rule) = rule;
48 *CONST_CAST(int *, &cls_match->priority) = rule->priority;
49 miniflow_clone_inline(CONST_CAST(struct miniflow *, &cls_match->flow),
50 &rule->match.flow, count);
627fb667
JR
51 rule->cls_match = cls_match;
52
53 return cls_match;
54}
cabd4c43 55
e48eccd1 56static struct cls_subtable *find_subtable(const struct classifier *cls,
dfea28b3 57 const struct minimask *);
e48eccd1 58static struct cls_subtable *insert_subtable(struct classifier *cls,
e65413ab
JR
59 const struct minimask *)
60 OVS_REQUIRES(cls->mutex);
e48eccd1 61static void destroy_subtable(struct classifier *cls, struct cls_subtable *)
e65413ab 62 OVS_REQUIRES(cls->mutex);
b5d97350 63
dfea28b3
JR
64static const struct cls_match *find_match_wc(const struct cls_subtable *,
65 const struct flow *,
66 struct trie_ctx *,
67 unsigned int n_tries,
68 struct flow_wildcards *);
69static struct cls_match *find_equal(const struct cls_subtable *,
627fb667 70 const struct miniflow *, uint32_t hash);
b5d97350 71
dfea28b3
JR
72static inline const struct cls_match *
73next_rule_in_list__(const struct cls_match *rule)
74{
75 const struct cls_match *next = NULL;
76 next = OBJECT_CONTAINING(rculist_next(&rule->list), next, list);
77 return next;
78}
79
80static inline const struct cls_match *
81next_rule_in_list(const struct cls_match *rule)
82{
83 const struct cls_match *next = next_rule_in_list__(rule);
84 return next->priority < rule->priority ? next : NULL;
85}
86
c501b427 87static inline struct cls_match *
dfea28b3 88next_rule_in_list_protected__(struct cls_match *rule)
c501b427
JR
89{
90 struct cls_match *next = NULL;
dfea28b3 91 next = OBJECT_CONTAINING(rculist_next_protected(&rule->list), next, list);
c501b427
JR
92 return next;
93}
94
95static inline struct cls_match *
dfea28b3 96next_rule_in_list_protected(struct cls_match *rule)
c501b427 97{
dfea28b3 98 struct cls_match *next = next_rule_in_list_protected__(rule);
c501b427
JR
99 return next->priority < rule->priority ? next : NULL;
100}
101
e65413ab
JR
102/* Iterates RULE over HEAD and all of the cls_rules on HEAD->list.
103 * Classifier's mutex must be held while iterating, as the list is
104 * protoceted by it. */
b5d97350
BP
105#define FOR_EACH_RULE_IN_LIST(RULE, HEAD) \
106 for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
dfea28b3
JR
107#define FOR_EACH_RULE_IN_LIST_PROTECTED(RULE, HEAD) \
108 for ((RULE) = (HEAD); (RULE) != NULL; \
109 (RULE) = next_rule_in_list_protected(RULE))
13751fd8
JR
110
111static unsigned int minimask_get_prefix_len(const struct minimask *,
112 const struct mf_field *);
e48eccd1 113static void trie_init(struct classifier *cls, int trie_idx,
e65413ab
JR
114 const struct mf_field *)
115 OVS_REQUIRES(cls->mutex);
13751fd8 116static unsigned int trie_lookup(const struct cls_trie *, const struct flow *,
c0bfb650 117 union mf_value *plens);
f358a2cb 118static unsigned int trie_lookup_value(const rcu_trie_ptr *,
c0bfb650
JR
119 const ovs_be32 value[], ovs_be32 plens[],
120 unsigned int value_bits);
f358a2cb 121static void trie_destroy(rcu_trie_ptr *);
13751fd8 122static void trie_insert(struct cls_trie *, const struct cls_rule *, int mlen);
f358a2cb 123static void trie_insert_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
69d6040e 124 int mlen);
13751fd8 125static void trie_remove(struct cls_trie *, const struct cls_rule *, int mlen);
f358a2cb 126static void trie_remove_prefix(rcu_trie_ptr *, const ovs_be32 *prefix,
69d6040e 127 int mlen);
13751fd8 128static void mask_set_prefix_bits(struct flow_wildcards *, uint8_t be32ofs,
c30cfa6b 129 unsigned int n_bits);
13751fd8 130static bool mask_prefix_bits_set(const struct flow_wildcards *,
c30cfa6b 131 uint8_t be32ofs, unsigned int n_bits);
81a76618
BP
132\f
133/* cls_rule. */
b5d97350 134
81a76618 135/* Initializes 'rule' to match packets specified by 'match' at the given
5cb7a798
BP
136 * 'priority'. 'match' must satisfy the invariant described in the comment at
137 * the definition of struct match.
66642cb4 138 *
48d28ac1
BP
139 * The caller must eventually destroy 'rule' with cls_rule_destroy().
140 *
eb391b76
BP
141 * Clients should not use priority INT_MIN. (OpenFlow uses priorities between
142 * 0 and UINT16_MAX, inclusive.) */
47284b1f 143void
eb391b76 144cls_rule_init(struct cls_rule *rule, const struct match *match, int priority)
47284b1f 145{
5cb7a798
BP
146 minimatch_init(&rule->match, match);
147 rule->priority = priority;
627fb667 148 rule->cls_match = NULL;
5cb7a798
BP
149}
150
151/* Same as cls_rule_init() for initialization from a "struct minimatch". */
152void
153cls_rule_init_from_minimatch(struct cls_rule *rule,
eb391b76 154 const struct minimatch *match, int priority)
5cb7a798
BP
155{
156 minimatch_clone(&rule->match, match);
81a76618 157 rule->priority = priority;
627fb667 158 rule->cls_match = NULL;
685a51a5
JP
159}
160
48d28ac1
BP
161/* Initializes 'dst' as a copy of 'src'.
162 *
b2c1f00b 163 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
48d28ac1
BP
164void
165cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
166{
5cb7a798
BP
167 minimatch_clone(&dst->match, &src->match);
168 dst->priority = src->priority;
627fb667 169 dst->cls_match = NULL;
48d28ac1
BP
170}
171
b2c1f00b
BP
172/* Initializes 'dst' with the data in 'src', destroying 'src'.
173 *
174 * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
175void
176cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
177{
178 minimatch_move(&dst->match, &src->match);
179 dst->priority = src->priority;
627fb667 180 dst->cls_match = NULL;
b2c1f00b
BP
181}
182
48d28ac1
BP
183/* Frees memory referenced by 'rule'. Doesn't free 'rule' itself (it's
184 * normally embedded into a larger structure).
185 *
186 * ('rule' must not currently be in a classifier.) */
187void
5cb7a798 188cls_rule_destroy(struct cls_rule *rule)
48d28ac1 189{
627fb667 190 ovs_assert(!rule->cls_match);
5cb7a798 191 minimatch_destroy(&rule->match);
48d28ac1
BP
192}
193
81a76618
BP
194/* Returns true if 'a' and 'b' match the same packets at the same priority,
195 * false if they differ in some way. */
193eb874
BP
196bool
197cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
198{
5cb7a798 199 return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
193eb874
BP
200}
201
81a76618 202/* Returns a hash value for 'rule', folding in 'basis'. */
57452fdc
BP
203uint32_t
204cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
205{
5cb7a798 206 return minimatch_hash(&rule->match, hash_int(rule->priority, basis));
73f33563
BP
207}
208
81a76618 209/* Appends a string describing 'rule' to 's'. */
07b37e8f
BP
210void
211cls_rule_format(const struct cls_rule *rule, struct ds *s)
212{
5cb7a798 213 minimatch_format(&rule->match, s, rule->priority);
064af421 214}
3ca1de08
BP
215
216/* Returns true if 'rule' matches every packet, false otherwise. */
217bool
218cls_rule_is_catchall(const struct cls_rule *rule)
219{
5cb7a798 220 return minimask_is_catchall(&rule->match.mask);
3ca1de08 221}
064af421
BP
222\f
223/* Initializes 'cls' as a classifier that initially contains no classification
224 * rules. */
225void
e48eccd1
JR
226classifier_init(struct classifier *cls, const uint8_t *flow_segments)
227 OVS_EXCLUDED(cls->mutex)
064af421 228{
e65413ab 229 ovs_mutex_init(&cls->mutex);
e65413ab 230 ovs_mutex_lock(&cls->mutex);
064af421 231 cls->n_rules = 0;
f2c21402 232 cmap_init(&cls->subtables_map);
fe7cfa5c 233 pvector_init(&cls->subtables);
f2c21402 234 cmap_init(&cls->partitions);
476f36e8
JR
235 cls->n_flow_segments = 0;
236 if (flow_segments) {
237 while (cls->n_flow_segments < CLS_MAX_INDICES
238 && *flow_segments < FLOW_U32S) {
239 cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
240 }
241 }
13751fd8 242 cls->n_tries = 0;
e65413ab
JR
243 for (int i = 0; i < CLS_MAX_TRIES; i++) {
244 trie_init(cls, i, NULL);
245 }
246 ovs_mutex_unlock(&cls->mutex);
064af421
BP
247}
248
249/* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
afae68b1
JR
250 * caller's responsibility.
251 * May only be called after all the readers have been terminated. */
064af421 252void
e48eccd1
JR
253classifier_destroy(struct classifier *cls)
254 OVS_EXCLUDED(cls->mutex)
064af421 255{
e48eccd1 256 if (cls) {
78c8df12
BP
257 struct cls_partition *partition;
258 struct cls_subtable *subtable;
13751fd8
JR
259 int i;
260
e65413ab 261 ovs_mutex_lock(&cls->mutex);
13751fd8 262 for (i = 0; i < cls->n_tries; i++) {
f358a2cb 263 trie_destroy(&cls->tries[i].root);
13751fd8 264 }
064af421 265
6bc3bb82 266 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
03868246 267 destroy_subtable(cls, subtable);
064af421 268 }
f2c21402 269 cmap_destroy(&cls->subtables_map);
c906cedf 270
6bc3bb82 271 CMAP_FOR_EACH (partition, cmap_node, &cls->partitions) {
f2c21402 272 ovsrcu_postpone(free, partition);
c906cedf 273 }
f2c21402 274 cmap_destroy(&cls->partitions);
cabd4c43 275
fe7cfa5c 276 pvector_destroy(&cls->subtables);
e65413ab
JR
277 ovs_mutex_unlock(&cls->mutex);
278 ovs_mutex_destroy(&cls->mutex);
064af421
BP
279 }
280}
281
13751fd8 282/* Set the fields for which prefix lookup should be performed. */
f358a2cb 283bool
e48eccd1 284classifier_set_prefix_fields(struct classifier *cls,
13751fd8
JR
285 const enum mf_field_id *trie_fields,
286 unsigned int n_fields)
e48eccd1 287 OVS_EXCLUDED(cls->mutex)
13751fd8 288{
f358a2cb 289 const struct mf_field * new_fields[CLS_MAX_TRIES];
abadfcb0 290 struct mf_bitmap fields = MF_BITMAP_INITIALIZER;
f358a2cb
JR
291 int i, n_tries = 0;
292 bool changed = false;
13751fd8 293
e65413ab 294 ovs_mutex_lock(&cls->mutex);
f358a2cb 295 for (i = 0; i < n_fields && n_tries < CLS_MAX_TRIES; i++) {
13751fd8
JR
296 const struct mf_field *field = mf_from_id(trie_fields[i]);
297 if (field->flow_be32ofs < 0 || field->n_bits % 32) {
298 /* Incompatible field. This is the only place where we
299 * enforce these requirements, but the rest of the trie code
300 * depends on the flow_be32ofs to be non-negative and the
301 * field length to be a multiple of 32 bits. */
302 continue;
303 }
304
abadfcb0 305 if (bitmap_is_set(fields.bm, trie_fields[i])) {
13751fd8
JR
306 /* Duplicate field, there is no need to build more than
307 * one index for any one field. */
308 continue;
309 }
abadfcb0 310 bitmap_set1(fields.bm, trie_fields[i]);
13751fd8 311
f358a2cb
JR
312 new_fields[n_tries] = NULL;
313 if (n_tries >= cls->n_tries || field != cls->tries[n_tries].field) {
314 new_fields[n_tries] = field;
315 changed = true;
316 }
317 n_tries++;
318 }
319
320 if (changed || n_tries < cls->n_tries) {
321 struct cls_subtable *subtable;
322
323 /* Trie configuration needs to change. Disable trie lookups
324 * for the tries that are changing and wait all the current readers
325 * with the old configuration to be done. */
326 changed = false;
327 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
328 for (i = 0; i < cls->n_tries; i++) {
329 if ((i < n_tries && new_fields[i]) || i >= n_tries) {
330 if (subtable->trie_plen[i]) {
331 subtable->trie_plen[i] = 0;
332 changed = true;
333 }
334 }
335 }
336 }
337 /* Synchronize if any readers were using tries. The readers may
338 * temporarily function without the trie lookup based optimizations. */
339 if (changed) {
340 /* ovsrcu_synchronize() functions as a memory barrier, so it does
341 * not matter that subtable->trie_plen is not atomic. */
342 ovsrcu_synchronize();
13751fd8 343 }
13751fd8 344
f358a2cb
JR
345 /* Now set up the tries. */
346 for (i = 0; i < n_tries; i++) {
347 if (new_fields[i]) {
348 trie_init(cls, i, new_fields[i]);
349 }
350 }
351 /* Destroy the rest, if any. */
352 for (; i < cls->n_tries; i++) {
353 trie_init(cls, i, NULL);
354 }
355
356 cls->n_tries = n_tries;
357 ovs_mutex_unlock(&cls->mutex);
358 return true;
13751fd8 359 }
f358a2cb 360
e65413ab 361 ovs_mutex_unlock(&cls->mutex);
f358a2cb 362 return false; /* No change. */
13751fd8
JR
363}
364
365static void
e48eccd1 366trie_init(struct classifier *cls, int trie_idx, const struct mf_field *field)
e65413ab 367 OVS_REQUIRES(cls->mutex)
13751fd8
JR
368{
369 struct cls_trie *trie = &cls->tries[trie_idx];
370 struct cls_subtable *subtable;
371
372 if (trie_idx < cls->n_tries) {
f358a2cb
JR
373 trie_destroy(&trie->root);
374 } else {
375 ovsrcu_set_hidden(&trie->root, NULL);
13751fd8 376 }
13751fd8
JR
377 trie->field = field;
378
f358a2cb 379 /* Add existing rules to the new trie. */
f2c21402 380 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
13751fd8
JR
381 unsigned int plen;
382
383 plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
13751fd8 384 if (plen) {
627fb667 385 struct cls_match *head;
13751fd8 386
f2c21402 387 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
627fb667 388 struct cls_match *match;
13751fd8 389
dfea28b3 390 FOR_EACH_RULE_IN_LIST_PROTECTED (match, head) {
627fb667 391 trie_insert(trie, match->cls_rule, plen);
13751fd8
JR
392 }
393 }
394 }
f358a2cb
JR
395 /* Initialize subtable's prefix length on this field. This will
396 * allow readers to use the trie. */
397 atomic_thread_fence(memory_order_release);
398 subtable->trie_plen[trie_idx] = plen;
13751fd8
JR
399 }
400}
401
5f0476ce
JR
402/* Returns true if 'cls' contains no classification rules, false otherwise.
403 * Checking the cmap requires no locking. */
064af421
BP
404bool
405classifier_is_empty(const struct classifier *cls)
406{
e48eccd1 407 return cmap_is_empty(&cls->subtables_map);
064af421
BP
408}
409
dbda2960 410/* Returns the number of rules in 'cls'. */
064af421
BP
411int
412classifier_count(const struct classifier *cls)
afae68b1 413 OVS_NO_THREAD_SAFETY_ANALYSIS
064af421 414{
afae68b1
JR
415 /* n_rules is an int, so in the presence of concurrent writers this will
416 * return either the old or a new value. */
e48eccd1 417 return cls->n_rules;
064af421
BP
418}
419
c906cedf
BP
420static uint32_t
421hash_metadata(ovs_be64 metadata_)
422{
423 uint64_t metadata = (OVS_FORCE uint64_t) metadata_;
965607c8 424 return hash_uint64(metadata);
c906cedf
BP
425}
426
427static struct cls_partition *
e48eccd1 428find_partition(const struct classifier *cls, ovs_be64 metadata, uint32_t hash)
c906cedf
BP
429{
430 struct cls_partition *partition;
431
f2c21402 432 CMAP_FOR_EACH_WITH_HASH (partition, cmap_node, hash, &cls->partitions) {
c906cedf
BP
433 if (partition->metadata == metadata) {
434 return partition;
435 }
436 }
437
438 return NULL;
439}
440
441static struct cls_partition *
e48eccd1 442create_partition(struct classifier *cls, struct cls_subtable *subtable,
c906cedf 443 ovs_be64 metadata)
e65413ab 444 OVS_REQUIRES(cls->mutex)
c906cedf
BP
445{
446 uint32_t hash = hash_metadata(metadata);
447 struct cls_partition *partition = find_partition(cls, metadata, hash);
448 if (!partition) {
449 partition = xmalloc(sizeof *partition);
450 partition->metadata = metadata;
451 partition->tags = 0;
183126a1 452 tag_tracker_init(&partition->tracker);
f2c21402 453 cmap_insert(&cls->partitions, &partition->cmap_node, hash);
c906cedf 454 }
03868246 455 tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
c906cedf
BP
456 return partition;
457}
458
69d6040e
JR
459static inline ovs_be32 minimatch_get_ports(const struct minimatch *match)
460{
461 /* Could optimize to use the same map if needed for fast path. */
462 return MINIFLOW_GET_BE32(&match->flow, tp_src)
463 & MINIFLOW_GET_BE32(&match->mask.masks, tp_src);
464}
465
b5d97350
BP
466/* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
467 * must not modify or free it.
064af421
BP
468 *
469 * If 'cls' already contains an identical rule (including wildcards, values of
470 * fixed fields, and priority), replaces the old rule by 'rule' and returns the
471 * rule that was replaced. The caller takes ownership of the returned rule and
48d28ac1
BP
472 * is thus responsible for destroying it with cls_rule_destroy(), freeing the
473 * memory block in which it resides, etc., as necessary.
064af421
BP
474 *
475 * Returns NULL if 'cls' does not contain a rule with an identical key, after
476 * inserting the new rule. In this case, no rules are displaced by the new
477 * rule, even rules that cannot have any effect because the new rule matches a
886af6ea
JR
478 * superset of their flows and has higher priority.
479 */
dfea28b3 480const struct cls_rule *
e48eccd1
JR
481classifier_replace(struct classifier *cls, struct cls_rule *rule)
482 OVS_EXCLUDED(cls->mutex)
064af421 483{
886af6ea
JR
484 struct cls_match *new = cls_match_alloc(rule);
485 struct cls_match *old_rule = NULL;
03868246 486 struct cls_subtable *subtable;
dfea28b3 487 const struct cls_rule *old_cls_rule = NULL;
886af6ea
JR
488 uint32_t ihash[CLS_MAX_INDICES];
489 uint8_t prev_be32ofs = 0;
490 struct cls_match *head;
491 uint32_t basis;
492 uint32_t hash;
493 int i;
b5d97350 494
e65413ab 495 ovs_mutex_lock(&cls->mutex);
03868246
JR
496 subtable = find_subtable(cls, &rule->match.mask);
497 if (!subtable) {
498 subtable = insert_subtable(cls, &rule->match.mask);
b5d97350
BP
499 }
500
886af6ea
JR
501 /* Add new node to segment indices.
502 *
503 * Readers may find the rule in the indices before the rule is visible in
504 * the subtables 'rules' map. This may result in us losing the opportunity
505 * to quit lookups earlier, resulting in sub-optimal wildcarding. This
506 * will be fixed later by revalidation (always scheduled after flow table
507 * changes). */
508 basis = 0;
509 for (i = 0; i < subtable->n_indices; i++) {
510 ihash[i] = minimatch_hash_range(&rule->match, prev_be32ofs,
511 subtable->index_ofs[i], &basis);
512 cmap_insert(&subtable->indices[i], &new->index_nodes[i], ihash[i]);
513 prev_be32ofs = subtable->index_ofs[i];
514 }
515 hash = minimatch_hash_range(&rule->match, prev_be32ofs, FLOW_U32S, &basis);
516 head = find_equal(subtable, &rule->match.flow, hash);
517 if (!head) {
518 cmap_insert(&subtable->rules, &new->cmap_node, hash);
519 rculist_init(&new->list);
520 } else {
521 /* Scan the list for the insertion point that will keep the list in
522 * order of decreasing priority. */
523 struct cls_match *iter;
524
525 FOR_EACH_RULE_IN_LIST_PROTECTED (iter, head) {
526 if (new->priority >= iter->priority) {
527 if (iter == head) {
528 /* 'new' is the new highest-priority flow in the list. */
529 cmap_replace(&subtable->rules, &iter->cmap_node,
530 &new->cmap_node, hash);
531 }
532
533 if (new->priority == iter->priority) {
534 rculist_replace(&new->list, &iter->list);
535 old_rule = iter;
536 } else {
537 rculist_insert(&iter->list, &new->list);
538 }
539 goto out;
540 }
541 }
542
543 /* Insert 'new' at the end of the list. */
544 rculist_push_back(&head->list, &new->list);
545 out:;
546 }
547
b5d97350 548 if (!old_rule) {
e65413ab 549 old_cls_rule = NULL;
886af6ea 550 subtable->n_rules++;
13751fd8 551
886af6ea
JR
552 /* Rule was added, not replaced. Update 'subtable's 'max_priority'
553 * and 'max_count', if necessary.
554 *
555 * The rule was already inserted, but concurrent readers may not see
556 * the rule yet as the subtables vector is not updated yet.
557 * This will have to be fixed by revalidation later. */
558 if (subtable->n_rules == 1) {
559 subtable->max_priority = new->priority;
560 subtable->max_count = 1;
561 pvector_insert(&cls->subtables, subtable, new->priority);
562 } else if (subtable->max_priority == new->priority) {
563 ++subtable->max_count;
564 } else if (new->priority > subtable->max_priority) {
565 subtable->max_priority = new->priority;
566 subtable->max_count = 1;
567 pvector_change_priority(&cls->subtables, subtable, new->priority);
568 }
569
570 /* Add rule to partitions.
571 *
572 * Concurrent readers might miss seeing the rule until this update,
573 * which might require being fixed up by revalidation later. */
627fb667 574 rule->cls_match->partition = NULL;
c906cedf
BP
575 if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
576 ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
627fb667
JR
577 rule->cls_match->partition = create_partition(cls, subtable,
578 metadata);
c906cedf
BP
579 }
580
064af421 581 cls->n_rules++;
13751fd8 582
886af6ea
JR
583 /* Add rule to tries.
584 *
585 * Concurrent readers might miss seeing the rule until this update,
586 * which might require being fixed up by revalidation later. */
e65413ab 587 for (int i = 0; i < cls->n_tries; i++) {
13751fd8
JR
588 if (subtable->trie_plen[i]) {
589 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
590 }
591 }
69d6040e 592
886af6ea 593 /* Add rule to ports trie. */
69d6040e
JR
594 if (subtable->ports_mask_len) {
595 /* We mask the value to be inserted to always have the wildcarded
596 * bits in known (zero) state, so we can include them in comparison
597 * and they will always match (== their original value does not
598 * matter). */
599 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
600
601 trie_insert_prefix(&subtable->ports_trie, &masked_ports,
602 subtable->ports_mask_len);
603 }
c906cedf 604 } else {
e65413ab 605 old_cls_rule = old_rule->cls_rule;
886af6ea
JR
606
607 /* Remove old node from indices.
608 *
609 * The effect of this late removal of a duplicate rule on concurrent
610 * readers is similar to that of adding the new rule to the segment
611 * indices early (at the beginning of this function.) */
612 for (i = 0; i < subtable->n_indices; i++) {
613 cmap_remove(&subtable->indices[i], &old_rule->index_nodes[i],
614 ihash[i]);
615 }
616
627fb667 617 rule->cls_match->partition = old_rule->partition;
dfea28b3 618 CONST_CAST(struct cls_rule *, old_cls_rule)->cls_match = NULL;
f2c21402
JR
619
620 /* 'old_rule' contains a cmap_node, which may not be freed
621 * immediately. */
622 ovsrcu_postpone(free, old_rule);
064af421 623 }
886af6ea 624
e65413ab
JR
625 ovs_mutex_unlock(&cls->mutex);
626 return old_cls_rule;
064af421
BP
627}
628
08944c1d
BP
629/* Inserts 'rule' into 'cls'. Until 'rule' is removed from 'cls', the caller
630 * must not modify or free it.
631 *
632 * 'cls' must not contain an identical rule (including wildcards, values of
633 * fixed fields, and priority). Use classifier_find_rule_exactly() to find
634 * such a rule. */
635void
636classifier_insert(struct classifier *cls, struct cls_rule *rule)
637{
dfea28b3 638 const struct cls_rule *displaced_rule = classifier_replace(cls, rule);
cb22974d 639 ovs_assert(!displaced_rule);
08944c1d
BP
640}
641
48d28ac1
BP
642/* Removes 'rule' from 'cls'. It is the caller's responsibility to destroy
643 * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
747f140a
JR
644 * resides, etc., as necessary.
645 *
646 * Does nothing if 'rule' has been already removed, or was never inserted.
647 *
648 * Returns the removed rule, or NULL, if it was already removed.
649 */
dfea28b3
JR
650const struct cls_rule *
651classifier_remove(struct classifier *cls, const struct cls_rule *rule)
e48eccd1 652 OVS_EXCLUDED(cls->mutex)
064af421 653{
c906cedf 654 struct cls_partition *partition;
747f140a 655 struct cls_match *cls_match;
627fb667 656 struct cls_match *head;
03868246 657 struct cls_subtable *subtable;
476f36e8 658 int i;
f2c21402
JR
659 uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
660 uint8_t prev_be32ofs = 0;
064af421 661
e65413ab 662 ovs_mutex_lock(&cls->mutex);
747f140a
JR
663 cls_match = rule->cls_match;
664 if (!cls_match) {
665 rule = NULL;
666 goto unlock; /* Already removed. */
667 }
668
03868246 669 subtable = find_subtable(cls, &rule->match.mask);
627fb667
JR
670 ovs_assert(subtable);
671
69d6040e
JR
672 if (subtable->ports_mask_len) {
673 ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
674
675 trie_remove_prefix(&subtable->ports_trie,
676 &masked_ports, subtable->ports_mask_len);
677 }
13751fd8
JR
678 for (i = 0; i < cls->n_tries; i++) {
679 if (subtable->trie_plen[i]) {
680 trie_remove(&cls->tries[i], rule, subtable->trie_plen[i]);
681 }
682 }
683
476f36e8
JR
684 /* Remove rule node from indices. */
685 for (i = 0; i < subtable->n_indices; i++) {
f2c21402
JR
686 ihash[i] = minimatch_hash_range(&rule->match, prev_be32ofs,
687 subtable->index_ofs[i], &basis);
688 cmap_remove(&subtable->indices[i], &cls_match->index_nodes[i],
689 ihash[i]);
690 prev_be32ofs = subtable->index_ofs[i];
476f36e8 691 }
f2c21402 692 hash = minimatch_hash_range(&rule->match, prev_be32ofs, FLOW_U32S, &basis);
476f36e8 693
f2c21402 694 head = find_equal(subtable, &rule->match.flow, hash);
627fb667 695 if (head != cls_match) {
c501b427
JR
696 rculist_remove(&cls_match->list);
697 } else if (rculist_is_empty(&cls_match->list)) {
f2c21402 698 cmap_remove(&subtable->rules, &cls_match->cmap_node, hash);
b5d97350 699 } else {
dfea28b3 700 struct cls_match *next = next_rule_in_list_protected(cls_match);
064af421 701
c501b427 702 rculist_remove(&cls_match->list);
f2c21402
JR
703 cmap_replace(&subtable->rules, &cls_match->cmap_node,
704 &next->cmap_node, hash);
b5d97350 705 }
064af421 706
627fb667 707 partition = cls_match->partition;
183126a1
BP
708 if (partition) {
709 tag_tracker_subtract(&partition->tracker, &partition->tags,
03868246 710 subtable->tag);
183126a1 711 if (!partition->tags) {
f2c21402
JR
712 cmap_remove(&cls->partitions, &partition->cmap_node,
713 hash_metadata(partition->metadata));
714 ovsrcu_postpone(free, partition);
183126a1 715 }
c906cedf
BP
716 }
717
03868246
JR
718 if (--subtable->n_rules == 0) {
719 destroy_subtable(cls, subtable);
fe7cfa5c
JR
720 } else if (subtable->max_priority == cls_match->priority
721 && --subtable->max_count == 0) {
722 /* Find the new 'max_priority' and 'max_count'. */
723 struct cls_match *head;
eb391b76 724 int max_priority = INT_MIN;
fe7cfa5c 725
f2c21402 726 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
fe7cfa5c
JR
727 if (head->priority > max_priority) {
728 max_priority = head->priority;
729 subtable->max_count = 1;
730 } else if (head->priority == max_priority) {
731 ++subtable->max_count;
732 }
733 }
734 subtable->max_priority = max_priority;
735 pvector_change_priority(&cls->subtables, subtable, max_priority);
4d935a6b 736 }
13751fd8 737
b5d97350 738 cls->n_rules--;
627fb667 739
f2c21402 740 ovsrcu_postpone(free, cls_match);
dfea28b3 741 CONST_CAST(struct cls_rule *, rule)->cls_match = NULL;
747f140a 742unlock:
e65413ab 743 ovs_mutex_unlock(&cls->mutex);
747f140a
JR
744
745 return rule;
064af421
BP
746}
747
13751fd8 748/* Prefix tree context. Valid when 'lookup_done' is true. Can skip all
c0bfb650
JR
749 * subtables which have a prefix match on the trie field, but whose prefix
750 * length is not indicated in 'match_plens'. For example, a subtable that
751 * has a 8-bit trie field prefix match can be skipped if
752 * !be_get_bit_at(&match_plens, 8 - 1). If skipped, 'maskbits' prefix bits
753 * must be unwildcarded to make datapath flow only match packets it should. */
13751fd8
JR
754struct trie_ctx {
755 const struct cls_trie *trie;
756 bool lookup_done; /* Status of the lookup. */
757 uint8_t be32ofs; /* U32 offset of the field in question. */
13751fd8 758 unsigned int maskbits; /* Prefix length needed to avoid false matches. */
c0bfb650
JR
759 union mf_value match_plens; /* Bitmask of prefix lengths with possible
760 * matches. */
13751fd8
JR
761};
762
763static void
764trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
765{
766 ctx->trie = trie;
767 ctx->be32ofs = trie->field->flow_be32ofs;
768 ctx->lookup_done = false;
769}
770
48c3de13
BP
771/* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
772 * Returns a null pointer if no rules in 'cls' match 'flow'. If multiple rules
74f74083
EJ
773 * of equal priority match 'flow', returns one arbitrarily.
774 *
775 * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
776 * set of bits that were significant in the lookup. At some point
777 * earlier, 'wc' should have been initialized (e.g., by
778 * flow_wildcards_init_catchall()). */
dfea28b3 779const struct cls_rule *
e48eccd1 780classifier_lookup(const struct classifier *cls, const struct flow *flow,
74f74083 781 struct flow_wildcards *wc)
48c3de13 782{
c906cedf 783 const struct cls_partition *partition;
c906cedf 784 tag_type tags;
eb391b76 785 int best_priority = INT_MIN;
fe7cfa5c
JR
786 const struct cls_match *best;
787 struct trie_ctx trie_ctx[CLS_MAX_TRIES];
788 struct cls_subtable *subtable;
c906cedf 789
f358a2cb
JR
790 /* Synchronize for cls->n_tries and subtable->trie_plen. They can change
791 * when table configuration changes, which happens typically only on
792 * startup. */
793 atomic_thread_fence(memory_order_acquire);
794
03868246
JR
795 /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
796 * then 'flow' cannot possibly match in 'subtable':
c906cedf
BP
797 *
798 * - If flow->metadata maps to a given 'partition', then we can use
799 * 'tags' for 'partition->tags'.
800 *
801 * - If flow->metadata has no partition, then no rule in 'cls' has an
802 * exact-match for flow->metadata. That means that we don't need to
03868246 803 * search any subtable that includes flow->metadata in its mask.
c906cedf 804 *
03868246 805 * In either case, we always need to search any cls_subtables that do not
c906cedf 806 * include flow->metadata in its mask. One way to do that would be to
03868246
JR
807 * check the "cls_subtable"s explicitly for that, but that would require an
808 * extra branch per subtable. Instead, we mark such a cls_subtable's
809 * 'tags' as TAG_ALL and make sure that 'tags' is never empty. This means
810 * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
811 * need a special case.
c906cedf 812 */
f2c21402 813 partition = (cmap_is_empty(&cls->partitions)
c906cedf
BP
814 ? NULL
815 : find_partition(cls, flow->metadata,
816 hash_metadata(flow->metadata)));
817 tags = partition ? partition->tags : TAG_ARBITRARY;
48c3de13 818
ff8241db 819 /* Initialize trie contexts for find_match_wc(). */
fe7cfa5c 820 for (int i = 0; i < cls->n_tries; i++) {
13751fd8
JR
821 trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
822 }
ec988646 823
b5d97350 824 best = NULL;
fe7cfa5c
JR
825 PVECTOR_FOR_EACH_PRIORITY(subtable, best_priority, 2,
826 sizeof(struct cls_subtable), &cls->subtables) {
dfea28b3 827 const struct cls_match *rule;
c906cedf 828
fe7cfa5c 829 if (!tag_intersects(tags, subtable->tag)) {
c906cedf
BP
830 continue;
831 }
74f74083 832
fe7cfa5c 833 rule = find_match_wc(subtable, flow, trie_ctx, cls->n_tries, wc);
eb391b76
BP
834 if (rule && rule->priority > best_priority) {
835 best_priority = rule->priority;
1f3c5efc 836 best = rule;
b5d97350 837 }
48c3de13 838 }
13751fd8 839
627fb667 840 return best ? best->cls_rule : NULL;
48c3de13
BP
841}
842
b5d97350
BP
843/* Finds and returns a rule in 'cls' with exactly the same priority and
844 * matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
c084ce1d 845 * contain an exact match. */
dfea28b3 846const struct cls_rule *
e48eccd1 847classifier_find_rule_exactly(const struct classifier *cls,
76ecc721 848 const struct cls_rule *target)
064af421 849{
dfea28b3
JR
850 const struct cls_match *head, *rule;
851 const struct cls_subtable *subtable;
064af421 852
03868246 853 subtable = find_subtable(cls, &target->match.mask);
0722ee5c 854 if (!subtable) {
98abae4a 855 return NULL;
4d935a6b
JR
856 }
857
03868246 858 head = find_equal(subtable, &target->match.flow,
5cb7a798
BP
859 miniflow_hash_in_minimask(&target->match.flow,
860 &target->match.mask, 0));
98abae4a
JR
861 if (!head) {
862 return NULL;
863 }
b5d97350
BP
864 FOR_EACH_RULE_IN_LIST (rule, head) {
865 if (target->priority >= rule->priority) {
627fb667 866 return target->priority == rule->priority ? rule->cls_rule : NULL;
064af421
BP
867 }
868 }
869 return NULL;
870}
871
81a76618
BP
872/* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
873 * same matching criteria as 'target'. Returns a null pointer if 'cls' doesn't
874 * contain an exact match. */
dfea28b3 875const struct cls_rule *
81a76618 876classifier_find_match_exactly(const struct classifier *cls,
eb391b76 877 const struct match *target, int priority)
81a76618 878{
dfea28b3 879 const struct cls_rule *retval;
81a76618
BP
880 struct cls_rule cr;
881
882 cls_rule_init(&cr, target, priority);
883 retval = classifier_find_rule_exactly(cls, &cr);
48d28ac1 884 cls_rule_destroy(&cr);
81a76618
BP
885
886 return retval;
887}
888
faa50f40
BP
889/* Checks if 'target' would overlap any other rule in 'cls'. Two rules are
890 * considered to overlap if both rules have the same priority and a packet
891 * could match both. */
49bdc010 892bool
e48eccd1 893classifier_rule_overlaps(const struct classifier *cls,
faa50f40 894 const struct cls_rule *target)
e48eccd1 895 OVS_EXCLUDED(cls->mutex)
49bdc010 896{
03868246 897 struct cls_subtable *subtable;
49bdc010 898
e65413ab 899 ovs_mutex_lock(&cls->mutex);
03868246 900 /* Iterate subtables in the descending max priority order. */
eb391b76 901 PVECTOR_FOR_EACH_PRIORITY (subtable, target->priority - 1, 2,
fe7cfa5c 902 sizeof(struct cls_subtable), &cls->subtables) {
5cb7a798
BP
903 uint32_t storage[FLOW_U32S];
904 struct minimask mask;
627fb667 905 struct cls_match *head;
49bdc010 906
03868246 907 minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
f2c21402 908 CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
627fb667 909 struct cls_match *rule;
49bdc010 910
dfea28b3 911 FOR_EACH_RULE_IN_LIST_PROTECTED (rule, head) {
4d935a6b
JR
912 if (rule->priority < target->priority) {
913 break; /* Rules in descending priority order. */
914 }
faa50f40 915 if (rule->priority == target->priority
5cb7a798 916 && miniflow_equal_in_minimask(&target->match.flow,
3016f3e4 917 &rule->flow, &mask)) {
e65413ab 918 ovs_mutex_unlock(&cls->mutex);
49bdc010
JP
919 return true;
920 }
921 }
922 }
923 }
924
e65413ab 925 ovs_mutex_unlock(&cls->mutex);
49bdc010
JP
926 return false;
927}
6ceeaa92
BP
928
929/* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
930 * specific than 'criteria'. That is, 'rule' matches 'criteria' and this
931 * function returns true if, for every field:
932 *
933 * - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
934 * field, or
935 *
936 * - 'criteria' wildcards the field,
937 *
938 * Conversely, 'rule' does not match 'criteria' and this function returns false
939 * if, for at least one field:
940 *
941 * - 'criteria' and 'rule' specify different values for the field, or
942 *
943 * - 'criteria' specifies a value for the field but 'rule' wildcards it.
944 *
945 * Equivalently, the truth table for whether a field matches is:
946 *
947 * rule
948 *
949 * c wildcard exact
950 * r +---------+---------+
951 * i wild | yes | yes |
952 * t card | | |
953 * e +---------+---------+
954 * r exact | no |if values|
955 * i | |are equal|
956 * a +---------+---------+
957 *
958 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
959 * commands and by OpenFlow 1.0 aggregate and flow stats.
960 *
81a76618 961 * Ignores rule->priority. */
6ceeaa92
BP
962bool
963cls_rule_is_loose_match(const struct cls_rule *rule,
5cb7a798 964 const struct minimatch *criteria)
6ceeaa92 965{
5cb7a798
BP
966 return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
967 && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
968 &criteria->mask));
6ceeaa92 969}
b5d97350 970\f
5ecc9d81
BP
971/* Iteration. */
972
973static bool
627fb667 974rule_matches(const struct cls_match *rule, const struct cls_rule *target)
5ecc9d81
BP
975{
976 return (!target
3016f3e4 977 || miniflow_equal_in_minimask(&rule->flow,
5cb7a798
BP
978 &target->match.flow,
979 &target->match.mask));
5ecc9d81
BP
980}
981
dfea28b3 982static const struct cls_match *
03868246 983search_subtable(const struct cls_subtable *subtable,
f2c21402 984 struct cls_cursor *cursor)
5ecc9d81 985{
f2c21402
JR
986 if (!cursor->target
987 || !minimask_has_extra(&subtable->mask, &cursor->target->match.mask)) {
dfea28b3 988 const struct cls_match *rule;
5ecc9d81 989
f2c21402
JR
990 CMAP_CURSOR_FOR_EACH (rule, cmap_node, &cursor->rules,
991 &subtable->rules) {
992 if (rule_matches(rule, cursor->target)) {
5ecc9d81
BP
993 return rule;
994 }
995 }
996 }
997 return NULL;
998}
999
5f0476ce
JR
1000/* Initializes 'cursor' for iterating through rules in 'cls', and returns the
1001 * first matching cls_rule via '*pnode', or NULL if there are no matches.
5ecc9d81 1002 *
6ceeaa92 1003 * - If 'target' is null, the cursor will visit every rule in 'cls'.
5ecc9d81 1004 *
6ceeaa92
BP
1005 * - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1006 * such that cls_rule_is_loose_match(rule, target) returns true.
5ecc9d81 1007 *
6ceeaa92 1008 * Ignores target->priority. */
78c8df12
BP
1009struct cls_cursor cls_cursor_start(const struct classifier *cls,
1010 const struct cls_rule *target,
1011 bool safe)
5f0476ce 1012 OVS_NO_THREAD_SAFETY_ANALYSIS
5ecc9d81 1013{
5f0476ce 1014 struct cls_cursor cursor;
03868246 1015 struct cls_subtable *subtable;
5ecc9d81 1016
5f0476ce 1017 cursor.safe = safe;
e48eccd1 1018 cursor.cls = cls;
5f0476ce 1019 cursor.target = target && !cls_rule_is_catchall(target) ? target : NULL;
78c8df12 1020 cursor.rule = NULL;
5f0476ce
JR
1021
1022 /* Find first rule. */
e65413ab 1023 ovs_mutex_lock(&cursor.cls->mutex);
5f0476ce 1024 CMAP_CURSOR_FOR_EACH (subtable, cmap_node, &cursor.subtables,
e65413ab 1025 &cursor.cls->subtables_map) {
dfea28b3 1026 const struct cls_match *rule = search_subtable(subtable, &cursor);
f2c21402 1027
5ecc9d81 1028 if (rule) {
5f0476ce 1029 cursor.subtable = subtable;
78c8df12 1030 cursor.rule = rule->cls_rule;
5f0476ce 1031 break;
5ecc9d81
BP
1032 }
1033 }
1034
5f0476ce 1035 /* Leave locked if requested and have a rule. */
78c8df12 1036 if (safe || !cursor.rule) {
e65413ab 1037 ovs_mutex_unlock(&cursor.cls->mutex);
5f0476ce
JR
1038 }
1039 return cursor;
1040}
1041
dfea28b3 1042static const struct cls_rule *
1caa1561 1043cls_cursor_next(struct cls_cursor *cursor)
5f0476ce 1044 OVS_NO_THREAD_SAFETY_ANALYSIS
5ecc9d81 1045{
dfea28b3 1046 const struct cls_match *rule = cursor->rule->cls_match;
03868246 1047 const struct cls_subtable *subtable;
dfea28b3 1048 const struct cls_match *next;
5ecc9d81 1049
955f579d
BP
1050 next = next_rule_in_list__(rule);
1051 if (next->priority < rule->priority) {
1caa1561 1052 return next->cls_rule;
5ecc9d81
BP
1053 }
1054
955f579d 1055 /* 'next' is the head of the list, that is, the rule that is included in
f2c21402 1056 * the subtable's map. (This is important when the classifier contains
03868246 1057 * rules that differ only in priority.) */
955f579d 1058 rule = next;
f2c21402 1059 CMAP_CURSOR_FOR_EACH_CONTINUE (rule, cmap_node, &cursor->rules) {
5ecc9d81 1060 if (rule_matches(rule, cursor->target)) {
1caa1561 1061 return rule->cls_rule;
5ecc9d81
BP
1062 }
1063 }
1064
03868246 1065 subtable = cursor->subtable;
f2c21402
JR
1066 CMAP_CURSOR_FOR_EACH_CONTINUE (subtable, cmap_node, &cursor->subtables) {
1067 rule = search_subtable(subtable, cursor);
5ecc9d81 1068 if (rule) {
03868246 1069 cursor->subtable = subtable;
1caa1561 1070 return rule->cls_rule;
5ecc9d81
BP
1071 }
1072 }
1073
1caa1561
BP
1074 return NULL;
1075}
1076
1077/* Sets 'cursor->rule' to the next matching cls_rule in 'cursor''s iteration,
1078 * or to null if all matching rules have been visited. */
1079void
1080cls_cursor_advance(struct cls_cursor *cursor)
1081 OVS_NO_THREAD_SAFETY_ANALYSIS
1082{
1083 if (cursor->safe) {
1084 ovs_mutex_lock(&cursor->cls->mutex);
1085 }
1086 cursor->rule = cls_cursor_next(cursor);
1087 if (cursor->safe || !cursor->rule) {
1088 ovs_mutex_unlock(&cursor->cls->mutex);
1089 }
5ecc9d81
BP
1090}
1091\f
03868246 1092static struct cls_subtable *
e48eccd1 1093find_subtable(const struct classifier *cls, const struct minimask *mask)
b5d97350 1094{
03868246 1095 struct cls_subtable *subtable;
064af421 1096
f2c21402 1097 CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, minimask_hash(mask, 0),
5a87054c 1098 &cls->subtables_map) {
03868246
JR
1099 if (minimask_equal(mask, &subtable->mask)) {
1100 return subtable;
064af421
BP
1101 }
1102 }
b5d97350 1103 return NULL;
064af421 1104}
064af421 1105
e65413ab 1106/* The new subtable will be visible to the readers only after this. */
03868246 1107static struct cls_subtable *
e48eccd1 1108insert_subtable(struct classifier *cls, const struct minimask *mask)
e65413ab 1109 OVS_REQUIRES(cls->mutex)
b5d97350 1110{
c906cedf 1111 uint32_t hash = minimask_hash(mask, 0);
03868246 1112 struct cls_subtable *subtable;
476f36e8
JR
1113 int i, index = 0;
1114 struct flow_wildcards old, new;
1115 uint8_t prev;
3016f3e4 1116 int count = count_1bits(mask->masks.map);
064af421 1117
3016f3e4
JR
1118 subtable = xzalloc(sizeof *subtable - sizeof mask->masks.inline_values
1119 + MINIFLOW_VALUES_SIZE(count));
f2c21402 1120 cmap_init(&subtable->rules);
f80028fe
JR
1121 miniflow_clone_inline(CONST_CAST(struct miniflow *, &subtable->mask.masks),
1122 &mask->masks, count);
476f36e8
JR
1123
1124 /* Init indices for segmented lookup, if any. */
1125 flow_wildcards_init_catchall(&new);
1126 old = new;
1127 prev = 0;
1128 for (i = 0; i < cls->n_flow_segments; i++) {
1129 flow_wildcards_fold_minimask_range(&new, mask, prev,
1130 cls->flow_segments[i]);
1131 /* Add an index if it adds mask bits. */
1132 if (!flow_wildcards_equal(&new, &old)) {
f2c21402 1133 cmap_init(&subtable->indices[index]);
f80028fe
JR
1134 *CONST_CAST(uint8_t *, &subtable->index_ofs[index])
1135 = cls->flow_segments[i];
476f36e8
JR
1136 index++;
1137 old = new;
1138 }
1139 prev = cls->flow_segments[i];
1140 }
1141 /* Check if the rest of the subtable's mask adds any bits,
1142 * and remove the last index if it doesn't. */
1143 if (index > 0) {
1144 flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U32S);
1145 if (flow_wildcards_equal(&new, &old)) {
1146 --index;
f80028fe 1147 *CONST_CAST(uint8_t *, &subtable->index_ofs[index]) = 0;
f2c21402 1148 cmap_destroy(&subtable->indices[index]);
476f36e8
JR
1149 }
1150 }
f80028fe 1151 *CONST_CAST(uint8_t *, &subtable->n_indices) = index;
476f36e8 1152
f80028fe
JR
1153 *CONST_CAST(tag_type *, &subtable->tag) =
1154 (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1155 ? tag_create_deterministic(hash)
1156 : TAG_ALL);
064af421 1157
13751fd8
JR
1158 for (i = 0; i < cls->n_tries; i++) {
1159 subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1160 cls->tries[i].field);
1161 }
1162
69d6040e 1163 /* Ports trie. */
f358a2cb 1164 ovsrcu_set_hidden(&subtable->ports_trie, NULL);
f80028fe 1165 *CONST_CAST(int *, &subtable->ports_mask_len)
69d6040e
JR
1166 = 32 - ctz32(ntohl(MINIFLOW_GET_BE32(&mask->masks, tp_src)));
1167
f2c21402 1168 cmap_insert(&cls->subtables_map, &subtable->cmap_node, hash);
ec988646 1169
03868246 1170 return subtable;
064af421
BP
1171}
1172
01c0f83a 1173/* RCU readers may still access the subtable before it is actually freed. */
b5d97350 1174static void
e48eccd1 1175destroy_subtable(struct classifier *cls, struct cls_subtable *subtable)
e65413ab 1176 OVS_REQUIRES(cls->mutex)
b5d97350 1177{
476f36e8
JR
1178 int i;
1179
fe7cfa5c 1180 pvector_remove(&cls->subtables, subtable);
01c0f83a
JR
1181 cmap_remove(&cls->subtables_map, &subtable->cmap_node,
1182 minimask_hash(&subtable->mask, 0));
1183
1184 ovs_assert(ovsrcu_get_protected(struct trie_node *, &subtable->ports_trie)
1185 == NULL);
1186 ovs_assert(cmap_is_empty(&subtable->rules));
69d6040e 1187
476f36e8 1188 for (i = 0; i < subtable->n_indices; i++) {
f2c21402 1189 cmap_destroy(&subtable->indices[i]);
476f36e8 1190 }
f2c21402 1191 cmap_destroy(&subtable->rules);
fe7cfa5c 1192 ovsrcu_postpone(free, subtable);
4aacd02d
BP
1193}
1194
13751fd8
JR
1195struct range {
1196 uint8_t start;
1197 uint8_t end;
1198};
1199
c0bfb650
JR
1200static unsigned int be_get_bit_at(const ovs_be32 value[], unsigned int ofs);
1201
13751fd8
JR
1202/* Return 'true' if can skip rest of the subtable based on the prefix trie
1203 * lookup results. */
1204static inline bool
1205check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1206 const unsigned int field_plen[CLS_MAX_TRIES],
1207 const struct range ofs, const struct flow *flow,
1208 struct flow_wildcards *wc)
1209{
1210 int j;
1211
1212 /* Check if we could avoid fully unwildcarding the next level of
1213 * fields using the prefix tries. The trie checks are done only as
1214 * needed to avoid folding in additional bits to the wildcards mask. */
1215 for (j = 0; j < n_tries; j++) {
1216 /* Is the trie field relevant for this subtable? */
1217 if (field_plen[j]) {
1218 struct trie_ctx *ctx = &trie_ctx[j];
1219 uint8_t be32ofs = ctx->be32ofs;
1220
1221 /* Is the trie field within the current range of fields? */
1222 if (be32ofs >= ofs.start && be32ofs < ofs.end) {
1223 /* On-demand trie lookup. */
1224 if (!ctx->lookup_done) {
c0bfb650
JR
1225 memset(&ctx->match_plens, 0, sizeof ctx->match_plens);
1226 ctx->maskbits = trie_lookup(ctx->trie, flow,
1227 &ctx->match_plens);
13751fd8
JR
1228 ctx->lookup_done = true;
1229 }
1230 /* Possible to skip the rest of the subtable if subtable's
c0bfb650
JR
1231 * prefix on the field is not included in the lookup result. */
1232 if (!be_get_bit_at(&ctx->match_plens.be32, field_plen[j] - 1)) {
1817dcea
JR
1233 /* We want the trie lookup to never result in unwildcarding
1234 * any bits that would not be unwildcarded otherwise.
1235 * Since the trie is shared by the whole classifier, it is
1236 * possible that the 'maskbits' contain bits that are
1237 * irrelevant for the partition relevant for the current
1238 * packet. Hence the checks below. */
13751fd8 1239
13751fd8 1240 /* Check that the trie result will not unwildcard more bits
1817dcea 1241 * than this subtable would otherwise. */
13751fd8
JR
1242 if (ctx->maskbits <= field_plen[j]) {
1243 /* Unwildcard the bits and skip the rest. */
1244 mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1245 /* Note: Prerequisite already unwildcarded, as the only
1246 * prerequisite of the supported trie lookup fields is
1817dcea
JR
1247 * the ethertype, which is always unwildcarded. */
1248 return true;
1249 }
1250 /* Can skip if the field is already unwildcarded. */
1251 if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
13751fd8
JR
1252 return true;
1253 }
1254 }
1255 }
1256 }
1257 }
1258 return false;
1259}
1260
3016f3e4
JR
1261/* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1262 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1263 * value has the correct value in 'target'.
1264 *
1265 * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
a64759f0
JR
1266 * target, mask) but this is faster because of the invariant that
1267 * flow->map and mask->masks.map are the same, and that this version
1268 * takes the 'wc'. */
3016f3e4
JR
1269static inline bool
1270miniflow_and_mask_matches_flow(const struct miniflow *flow,
1271 const struct minimask *mask,
e9319757 1272 const struct flow *target)
3016f3e4
JR
1273{
1274 const uint32_t *flowp = miniflow_get_u32_values(flow);
1275 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
a64759f0 1276 uint32_t idx;
3016f3e4 1277
a64759f0
JR
1278 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1279 uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & *maskp++;
1280
1281 if (diff) {
3016f3e4
JR
1282 return false;
1283 }
1284 }
1285
1286 return true;
1287}
1288
dfea28b3 1289static inline const struct cls_match *
476f36e8
JR
1290find_match(const struct cls_subtable *subtable, const struct flow *flow,
1291 uint32_t hash)
b5d97350 1292{
dfea28b3 1293 const struct cls_match *rule;
b5d97350 1294
f2c21402 1295 CMAP_FOR_EACH_WITH_HASH (rule, cmap_node, hash, &subtable->rules) {
3016f3e4 1296 if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
e9319757 1297 flow)) {
b5d97350 1298 return rule;
064af421
BP
1299 }
1300 }
c23740be 1301
064af421
BP
1302 return NULL;
1303}
1304
e9319757
JR
1305/* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1306 * for which 'flow', for which 'mask' has a bit set, specifies a particular
1307 * value has the correct value in 'target'.
1308 *
1309 * This function is equivalent to miniflow_and_mask_matches_flow() but this
1310 * version fills in the mask bits in 'wc'. */
1311static inline bool
1312miniflow_and_mask_matches_flow_wc(const struct miniflow *flow,
1313 const struct minimask *mask,
1314 const struct flow *target,
1315 struct flow_wildcards *wc)
1316{
1317 const uint32_t *flowp = miniflow_get_u32_values(flow);
1318 const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1319 uint32_t idx;
1320
1321 MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1322 uint32_t mask = *maskp++;
1323 uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & mask;
1324
1325 if (diff) {
1326 /* Only unwildcard if none of the differing bits is already
1327 * exact-matched. */
1328 if (!(flow_u32_value(&wc->masks, idx) & diff)) {
1329 /* Keep one bit of the difference. */
1330 *flow_u32_lvalue(&wc->masks, idx) |= rightmost_1bit(diff);
1331 }
1332 return false;
1333 }
1334 /* Fill in the bits that were looked at. */
1335 *flow_u32_lvalue(&wc->masks, idx) |= mask;
1336 }
1337
1338 return true;
1339}
1340
386cb9f7
JR
1341/* Unwildcard the fields looked up so far, if any. */
1342static void
1343fill_range_wc(const struct cls_subtable *subtable, struct flow_wildcards *wc,
1344 uint8_t to)
1345{
1346 if (to) {
1347 flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, to);
1348 }
1349}
1350
dfea28b3 1351static const struct cls_match *
476f36e8 1352find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
13751fd8
JR
1353 struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1354 struct flow_wildcards *wc)
476f36e8
JR
1355{
1356 uint32_t basis = 0, hash;
dfea28b3 1357 const struct cls_match *rule = NULL;
476f36e8 1358 int i;
13751fd8 1359 struct range ofs;
476f36e8 1360
ec988646 1361 if (OVS_UNLIKELY(!wc)) {
476f36e8
JR
1362 return find_match(subtable, flow,
1363 flow_hash_in_minimask(flow, &subtable->mask, 0));
1364 }
1365
13751fd8 1366 ofs.start = 0;
476f36e8
JR
1367 /* Try to finish early by checking fields in segments. */
1368 for (i = 0; i < subtable->n_indices; i++) {
55847abe 1369 const struct cmap_node *inode;
f2c21402 1370
13751fd8 1371 ofs.end = subtable->index_ofs[i];
476f36e8 1372
13751fd8
JR
1373 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1374 wc)) {
386cb9f7
JR
1375 /* 'wc' bits for the trie field set, now unwildcard the preceding
1376 * bits used so far. */
1377 fill_range_wc(subtable, wc, ofs.start);
1378 return NULL;
13751fd8
JR
1379 }
1380 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1381 ofs.end, &basis);
f2c21402 1382 inode = cmap_find(&subtable->indices[i], hash);
476f36e8 1383 if (!inode) {
386cb9f7
JR
1384 /* No match, can stop immediately, but must fold in the bits
1385 * used in lookup so far. */
1386 fill_range_wc(subtable, wc, ofs.end);
1387 return NULL;
476f36e8
JR
1388 }
1389
1390 /* If we have narrowed down to a single rule already, check whether
a64759f0 1391 * that rule matches. Either way, we're done.
476f36e8
JR
1392 *
1393 * (Rare) hash collisions may cause us to miss the opportunity for this
1394 * optimization. */
f2c21402 1395 if (!cmap_node_next(inode)) {
476f36e8 1396 ASSIGN_CONTAINER(rule, inode - i, index_nodes);
e9319757
JR
1397 if (miniflow_and_mask_matches_flow_wc(&rule->flow, &subtable->mask,
1398 flow, wc)) {
1399 return rule;
476f36e8 1400 }
e9319757 1401 return NULL;
476f36e8 1402 }
386cb9f7 1403 ofs.start = ofs.end;
476f36e8 1404 }
13751fd8
JR
1405 ofs.end = FLOW_U32S;
1406 /* Trie check for the final range. */
1407 if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
386cb9f7
JR
1408 fill_range_wc(subtable, wc, ofs.start);
1409 return NULL;
13751fd8 1410 }
a64759f0
JR
1411 hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1412 ofs.end, &basis);
1413 rule = find_match(subtable, flow, hash);
69d6040e
JR
1414 if (!rule && subtable->ports_mask_len) {
1415 /* Ports are always part of the final range, if any.
1416 * No match was found for the ports. Use the ports trie to figure out
1417 * which ports bits to unwildcard. */
1418 unsigned int mbits;
c0bfb650 1419 ovs_be32 value, plens, mask;
69d6040e
JR
1420
1421 mask = MINIFLOW_GET_BE32(&subtable->mask.masks, tp_src);
1422 value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
c0bfb650 1423 mbits = trie_lookup_value(&subtable->ports_trie, &value, &plens, 32);
69d6040e
JR
1424
1425 ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
86f35fb5 1426 mask & be32_prefix_mask(mbits);
69d6040e 1427
386cb9f7
JR
1428 /* Unwildcard all bits in the mask upto the ports, as they were used
1429 * to determine there is no match. */
1430 fill_range_wc(subtable, wc, TP_PORTS_OFS32);
1431 return NULL;
69d6040e 1432 }
e9319757 1433
13751fd8 1434 /* Must unwildcard all the fields, as they were looked at. */
476f36e8
JR
1435 flow_wildcards_fold_minimask(wc, &subtable->mask);
1436 return rule;
1437}
1438
627fb667 1439static struct cls_match *
dfea28b3 1440find_equal(const struct cls_subtable *subtable, const struct miniflow *flow,
03868246 1441 uint32_t hash)
064af421 1442{
627fb667 1443 struct cls_match *head;
064af421 1444
f2c21402 1445 CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
3016f3e4 1446 if (miniflow_equal(&head->flow, flow)) {
b5d97350 1447 return head;
064af421
BP
1448 }
1449 }
1450 return NULL;
1451}
13751fd8
JR
1452\f
1453/* A longest-prefix match tree. */
13751fd8
JR
1454
1455/* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1456 * Prefixes are in the network byte order, and the offset 0 corresponds to
1457 * the most significant bit of the first byte. The offset can be read as
1458 * "how many bits to skip from the start of the prefix starting at 'pr'". */
1459static uint32_t
1460raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1461{
1462 uint32_t prefix;
1463
1464 pr += ofs / 32; /* Where to start. */
1465 ofs %= 32; /* How many bits to skip at 'pr'. */
1466
1467 prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1468 if (plen > 32 - ofs) { /* Need more than we have already? */
1469 prefix |= ntohl(*++pr) >> (32 - ofs);
1470 }
1471 /* Return with possible unwanted bits at the end. */
1472 return prefix;
1473}
1474
1475/* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1476 * offset 'ofs'. Prefixes are in the network byte order, and the offset 0
1477 * corresponds to the most significant bit of the first byte. The offset can
1478 * be read as "how many bits to skip from the start of the prefix starting at
1479 * 'pr'". */
1480static uint32_t
1481trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1482{
1483 if (!plen) {
1484 return 0;
1485 }
1486 if (plen > TRIE_PREFIX_BITS) {
1487 plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1488 }
1489 /* Return with unwanted bits cleared. */
1490 return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1491}
1492
c30cfa6b 1493/* Return the number of equal bits in 'n_bits' of 'prefix's MSBs and a 'value'
13751fd8
JR
1494 * starting at "MSB 0"-based offset 'ofs'. */
1495static unsigned int
c30cfa6b 1496prefix_equal_bits(uint32_t prefix, unsigned int n_bits, const ovs_be32 value[],
13751fd8
JR
1497 unsigned int ofs)
1498{
c30cfa6b 1499 uint64_t diff = prefix ^ raw_get_prefix(value, ofs, n_bits);
13751fd8 1500 /* Set the bit after the relevant bits to limit the result. */
c30cfa6b 1501 return raw_clz64(diff << 32 | UINT64_C(1) << (63 - n_bits));
13751fd8
JR
1502}
1503
1504/* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1505 * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1506static unsigned int
1507trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1508 unsigned int ofs, unsigned int plen)
1509{
c30cfa6b 1510 return prefix_equal_bits(node->prefix, MIN(node->n_bits, plen - ofs),
13751fd8
JR
1511 prefix, ofs);
1512}
1513
1514/* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' can
1515 * be greater than 31. */
1516static unsigned int
1517be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1518{
1519 return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1520}
1521
1522/* Return the bit at ("MSB 0"-based) offset 'ofs' as an int. 'ofs' must
1523 * be between 0 and 31, inclusive. */
1524static unsigned int
1525get_bit_at(const uint32_t prefix, unsigned int ofs)
1526{
1527 return (prefix >> (31 - ofs)) & 1u;
1528}
1529
1530/* Create new branch. */
1531static struct trie_node *
1532trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1533 unsigned int n_rules)
1534{
1535 struct trie_node *node = xmalloc(sizeof *node);
1536
1537 node->prefix = trie_get_prefix(prefix, ofs, plen);
1538
1539 if (plen <= TRIE_PREFIX_BITS) {
c30cfa6b 1540 node->n_bits = plen;
f358a2cb
JR
1541 ovsrcu_set_hidden(&node->edges[0], NULL);
1542 ovsrcu_set_hidden(&node->edges[1], NULL);
13751fd8
JR
1543 node->n_rules = n_rules;
1544 } else { /* Need intermediate nodes. */
1545 struct trie_node *subnode = trie_branch_create(prefix,
1546 ofs + TRIE_PREFIX_BITS,
1547 plen - TRIE_PREFIX_BITS,
1548 n_rules);
1549 int bit = get_bit_at(subnode->prefix, 0);
c30cfa6b 1550 node->n_bits = TRIE_PREFIX_BITS;
f358a2cb
JR
1551 ovsrcu_set_hidden(&node->edges[bit], subnode);
1552 ovsrcu_set_hidden(&node->edges[!bit], NULL);
13751fd8
JR
1553 node->n_rules = 0;
1554 }
1555 return node;
1556}
1557
1558static void
f358a2cb 1559trie_node_destroy(const struct trie_node *node)
13751fd8 1560{
f358a2cb
JR
1561 ovsrcu_postpone(free, CONST_CAST(struct trie_node *, node));
1562}
1563
1564/* Copy a trie node for modification and postpone delete the old one. */
1565static struct trie_node *
1566trie_node_rcu_realloc(const struct trie_node *node)
1567{
1568 struct trie_node *new_node = xmalloc(sizeof *node);
1569
1570 *new_node = *node;
1571 trie_node_destroy(node);
1572
1573 return new_node;
13751fd8
JR
1574}
1575
e48eccd1 1576/* May only be called while holding the classifier mutex. */
13751fd8 1577static void
f358a2cb 1578trie_destroy(rcu_trie_ptr *trie)
13751fd8 1579{
f358a2cb
JR
1580 struct trie_node *node = ovsrcu_get_protected(struct trie_node *, trie);
1581
13751fd8 1582 if (node) {
f358a2cb
JR
1583 ovsrcu_set_hidden(trie, NULL);
1584 trie_destroy(&node->edges[0]);
1585 trie_destroy(&node->edges[1]);
1586 trie_node_destroy(node);
13751fd8
JR
1587 }
1588}
1589
1590static bool
1591trie_is_leaf(const struct trie_node *trie)
1592{
f358a2cb
JR
1593 /* No children? */
1594 return !ovsrcu_get(struct trie_node *, &trie->edges[0])
1595 && !ovsrcu_get(struct trie_node *, &trie->edges[1]);
13751fd8
JR
1596}
1597
1598static void
1599mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
c30cfa6b 1600 unsigned int n_bits)
13751fd8
JR
1601{
1602 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1603 unsigned int i;
1604
c30cfa6b 1605 for (i = 0; i < n_bits / 32; i++) {
13751fd8
JR
1606 mask[i] = OVS_BE32_MAX;
1607 }
c30cfa6b
JR
1608 if (n_bits % 32) {
1609 mask[i] |= htonl(~0u << (32 - n_bits % 32));
13751fd8
JR
1610 }
1611}
1612
1613static bool
1614mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
c30cfa6b 1615 unsigned int n_bits)
13751fd8
JR
1616{
1617 ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1618 unsigned int i;
1619 ovs_be32 zeroes = 0;
1620
c30cfa6b 1621 for (i = 0; i < n_bits / 32; i++) {
13751fd8
JR
1622 zeroes |= ~mask[i];
1623 }
c30cfa6b
JR
1624 if (n_bits % 32) {
1625 zeroes |= ~mask[i] & htonl(~0u << (32 - n_bits % 32));
13751fd8
JR
1626 }
1627
c30cfa6b 1628 return !zeroes; /* All 'n_bits' bits set. */
13751fd8
JR
1629}
1630
f358a2cb 1631static rcu_trie_ptr *
13751fd8
JR
1632trie_next_edge(struct trie_node *node, const ovs_be32 value[],
1633 unsigned int ofs)
1634{
1635 return node->edges + be_get_bit_at(value, ofs);
1636}
1637
1638static const struct trie_node *
1639trie_next_node(const struct trie_node *node, const ovs_be32 value[],
1640 unsigned int ofs)
1641{
f358a2cb
JR
1642 return ovsrcu_get(struct trie_node *,
1643 &node->edges[be_get_bit_at(value, ofs)]);
13751fd8
JR
1644}
1645
c0bfb650
JR
1646/* Set the bit at ("MSB 0"-based) offset 'ofs'. 'ofs' can be greater than 31.
1647 */
1648static void
1649be_set_bit_at(ovs_be32 value[], unsigned int ofs)
1650{
1651 ((uint8_t *)value)[ofs / 8] |= 1u << (7 - ofs % 8);
1652}
1653
1654/* Returns the number of bits in the prefix mask necessary to determine a
1655 * mismatch, in case there are longer prefixes in the tree below the one that
1656 * matched.
1657 * '*plens' will have a bit set for each prefix length that may have matching
1658 * rules. The caller is responsible for clearing the '*plens' prior to
1659 * calling this.
13751fd8
JR
1660 */
1661static unsigned int
f358a2cb 1662trie_lookup_value(const rcu_trie_ptr *trie, const ovs_be32 value[],
c0bfb650 1663 ovs_be32 plens[], unsigned int n_bits)
13751fd8 1664{
13751fd8 1665 const struct trie_node *prev = NULL;
c0bfb650
JR
1666 const struct trie_node *node = ovsrcu_get(struct trie_node *, trie);
1667 unsigned int match_len = 0; /* Number of matching bits. */
13751fd8 1668
27ce650f 1669 for (; node; prev = node, node = trie_next_node(node, value, match_len)) {
13751fd8
JR
1670 unsigned int eqbits;
1671 /* Check if this edge can be followed. */
27ce650f
JR
1672 eqbits = prefix_equal_bits(node->prefix, node->n_bits, value,
1673 match_len);
1674 match_len += eqbits;
c30cfa6b 1675 if (eqbits < node->n_bits) { /* Mismatch, nothing more to be found. */
27ce650f 1676 /* Bit at offset 'match_len' differed. */
c0bfb650 1677 return match_len + 1; /* Includes the first mismatching bit. */
13751fd8
JR
1678 }
1679 /* Full match, check if rules exist at this prefix length. */
1680 if (node->n_rules > 0) {
c0bfb650 1681 be_set_bit_at(plens, match_len - 1);
13751fd8 1682 }
27ce650f 1683 if (match_len >= n_bits) {
c0bfb650 1684 return n_bits; /* Full prefix. */
f0e5aa11 1685 }
13751fd8 1686 }
c0bfb650
JR
1687 /* node == NULL. Full match so far, but we tried to follow an
1688 * non-existing branch. Need to exclude the other branch if it exists
1689 * (it does not if we were called on an empty trie or 'prev' is a leaf
1690 * node). */
1691 return !prev || trie_is_leaf(prev) ? match_len : match_len + 1;
13751fd8
JR
1692}
1693
1694static unsigned int
1695trie_lookup(const struct cls_trie *trie, const struct flow *flow,
c0bfb650 1696 union mf_value *plens)
13751fd8
JR
1697{
1698 const struct mf_field *mf = trie->field;
1699
1700 /* Check that current flow matches the prerequisites for the trie
1701 * field. Some match fields are used for multiple purposes, so we
1702 * must check that the trie is relevant for this flow. */
1703 if (mf_are_prereqs_ok(mf, flow)) {
f358a2cb 1704 return trie_lookup_value(&trie->root,
13751fd8 1705 &((ovs_be32 *)flow)[mf->flow_be32ofs],
c0bfb650 1706 &plens->be32, mf->n_bits);
13751fd8 1707 }
c0bfb650
JR
1708 memset(plens, 0xff, sizeof *plens); /* All prefixes, no skipping. */
1709 return 0; /* Value not used in this case. */
13751fd8
JR
1710}
1711
1712/* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
1713 * Returns the u32 offset to the miniflow data in '*miniflow_index', if
1714 * 'miniflow_index' is not NULL. */
1715static unsigned int
1716minimask_get_prefix_len(const struct minimask *minimask,
1717 const struct mf_field *mf)
1718{
c30cfa6b 1719 unsigned int n_bits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
13751fd8
JR
1720 uint8_t u32_ofs = mf->flow_be32ofs;
1721 uint8_t u32_end = u32_ofs + mf->n_bytes / 4;
1722
1723 for (; u32_ofs < u32_end; ++u32_ofs) {
1724 uint32_t mask;
1725 mask = ntohl((OVS_FORCE ovs_be32)minimask_get(minimask, u32_ofs));
1726
1727 /* Validate mask, count the mask length. */
1728 if (mask_tz) {
1729 if (mask) {
1730 return 0; /* No bits allowed after mask ended. */
1731 }
1732 } else {
1733 if (~mask & (~mask + 1)) {
1734 return 0; /* Mask not contiguous. */
1735 }
1736 mask_tz = ctz32(mask);
c30cfa6b 1737 n_bits += 32 - mask_tz;
13751fd8
JR
1738 }
1739 }
1740
c30cfa6b 1741 return n_bits;
13751fd8
JR
1742}
1743
1744/*
1745 * This is called only when mask prefix is known to be CIDR and non-zero.
1746 * Relies on the fact that the flow and mask have the same map, and since
1747 * the mask is CIDR, the storage for the flow field exists even if it
1748 * happened to be zeros.
1749 */
1750static const ovs_be32 *
1751minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
1752{
27bbe15d 1753 return miniflow_get_be32_values(&match->flow) +
13751fd8
JR
1754 count_1bits(match->flow.map & ((UINT64_C(1) << mf->flow_be32ofs) - 1));
1755}
1756
1757/* Insert rule in to the prefix tree.
1758 * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1759 * in 'rule'. */
1760static void
1761trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1762{
69d6040e
JR
1763 trie_insert_prefix(&trie->root,
1764 minimatch_get_prefix(&rule->match, trie->field), mlen);
1765}
1766
1767static void
f358a2cb 1768trie_insert_prefix(rcu_trie_ptr *edge, const ovs_be32 *prefix, int mlen)
69d6040e 1769{
13751fd8 1770 struct trie_node *node;
13751fd8
JR
1771 int ofs = 0;
1772
1773 /* Walk the tree. */
f358a2cb 1774 for (; (node = ovsrcu_get_protected(struct trie_node *, edge));
13751fd8
JR
1775 edge = trie_next_edge(node, prefix, ofs)) {
1776 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
1777 ofs += eqbits;
c30cfa6b 1778 if (eqbits < node->n_bits) {
13751fd8
JR
1779 /* Mismatch, new node needs to be inserted above. */
1780 int old_branch = get_bit_at(node->prefix, eqbits);
f358a2cb 1781 struct trie_node *new_parent;
13751fd8 1782
f358a2cb
JR
1783 new_parent = trie_branch_create(prefix, ofs - eqbits, eqbits,
1784 ofs == mlen ? 1 : 0);
1785 /* Copy the node to modify it. */
1786 node = trie_node_rcu_realloc(node);
1787 /* Adjust the new node for its new position in the tree. */
13751fd8 1788 node->prefix <<= eqbits;
c30cfa6b 1789 node->n_bits -= eqbits;
f358a2cb 1790 ovsrcu_set_hidden(&new_parent->edges[old_branch], node);
13751fd8
JR
1791
1792 /* Check if need a new branch for the new rule. */
1793 if (ofs < mlen) {
f358a2cb
JR
1794 ovsrcu_set_hidden(&new_parent->edges[!old_branch],
1795 trie_branch_create(prefix, ofs, mlen - ofs,
1796 1));
13751fd8 1797 }
f358a2cb 1798 ovsrcu_set(edge, new_parent); /* Publish changes. */
13751fd8
JR
1799 return;
1800 }
1801 /* Full match so far. */
1802
1803 if (ofs == mlen) {
1804 /* Full match at the current node, rule needs to be added here. */
1805 node->n_rules++;
1806 return;
1807 }
1808 }
1809 /* Must insert a new tree branch for the new rule. */
f358a2cb 1810 ovsrcu_set(edge, trie_branch_create(prefix, ofs, mlen - ofs, 1));
13751fd8
JR
1811}
1812
1813/* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1814 * in 'rule'. */
1815static void
1816trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
1817{
69d6040e
JR
1818 trie_remove_prefix(&trie->root,
1819 minimatch_get_prefix(&rule->match, trie->field), mlen);
1820}
1821
1822/* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
1823 * in 'rule'. */
1824static void
f358a2cb 1825trie_remove_prefix(rcu_trie_ptr *root, const ovs_be32 *prefix, int mlen)
69d6040e 1826{
13751fd8 1827 struct trie_node *node;
f358a2cb 1828 rcu_trie_ptr *edges[sizeof(union mf_value) * 8];
13751fd8
JR
1829 int depth = 0, ofs = 0;
1830
1831 /* Walk the tree. */
69d6040e 1832 for (edges[0] = root;
f358a2cb 1833 (node = ovsrcu_get_protected(struct trie_node *, edges[depth]));
13751fd8
JR
1834 edges[++depth] = trie_next_edge(node, prefix, ofs)) {
1835 unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
69d6040e 1836
c30cfa6b 1837 if (eqbits < node->n_bits) {
13751fd8
JR
1838 /* Mismatch, nothing to be removed. This should never happen, as
1839 * only rules in the classifier are ever removed. */
1840 break; /* Log a warning. */
1841 }
1842 /* Full match so far. */
1843 ofs += eqbits;
1844
1845 if (ofs == mlen) {
1846 /* Full prefix match at the current node, remove rule here. */
1847 if (!node->n_rules) {
1848 break; /* Log a warning. */
1849 }
1850 node->n_rules--;
1851
1852 /* Check if can prune the tree. */
f358a2cb
JR
1853 while (!node->n_rules) {
1854 struct trie_node *next,
1855 *edge0 = ovsrcu_get_protected(struct trie_node *,
1856 &node->edges[0]),
1857 *edge1 = ovsrcu_get_protected(struct trie_node *,
1858 &node->edges[1]);
1859
1860 if (edge0 && edge1) {
1861 break; /* A branching point, cannot prune. */
1862 }
1863
1864 /* Else have at most one child node, remove this node. */
1865 next = edge0 ? edge0 : edge1;
13751fd8
JR
1866
1867 if (next) {
c30cfa6b 1868 if (node->n_bits + next->n_bits > TRIE_PREFIX_BITS) {
13751fd8
JR
1869 break; /* Cannot combine. */
1870 }
f358a2cb
JR
1871 next = trie_node_rcu_realloc(next); /* Modify. */
1872
13751fd8 1873 /* Combine node with next. */
c30cfa6b
JR
1874 next->prefix = node->prefix | next->prefix >> node->n_bits;
1875 next->n_bits += node->n_bits;
13751fd8 1876 }
13751fd8 1877 /* Update the parent's edge. */
f358a2cb
JR
1878 ovsrcu_set(edges[depth], next); /* Publish changes. */
1879 trie_node_destroy(node);
1880
13751fd8
JR
1881 if (next || !depth) {
1882 /* Branch not pruned or at root, nothing more to do. */
1883 break;
1884 }
f358a2cb
JR
1885 node = ovsrcu_get_protected(struct trie_node *,
1886 edges[--depth]);
13751fd8
JR
1887 }
1888 return;
1889 }
1890 }
1891 /* Cannot go deeper. This should never happen, since only rules
1892 * that actually exist in the classifier are ever removed. */
1893 VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");
1894}