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