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