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