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