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