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