lib/classifier: RCUify prefix trie code.
[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     fat_rwlock_init(&cls_->rwlock);
485     ovs_mutex_init(&cls->mutex);
486
487     ovs_mutex_lock(&cls->mutex);
488     cls_->cls = cls;
489
490     cls->n_rules = 0;
491     cmap_init(&cls->subtables_map);
492     pvector_init(&cls->subtables);
493     cmap_init(&cls->partitions);
494     cls->n_flow_segments = 0;
495     if (flow_segments) {
496         while (cls->n_flow_segments < CLS_MAX_INDICES
497                && *flow_segments < FLOW_U32S) {
498             cls->flow_segments[cls->n_flow_segments++] = *flow_segments++;
499         }
500     }
501     cls->n_tries = 0;
502     for (int i = 0; i < CLS_MAX_TRIES; i++) {
503         trie_init(cls, i, NULL);
504     }
505     ovs_mutex_unlock(&cls->mutex);
506 }
507
508 /* Destroys 'cls'.  Rules within 'cls', if any, are not freed; this is the
509  * caller's responsibility. */
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         fat_rwlock_destroy(&cls_->rwlock);
521         if (!cls) {
522             return;
523         }
524
525         ovs_mutex_lock(&cls->mutex);
526         for (i = 0; i < cls->n_tries; i++) {
527             trie_destroy(&cls->tries[i].root);
528         }
529
530         CMAP_FOR_EACH_SAFE (subtable, next_subtable, cmap_node,
531                             &cls->subtables_map) {
532             destroy_subtable(cls, subtable);
533         }
534         cmap_destroy(&cls->subtables_map);
535
536         CMAP_FOR_EACH_SAFE (partition, next_partition, cmap_node,
537                             &cls->partitions) {
538             ovsrcu_postpone(free, partition);
539         }
540         cmap_destroy(&cls->partitions);
541
542         pvector_destroy(&cls->subtables);
543         ovs_mutex_unlock(&cls->mutex);
544         ovs_mutex_destroy(&cls->mutex);
545         free(cls);
546     }
547 }
548
549 /* We use uint64_t as a set for the fields below. */
550 BUILD_ASSERT_DECL(MFF_N_IDS <= 64);
551
552 /* Set the fields for which prefix lookup should be performed. */
553 bool
554 classifier_set_prefix_fields(struct classifier *cls_,
555                              const enum mf_field_id *trie_fields,
556                              unsigned int n_fields)
557     OVS_EXCLUDED(cls_->cls->mutex)
558 {
559     struct cls_classifier *cls = cls_->cls;
560     uint64_t fields = 0;
561     const struct mf_field * new_fields[CLS_MAX_TRIES];
562     int i, n_tries = 0;
563     bool changed = false;
564
565     ovs_mutex_lock(&cls->mutex);
566     for (i = 0; i < n_fields && n_tries < CLS_MAX_TRIES; i++) {
567         const struct mf_field *field = mf_from_id(trie_fields[i]);
568         if (field->flow_be32ofs < 0 || field->n_bits % 32) {
569             /* Incompatible field.  This is the only place where we
570              * enforce these requirements, but the rest of the trie code
571              * depends on the flow_be32ofs to be non-negative and the
572              * field length to be a multiple of 32 bits. */
573             continue;
574         }
575
576         if (fields & (UINT64_C(1) << trie_fields[i])) {
577             /* Duplicate field, there is no need to build more than
578              * one index for any one field. */
579             continue;
580         }
581         fields |= UINT64_C(1) << trie_fields[i];
582
583         new_fields[n_tries] = NULL;
584         if (n_tries >= cls->n_tries || field != cls->tries[n_tries].field) {
585             new_fields[n_tries] = field;
586             changed = true;
587         }
588         n_tries++;
589     }
590
591     if (changed || n_tries < cls->n_tries) {
592         struct cls_subtable *subtable;
593
594         /* Trie configuration needs to change.  Disable trie lookups
595          * for the tries that are changing and wait all the current readers
596          * with the old configuration to be done. */
597         changed = false;
598         CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
599             for (i = 0; i < cls->n_tries; i++) {
600                 if ((i < n_tries && new_fields[i]) || i >= n_tries) {
601                     if (subtable->trie_plen[i]) {
602                         subtable->trie_plen[i] = 0;
603                         changed = true;
604                     }
605                 }
606             }
607         }
608         /* Synchronize if any readers were using tries.  The readers may
609          * temporarily function without the trie lookup based optimizations. */
610         if (changed) {
611             /* ovsrcu_synchronize() functions as a memory barrier, so it does
612              * not matter that subtable->trie_plen is not atomic. */
613             ovsrcu_synchronize();
614         }
615
616         /* Now set up the tries. */
617         for (i = 0; i < n_tries; i++) {
618             if (new_fields[i]) {
619                 trie_init(cls, i, new_fields[i]);
620             }
621         }
622         /* Destroy the rest, if any. */
623         for (; i < cls->n_tries; i++) {
624             trie_init(cls, i, NULL);
625         }
626
627         cls->n_tries = n_tries;
628         ovs_mutex_unlock(&cls->mutex);
629         return true;
630     }
631
632     ovs_mutex_unlock(&cls->mutex);
633     return false; /* No change. */
634 }
635
636 static void
637 trie_init(struct cls_classifier *cls, int trie_idx,
638           const struct mf_field *field)
639     OVS_REQUIRES(cls->mutex)
640 {
641     struct cls_trie *trie = &cls->tries[trie_idx];
642     struct cls_subtable *subtable;
643
644     if (trie_idx < cls->n_tries) {
645         trie_destroy(&trie->root);
646     } else {
647         ovsrcu_set_hidden(&trie->root, NULL);
648     }
649     trie->field = field;
650
651     /* Add existing rules to the new trie. */
652     CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
653         unsigned int plen;
654
655         plen = field ? minimask_get_prefix_len(&subtable->mask, field) : 0;
656         if (plen) {
657             struct cls_match *head;
658
659             CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
660                 struct cls_match *match;
661
662                 FOR_EACH_RULE_IN_LIST (match, head) {
663                     trie_insert(trie, match->cls_rule, plen);
664                 }
665             }
666         }
667         /* Initialize subtable's prefix length on this field.  This will
668          * allow readers to use the trie. */
669         atomic_thread_fence(memory_order_release);
670         subtable->trie_plen[trie_idx] = plen;
671     }
672 }
673
674 /* Returns true if 'cls' contains no classification rules, false otherwise.
675  * Checking the cmap requires no locking. */
676 bool
677 classifier_is_empty(const struct classifier *cls)
678 {
679     return cmap_is_empty(&cls->cls->subtables_map);
680 }
681
682 /* Returns the number of rules in 'cls'. */
683 int
684 classifier_count(const struct classifier *cls)
685 {
686     return cls->cls->n_rules;
687 }
688
689 static uint32_t
690 hash_metadata(ovs_be64 metadata_)
691 {
692     uint64_t metadata = (OVS_FORCE uint64_t) metadata_;
693     return hash_uint64(metadata);
694 }
695
696 static struct cls_partition *
697 find_partition(const struct cls_classifier *cls, ovs_be64 metadata,
698                uint32_t hash)
699 {
700     struct cls_partition *partition;
701
702     CMAP_FOR_EACH_WITH_HASH (partition, cmap_node, hash, &cls->partitions) {
703         if (partition->metadata == metadata) {
704             return partition;
705         }
706     }
707
708     return NULL;
709 }
710
711 static struct cls_partition *
712 create_partition(struct cls_classifier *cls, struct cls_subtable *subtable,
713                  ovs_be64 metadata)
714     OVS_REQUIRES(cls->mutex)
715 {
716     uint32_t hash = hash_metadata(metadata);
717     struct cls_partition *partition = find_partition(cls, metadata, hash);
718     if (!partition) {
719         partition = xmalloc(sizeof *partition);
720         partition->metadata = metadata;
721         partition->tags = 0;
722         tag_tracker_init(&partition->tracker);
723         cmap_insert(&cls->partitions, &partition->cmap_node, hash);
724     }
725     tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
726     return partition;
727 }
728
729 static inline ovs_be32 minimatch_get_ports(const struct minimatch *match)
730 {
731     /* Could optimize to use the same map if needed for fast path. */
732     return MINIFLOW_GET_BE32(&match->flow, tp_src)
733         & MINIFLOW_GET_BE32(&match->mask.masks, tp_src);
734 }
735
736 /* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
737  * must not modify or free it.
738  *
739  * If 'cls' already contains an identical rule (including wildcards, values of
740  * fixed fields, and priority), replaces the old rule by 'rule' and returns the
741  * rule that was replaced.  The caller takes ownership of the returned rule and
742  * is thus responsible for destroying it with cls_rule_destroy(), freeing the
743  * memory block in which it resides, etc., as necessary.
744  *
745  * Returns NULL if 'cls' does not contain a rule with an identical key, after
746  * inserting the new rule.  In this case, no rules are displaced by the new
747  * rule, even rules that cannot have any effect because the new rule matches a
748  * superset of their flows and has higher priority. */
749 struct cls_rule *
750 classifier_replace(struct classifier *cls_, struct cls_rule *rule)
751     OVS_EXCLUDED(cls_->cls->mutex)
752 {
753     struct cls_classifier *cls = cls_->cls;
754     struct cls_match *old_rule;
755     struct cls_subtable *subtable;
756     struct cls_rule *old_cls_rule = NULL;
757
758     ovs_mutex_lock(&cls->mutex);
759     subtable = find_subtable(cls, &rule->match.mask);
760     if (!subtable) {
761         subtable = insert_subtable(cls, &rule->match.mask);
762     }
763
764     old_rule = insert_rule(cls, subtable, rule);
765     if (!old_rule) {
766         old_cls_rule = NULL;
767
768         rule->cls_match->partition = NULL;
769         if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
770             ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
771             rule->cls_match->partition = create_partition(cls, subtable,
772                                                           metadata);
773         }
774
775         cls->n_rules++;
776
777         for (int i = 0; i < cls->n_tries; i++) {
778             if (subtable->trie_plen[i]) {
779                 trie_insert(&cls->tries[i], rule, subtable->trie_plen[i]);
780             }
781         }
782
783         /* Ports trie. */
784         if (subtable->ports_mask_len) {
785             /* We mask the value to be inserted to always have the wildcarded
786              * bits in known (zero) state, so we can include them in comparison
787              * and they will always match (== their original value does not
788              * matter). */
789             ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
790
791             trie_insert_prefix(&subtable->ports_trie, &masked_ports,
792                                subtable->ports_mask_len);
793         }
794     } else {
795         old_cls_rule = old_rule->cls_rule;
796         rule->cls_match->partition = old_rule->partition;
797         old_cls_rule->cls_match = NULL;
798
799         /* 'old_rule' contains a cmap_node, which may not be freed
800          * immediately. */
801         ovsrcu_postpone(free, old_rule);
802     }
803     ovs_mutex_unlock(&cls->mutex);
804     return old_cls_rule;
805 }
806
807 /* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
808  * must not modify or free it.
809  *
810  * 'cls' must not contain an identical rule (including wildcards, values of
811  * fixed fields, and priority).  Use classifier_find_rule_exactly() to find
812  * such a rule. */
813 void
814 classifier_insert(struct classifier *cls, struct cls_rule *rule)
815 {
816     struct cls_rule *displaced_rule = classifier_replace(cls, rule);
817     ovs_assert(!displaced_rule);
818 }
819
820 /* Removes 'rule' from 'cls'.  It is the caller's responsibility to destroy
821  * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
822  * resides, etc., as necessary. */
823 void
824 classifier_remove(struct classifier *cls_, struct cls_rule *rule)
825     OVS_EXCLUDED(cls_->cls->mutex)
826 {
827     struct cls_classifier *cls = cls_->cls;
828     struct cls_partition *partition;
829     struct cls_match *cls_match = rule->cls_match;
830     struct cls_match *head;
831     struct cls_subtable *subtable;
832     int i;
833     uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
834     uint8_t prev_be32ofs = 0;
835
836     ovs_assert(cls_match);
837
838     ovs_mutex_lock(&cls->mutex);
839     subtable = find_subtable(cls, &rule->match.mask);
840     ovs_assert(subtable);
841
842     if (subtable->ports_mask_len) {
843         ovs_be32 masked_ports = minimatch_get_ports(&rule->match);
844
845         trie_remove_prefix(&subtable->ports_trie,
846                            &masked_ports, subtable->ports_mask_len);
847     }
848     for (i = 0; i < cls->n_tries; i++) {
849         if (subtable->trie_plen[i]) {
850             trie_remove(&cls->tries[i], rule, subtable->trie_plen[i]);
851         }
852     }
853
854     /* Remove rule node from indices. */
855     for (i = 0; i < subtable->n_indices; i++) {
856         ihash[i] = minimatch_hash_range(&rule->match, prev_be32ofs,
857                                         subtable->index_ofs[i], &basis);
858         cmap_remove(&subtable->indices[i], &cls_match->index_nodes[i],
859                     ihash[i]);
860         prev_be32ofs = subtable->index_ofs[i];
861     }
862     hash = minimatch_hash_range(&rule->match, prev_be32ofs, FLOW_U32S, &basis);
863
864     head = find_equal(subtable, &rule->match.flow, hash);
865     if (head != cls_match) {
866         list_remove(&cls_match->list);
867     } else if (list_is_empty(&cls_match->list)) {
868         cmap_remove(&subtable->rules, &cls_match->cmap_node, hash);
869     } else {
870         struct cls_match *next = CONTAINER_OF(cls_match->list.next,
871                                               struct cls_match, list);
872
873         list_remove(&cls_match->list);
874         cmap_replace(&subtable->rules, &cls_match->cmap_node,
875                      &next->cmap_node, hash);
876     }
877
878     partition = cls_match->partition;
879     if (partition) {
880         tag_tracker_subtract(&partition->tracker, &partition->tags,
881                              subtable->tag);
882         if (!partition->tags) {
883             cmap_remove(&cls->partitions, &partition->cmap_node,
884                         hash_metadata(partition->metadata));
885             ovsrcu_postpone(free, partition);
886         }
887     }
888
889     if (--subtable->n_rules == 0) {
890         destroy_subtable(cls, subtable);
891     } else if (subtable->max_priority == cls_match->priority
892                && --subtable->max_count == 0) {
893         /* Find the new 'max_priority' and 'max_count'. */
894         struct cls_match *head;
895         unsigned int max_priority = 0;
896
897         CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
898             if (head->priority > max_priority) {
899                 max_priority = head->priority;
900                 subtable->max_count = 1;
901             } else if (head->priority == max_priority) {
902                 ++subtable->max_count;
903             }
904         }
905         subtable->max_priority = max_priority;
906         pvector_change_priority(&cls->subtables, subtable, max_priority);
907     }
908
909     cls->n_rules--;
910
911     rule->cls_match = NULL;
912     ovsrcu_postpone(free, cls_match);
913     ovs_mutex_unlock(&cls->mutex);
914 }
915
916 /* Prefix tree context.  Valid when 'lookup_done' is true.  Can skip all
917  * subtables which have more than 'match_plen' bits in their corresponding
918  * field at offset 'be32ofs'.  If skipped, 'maskbits' prefix bits should be
919  * unwildcarded to quarantee datapath flow matches only packets it should. */
920 struct trie_ctx {
921     const struct cls_trie *trie;
922     bool lookup_done;        /* Status of the lookup. */
923     uint8_t be32ofs;         /* U32 offset of the field in question. */
924     unsigned int match_plen; /* Longest prefix than could possibly match. */
925     unsigned int maskbits;   /* Prefix length needed to avoid false matches. */
926 };
927
928 static void
929 trie_ctx_init(struct trie_ctx *ctx, const struct cls_trie *trie)
930 {
931     ctx->trie = trie;
932     ctx->be32ofs = trie->field->flow_be32ofs;
933     ctx->lookup_done = false;
934 }
935
936 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
937  * Returns a null pointer if no rules in 'cls' match 'flow'.  If multiple rules
938  * of equal priority match 'flow', returns one arbitrarily.
939  *
940  * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
941  * set of bits that were significant in the lookup.  At some point
942  * earlier, 'wc' should have been initialized (e.g., by
943  * flow_wildcards_init_catchall()). */
944 struct cls_rule *
945 classifier_lookup(const struct classifier *cls_, const struct flow *flow,
946                   struct flow_wildcards *wc)
947 {
948     struct cls_classifier *cls = cls_->cls;
949     const struct cls_partition *partition;
950     tag_type tags;
951     int64_t best_priority = -1;
952     const struct cls_match *best;
953     struct trie_ctx trie_ctx[CLS_MAX_TRIES];
954     struct cls_subtable *subtable;
955
956     /* Synchronize for cls->n_tries and subtable->trie_plen.  They can change
957      * when table configuration changes, which happens typically only on
958      * startup. */
959     atomic_thread_fence(memory_order_acquire);
960
961     /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
962      * then 'flow' cannot possibly match in 'subtable':
963      *
964      *     - If flow->metadata maps to a given 'partition', then we can use
965      *       'tags' for 'partition->tags'.
966      *
967      *     - If flow->metadata has no partition, then no rule in 'cls' has an
968      *       exact-match for flow->metadata.  That means that we don't need to
969      *       search any subtable that includes flow->metadata in its mask.
970      *
971      * In either case, we always need to search any cls_subtables that do not
972      * include flow->metadata in its mask.  One way to do that would be to
973      * check the "cls_subtable"s explicitly for that, but that would require an
974      * extra branch per subtable.  Instead, we mark such a cls_subtable's
975      * 'tags' as TAG_ALL and make sure that 'tags' is never empty.  This means
976      * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
977      * need a special case.
978      */
979     partition = (cmap_is_empty(&cls->partitions)
980                  ? NULL
981                  : find_partition(cls, flow->metadata,
982                                   hash_metadata(flow->metadata)));
983     tags = partition ? partition->tags : TAG_ARBITRARY;
984
985     /* Initialize trie contexts for match_find_wc(). */
986     for (int i = 0; i < cls->n_tries; i++) {
987         trie_ctx_init(&trie_ctx[i], &cls->tries[i]);
988     }
989
990     best = NULL;
991     PVECTOR_FOR_EACH_PRIORITY(subtable, best_priority, 2,
992                               sizeof(struct cls_subtable), &cls->subtables) {
993         struct cls_match *rule;
994
995         if (!tag_intersects(tags, subtable->tag)) {
996             continue;
997         }
998
999         rule = find_match_wc(subtable, flow, trie_ctx, cls->n_tries, wc);
1000         if (rule && (int64_t)rule->priority > best_priority) {
1001             best_priority = (int64_t)rule->priority;
1002             best = rule;
1003         }
1004     }
1005
1006     return best ? best->cls_rule : NULL;
1007 }
1008
1009 /* Returns true if 'target' satisifies 'match', that is, if each bit for which
1010  * 'match' specifies a particular value has the correct value in 'target'.
1011  *
1012  * 'flow' and 'mask' have the same mask! */
1013 static bool
1014 miniflow_and_mask_matches_miniflow(const struct miniflow *flow,
1015                                    const struct minimask *mask,
1016                                    const struct miniflow *target)
1017 {
1018     const uint32_t *flowp = miniflow_get_u32_values(flow);
1019     const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1020     uint32_t target_u32;
1021
1022     MINIFLOW_FOR_EACH_IN_MAP(target_u32, target, mask->masks.map) {
1023         if ((*flowp++ ^ target_u32) & *maskp++) {
1024             return false;
1025         }
1026     }
1027
1028     return true;
1029 }
1030
1031 static inline struct cls_match *
1032 find_match_miniflow(const struct cls_subtable *subtable,
1033                     const struct miniflow *flow,
1034                     uint32_t hash)
1035 {
1036     struct cls_match *rule;
1037
1038     CMAP_FOR_EACH_WITH_HASH (rule, cmap_node, hash, &subtable->rules) {
1039         if (miniflow_and_mask_matches_miniflow(&rule->flow, &subtable->mask,
1040                                                flow)) {
1041             return rule;
1042         }
1043     }
1044
1045     return NULL;
1046 }
1047
1048 /* For each miniflow in 'flows' performs a classifier lookup writing the result
1049  * into the corresponding slot in 'rules'.  If a particular entry in 'flows' is
1050  * NULL it is skipped.
1051  *
1052  * This function is optimized for use in the userspace datapath and therefore
1053  * does not implement a lot of features available in the standard
1054  * classifier_lookup() function.  Specifically, it does not implement
1055  * priorities, instead returning any rule which matches the flow. */
1056 void
1057 classifier_lookup_miniflow_batch(const struct classifier *cls_,
1058                                  const struct miniflow **flows,
1059                                  struct cls_rule **rules, size_t len)
1060 {
1061     struct cls_classifier *cls = cls_->cls;
1062     struct cls_subtable *subtable;
1063     size_t i, begin = 0;
1064
1065     memset(rules, 0, len * sizeof *rules);
1066     PVECTOR_FOR_EACH (subtable, &cls->subtables) {
1067         for (i = begin; i < len; i++) {
1068             struct cls_match *match;
1069             uint32_t hash;
1070
1071             if (OVS_UNLIKELY(rules[i] || !flows[i])) {
1072                 continue;
1073             }
1074
1075             hash = miniflow_hash_in_minimask(flows[i], &subtable->mask, 0);
1076             match = find_match_miniflow(subtable, flows[i], hash);
1077             if (OVS_UNLIKELY(match)) {
1078                 rules[i] = match->cls_rule;
1079             }
1080         }
1081
1082         while (begin < len && (rules[begin] || !flows[begin])) {
1083             begin++;
1084         }
1085         if (begin >= len) {
1086             break;
1087         }
1088     }
1089 }
1090
1091 /* Finds and returns a rule in 'cls' with exactly the same priority and
1092  * matching criteria as 'target'.  Returns a null pointer if 'cls' doesn't
1093  * contain an exact match. */
1094 struct cls_rule *
1095 classifier_find_rule_exactly(const struct classifier *cls_,
1096                              const struct cls_rule *target)
1097     OVS_EXCLUDED(cls_->cls->mutex)
1098 {
1099     struct cls_classifier *cls = cls_->cls;
1100     struct cls_match *head, *rule;
1101     struct cls_subtable *subtable;
1102
1103     ovs_mutex_lock(&cls->mutex);
1104     subtable = find_subtable(cls, &target->match.mask);
1105     if (!subtable) {
1106         goto out;
1107     }
1108
1109     /* Skip if there is no hope. */
1110     if (target->priority > subtable->max_priority) {
1111         goto out;
1112     }
1113
1114     head = find_equal(subtable, &target->match.flow,
1115                       miniflow_hash_in_minimask(&target->match.flow,
1116                                                 &target->match.mask, 0));
1117     FOR_EACH_RULE_IN_LIST (rule, head) {
1118         if (target->priority >= rule->priority) {
1119             ovs_mutex_unlock(&cls->mutex);
1120             return target->priority == rule->priority ? rule->cls_rule : NULL;
1121         }
1122     }
1123 out:
1124     ovs_mutex_unlock(&cls->mutex);
1125     return NULL;
1126 }
1127
1128 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
1129  * same matching criteria as 'target'.  Returns a null pointer if 'cls' doesn't
1130  * contain an exact match. */
1131 struct cls_rule *
1132 classifier_find_match_exactly(const struct classifier *cls,
1133                               const struct match *target,
1134                               unsigned int priority)
1135 {
1136     struct cls_rule *retval;
1137     struct cls_rule cr;
1138
1139     cls_rule_init(&cr, target, priority);
1140     retval = classifier_find_rule_exactly(cls, &cr);
1141     cls_rule_destroy(&cr);
1142
1143     return retval;
1144 }
1145
1146 /* Checks if 'target' would overlap any other rule in 'cls'.  Two rules are
1147  * considered to overlap if both rules have the same priority and a packet
1148  * could match both. */
1149 bool
1150 classifier_rule_overlaps(const struct classifier *cls_,
1151                          const struct cls_rule *target)
1152     OVS_EXCLUDED(cls_->cls->mutex)
1153 {
1154     struct cls_classifier *cls = cls_->cls;
1155     struct cls_subtable *subtable;
1156     int64_t stop_at_priority = (int64_t)target->priority - 1;
1157
1158     ovs_mutex_lock(&cls->mutex);
1159     /* Iterate subtables in the descending max priority order. */
1160     PVECTOR_FOR_EACH_PRIORITY (subtable, stop_at_priority, 2,
1161                                sizeof(struct cls_subtable), &cls->subtables) {
1162         uint32_t storage[FLOW_U32S];
1163         struct minimask mask;
1164         struct cls_match *head;
1165
1166         minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
1167         CMAP_FOR_EACH (head, cmap_node, &subtable->rules) {
1168             struct cls_match *rule;
1169
1170             FOR_EACH_RULE_IN_LIST (rule, head) {
1171                 if (rule->priority < target->priority) {
1172                     break; /* Rules in descending priority order. */
1173                 }
1174                 if (rule->priority == target->priority
1175                     && miniflow_equal_in_minimask(&target->match.flow,
1176                                                   &rule->flow, &mask)) {
1177                     ovs_mutex_unlock(&cls->mutex);
1178                     return true;
1179                 }
1180             }
1181         }
1182     }
1183
1184     ovs_mutex_unlock(&cls->mutex);
1185     return false;
1186 }
1187
1188 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
1189  * specific than 'criteria'.  That is, 'rule' matches 'criteria' and this
1190  * function returns true if, for every field:
1191  *
1192  *   - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
1193  *     field, or
1194  *
1195  *   - 'criteria' wildcards the field,
1196  *
1197  * Conversely, 'rule' does not match 'criteria' and this function returns false
1198  * if, for at least one field:
1199  *
1200  *   - 'criteria' and 'rule' specify different values for the field, or
1201  *
1202  *   - 'criteria' specifies a value for the field but 'rule' wildcards it.
1203  *
1204  * Equivalently, the truth table for whether a field matches is:
1205  *
1206  *                                     rule
1207  *
1208  *                   c         wildcard    exact
1209  *                   r        +---------+---------+
1210  *                   i   wild |   yes   |   yes   |
1211  *                   t   card |         |         |
1212  *                   e        +---------+---------+
1213  *                   r  exact |    no   |if values|
1214  *                   i        |         |are equal|
1215  *                   a        +---------+---------+
1216  *
1217  * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
1218  * commands and by OpenFlow 1.0 aggregate and flow stats.
1219  *
1220  * Ignores rule->priority. */
1221 bool
1222 cls_rule_is_loose_match(const struct cls_rule *rule,
1223                         const struct minimatch *criteria)
1224 {
1225     return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
1226             && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
1227                                           &criteria->mask));
1228 }
1229 \f
1230 /* Iteration. */
1231
1232 static bool
1233 rule_matches(const struct cls_match *rule, const struct cls_rule *target)
1234 {
1235     return (!target
1236             || miniflow_equal_in_minimask(&rule->flow,
1237                                           &target->match.flow,
1238                                           &target->match.mask));
1239 }
1240
1241 static struct cls_match *
1242 search_subtable(const struct cls_subtable *subtable,
1243                 struct cls_cursor *cursor)
1244 {
1245     if (!cursor->target
1246         || !minimask_has_extra(&subtable->mask, &cursor->target->match.mask)) {
1247         struct cls_match *rule;
1248
1249         CMAP_CURSOR_FOR_EACH (rule, cmap_node, &cursor->rules,
1250                               &subtable->rules) {
1251             if (rule_matches(rule, cursor->target)) {
1252                 return rule;
1253             }
1254         }
1255     }
1256     return NULL;
1257 }
1258
1259 /* Initializes 'cursor' for iterating through rules in 'cls', and returns the
1260  * first matching cls_rule via '*pnode', or NULL if there are no matches.
1261  *
1262  *     - If 'target' is null, the cursor will visit every rule in 'cls'.
1263  *
1264  *     - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
1265  *       such that cls_rule_is_loose_match(rule, target) returns true.
1266  *
1267  * Ignores target->priority. */
1268 struct cls_cursor cls_cursor_init(const struct classifier *cls,
1269                                   const struct cls_rule *target,
1270                                   void **pnode, const void *offset, bool safe)
1271     OVS_NO_THREAD_SAFETY_ANALYSIS
1272 {
1273     struct cls_cursor cursor;
1274     struct cls_subtable *subtable;
1275     struct cls_rule *cls_rule = NULL;
1276
1277     cursor.safe = safe;
1278     cursor.cls = cls->cls;
1279     cursor.target = target && !cls_rule_is_catchall(target) ? target : NULL;
1280
1281     /* Find first rule. */
1282     ovs_mutex_lock(&cursor.cls->mutex);
1283     CMAP_CURSOR_FOR_EACH (subtable, cmap_node, &cursor.subtables,
1284                           &cursor.cls->subtables_map) {
1285         struct cls_match *rule = search_subtable(subtable, &cursor);
1286
1287         if (rule) {
1288             cursor.subtable = subtable;
1289             cls_rule = rule->cls_rule;
1290             break;
1291         }
1292     }
1293     *pnode = (char *)cls_rule + (ptrdiff_t)offset;
1294
1295     /* Leave locked if requested and have a rule. */
1296     if (safe || !cls_rule) {
1297         ovs_mutex_unlock(&cursor.cls->mutex);
1298     }
1299     return cursor;
1300 }
1301
1302 static void
1303 cls_cursor_next_unlock(struct cls_cursor *cursor, struct cls_rule *rule)
1304     OVS_NO_THREAD_SAFETY_ANALYSIS
1305 {
1306     /* Release the mutex if no rule, or 'safe' mode. */
1307     if (!rule || cursor->safe) {
1308         ovs_mutex_unlock(&cursor->cls->mutex);
1309     }
1310 }
1311
1312 /* Returns the next matching cls_rule in 'cursor''s iteration, or a null
1313  * pointer if there are no more matches. */
1314 struct cls_rule *
1315 cls_cursor_next(struct cls_cursor *cursor, const struct cls_rule *rule_)
1316     OVS_NO_THREAD_SAFETY_ANALYSIS
1317 {
1318     struct cls_match *rule = CONST_CAST(struct cls_match *, rule_->cls_match);
1319     const struct cls_subtable *subtable;
1320     struct cls_match *next;
1321
1322     /* Lock if not locked already. */
1323     if (cursor->safe) {
1324         ovs_mutex_lock(&cursor->cls->mutex);
1325     }
1326
1327     next = next_rule_in_list__(rule);
1328     if (next->priority < rule->priority) {
1329         cls_cursor_next_unlock(cursor, next->cls_rule);
1330         return next->cls_rule;
1331     }
1332
1333     /* 'next' is the head of the list, that is, the rule that is included in
1334      * the subtable's map.  (This is important when the classifier contains
1335      * rules that differ only in priority.) */
1336     rule = next;
1337     CMAP_CURSOR_FOR_EACH_CONTINUE (rule, cmap_node, &cursor->rules) {
1338         if (rule_matches(rule, cursor->target)) {
1339             cls_cursor_next_unlock(cursor, rule->cls_rule);
1340             return rule->cls_rule;
1341         }
1342     }
1343
1344     subtable = cursor->subtable;
1345     CMAP_CURSOR_FOR_EACH_CONTINUE (subtable, cmap_node, &cursor->subtables) {
1346         rule = search_subtable(subtable, cursor);
1347         if (rule) {
1348             cursor->subtable = subtable;
1349             cls_cursor_next_unlock(cursor, rule->cls_rule);
1350             return rule->cls_rule;
1351         }
1352     }
1353
1354     ovs_mutex_unlock(&cursor->cls->mutex);
1355     return NULL;
1356 }
1357 \f
1358 static struct cls_subtable *
1359 find_subtable(const struct cls_classifier *cls, const struct minimask *mask)
1360     OVS_REQUIRES(cls->mutex)
1361 {
1362     struct cls_subtable *subtable;
1363
1364     CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, minimask_hash(mask, 0),
1365                              &cls->subtables_map) {
1366         if (minimask_equal(mask, &subtable->mask)) {
1367             return subtable;
1368         }
1369     }
1370     return NULL;
1371 }
1372
1373 /* The new subtable will be visible to the readers only after this. */
1374 static struct cls_subtable *
1375 insert_subtable(struct cls_classifier *cls, const struct minimask *mask)
1376     OVS_REQUIRES(cls->mutex)
1377 {
1378     uint32_t hash = minimask_hash(mask, 0);
1379     struct cls_subtable *subtable;
1380     int i, index = 0;
1381     struct flow_wildcards old, new;
1382     uint8_t prev;
1383     int count = count_1bits(mask->masks.map);
1384
1385     subtable = xzalloc(sizeof *subtable - sizeof mask->masks.inline_values
1386                        + MINIFLOW_VALUES_SIZE(count));
1387     cmap_init(&subtable->rules);
1388     miniflow_clone_inline(&subtable->mask.masks, &mask->masks, count);
1389
1390     /* Init indices for segmented lookup, if any. */
1391     flow_wildcards_init_catchall(&new);
1392     old = new;
1393     prev = 0;
1394     for (i = 0; i < cls->n_flow_segments; i++) {
1395         flow_wildcards_fold_minimask_range(&new, mask, prev,
1396                                            cls->flow_segments[i]);
1397         /* Add an index if it adds mask bits. */
1398         if (!flow_wildcards_equal(&new, &old)) {
1399             cmap_init(&subtable->indices[index]);
1400             subtable->index_ofs[index] = cls->flow_segments[i];
1401             index++;
1402             old = new;
1403         }
1404         prev = cls->flow_segments[i];
1405     }
1406     /* Check if the rest of the subtable's mask adds any bits,
1407      * and remove the last index if it doesn't. */
1408     if (index > 0) {
1409         flow_wildcards_fold_minimask_range(&new, mask, prev, FLOW_U32S);
1410         if (flow_wildcards_equal(&new, &old)) {
1411             --index;
1412             subtable->index_ofs[index] = 0;
1413             cmap_destroy(&subtable->indices[index]);
1414         }
1415     }
1416     subtable->n_indices = index;
1417
1418     subtable->tag = (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
1419                      ? tag_create_deterministic(hash)
1420                      : TAG_ALL);
1421
1422     for (i = 0; i < cls->n_tries; i++) {
1423         subtable->trie_plen[i] = minimask_get_prefix_len(mask,
1424                                                          cls->tries[i].field);
1425     }
1426
1427     /* Ports trie. */
1428     ovsrcu_set_hidden(&subtable->ports_trie, NULL);
1429     subtable->ports_mask_len
1430         = 32 - ctz32(ntohl(MINIFLOW_GET_BE32(&mask->masks, tp_src)));
1431
1432     cmap_insert(&cls->subtables_map, &subtable->cmap_node, hash);
1433
1434     return subtable;
1435 }
1436
1437 static void
1438 destroy_subtable(struct cls_classifier *cls, struct cls_subtable *subtable)
1439     OVS_REQUIRES(cls->mutex)
1440 {
1441     int i;
1442
1443     pvector_remove(&cls->subtables, subtable);
1444     trie_destroy(&subtable->ports_trie);
1445
1446     for (i = 0; i < subtable->n_indices; i++) {
1447         cmap_destroy(&subtable->indices[i]);
1448     }
1449     cmap_remove(&cls->subtables_map, &subtable->cmap_node,
1450                 minimask_hash(&subtable->mask, 0));
1451     minimask_destroy(&subtable->mask);
1452     cmap_destroy(&subtable->rules);
1453     ovsrcu_postpone(free, subtable);
1454 }
1455
1456 struct range {
1457     uint8_t start;
1458     uint8_t end;
1459 };
1460
1461 /* Return 'true' if can skip rest of the subtable based on the prefix trie
1462  * lookup results. */
1463 static inline bool
1464 check_tries(struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1465             const unsigned int field_plen[CLS_MAX_TRIES],
1466             const struct range ofs, const struct flow *flow,
1467             struct flow_wildcards *wc)
1468 {
1469     int j;
1470
1471     /* Check if we could avoid fully unwildcarding the next level of
1472      * fields using the prefix tries.  The trie checks are done only as
1473      * needed to avoid folding in additional bits to the wildcards mask. */
1474     for (j = 0; j < n_tries; j++) {
1475         /* Is the trie field relevant for this subtable? */
1476         if (field_plen[j]) {
1477             struct trie_ctx *ctx = &trie_ctx[j];
1478             uint8_t be32ofs = ctx->be32ofs;
1479
1480             /* Is the trie field within the current range of fields? */
1481             if (be32ofs >= ofs.start && be32ofs < ofs.end) {
1482                 /* On-demand trie lookup. */
1483                 if (!ctx->lookup_done) {
1484                     ctx->match_plen = trie_lookup(ctx->trie, flow,
1485                                                   &ctx->maskbits);
1486                     ctx->lookup_done = true;
1487                 }
1488                 /* Possible to skip the rest of the subtable if subtable's
1489                  * prefix on the field is longer than what is known to match
1490                  * based on the trie lookup. */
1491                 if (field_plen[j] > ctx->match_plen) {
1492                     /* RFC: We want the trie lookup to never result in
1493                      * unwildcarding any bits that would not be unwildcarded
1494                      * otherwise.  Since the trie is shared by the whole
1495                      * classifier, it is possible that the 'maskbits' contain
1496                      * bits that are irrelevant for the partition of the
1497                      * classifier relevant for the current flow. */
1498
1499                     /* Can skip if the field is already unwildcarded. */
1500                     if (mask_prefix_bits_set(wc, be32ofs, ctx->maskbits)) {
1501                         return true;
1502                     }
1503                     /* Check that the trie result will not unwildcard more bits
1504                      * than this stage will. */
1505                     if (ctx->maskbits <= field_plen[j]) {
1506                         /* Unwildcard the bits and skip the rest. */
1507                         mask_set_prefix_bits(wc, be32ofs, ctx->maskbits);
1508                         /* Note: Prerequisite already unwildcarded, as the only
1509                          * prerequisite of the supported trie lookup fields is
1510                          * the ethertype, which is currently always
1511                          * unwildcarded.
1512                          */
1513                         return true;
1514                     }
1515                 }
1516             }
1517         }
1518     }
1519     return false;
1520 }
1521
1522 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1523  * for which 'flow', for which 'mask' has a bit set, specifies a particular
1524  * value has the correct value in 'target'.
1525  *
1526  * This function is equivalent to miniflow_equal_flow_in_minimask(flow,
1527  * target, mask) but this is faster because of the invariant that
1528  * flow->map and mask->masks.map are the same, and that this version
1529  * takes the 'wc'. */
1530 static inline bool
1531 miniflow_and_mask_matches_flow(const struct miniflow *flow,
1532                                const struct minimask *mask,
1533                                const struct flow *target)
1534 {
1535     const uint32_t *flowp = miniflow_get_u32_values(flow);
1536     const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1537     uint32_t idx;
1538
1539     MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1540         uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & *maskp++;
1541
1542         if (diff) {
1543             return false;
1544         }
1545     }
1546
1547     return true;
1548 }
1549
1550 static inline struct cls_match *
1551 find_match(const struct cls_subtable *subtable, const struct flow *flow,
1552            uint32_t hash)
1553 {
1554     struct cls_match *rule;
1555
1556     CMAP_FOR_EACH_WITH_HASH (rule, cmap_node, hash, &subtable->rules) {
1557         if (miniflow_and_mask_matches_flow(&rule->flow, &subtable->mask,
1558                                            flow)) {
1559             return rule;
1560         }
1561     }
1562
1563     return NULL;
1564 }
1565
1566 /* Returns true if 'target' satisifies 'flow'/'mask', that is, if each bit
1567  * for which 'flow', for which 'mask' has a bit set, specifies a particular
1568  * value has the correct value in 'target'.
1569  *
1570  * This function is equivalent to miniflow_and_mask_matches_flow() but this
1571  * version fills in the mask bits in 'wc'. */
1572 static inline bool
1573 miniflow_and_mask_matches_flow_wc(const struct miniflow *flow,
1574                                   const struct minimask *mask,
1575                                   const struct flow *target,
1576                                   struct flow_wildcards *wc)
1577 {
1578     const uint32_t *flowp = miniflow_get_u32_values(flow);
1579     const uint32_t *maskp = miniflow_get_u32_values(&mask->masks);
1580     uint32_t idx;
1581
1582     MAP_FOR_EACH_INDEX(idx, mask->masks.map) {
1583         uint32_t mask = *maskp++;
1584         uint32_t diff = (*flowp++ ^ flow_u32_value(target, idx)) & mask;
1585
1586         if (diff) {
1587             /* Only unwildcard if none of the differing bits is already
1588              * exact-matched. */
1589             if (!(flow_u32_value(&wc->masks, idx) & diff)) {
1590                 /* Keep one bit of the difference. */
1591                 *flow_u32_lvalue(&wc->masks, idx) |= rightmost_1bit(diff);
1592             }
1593             return false;
1594         }
1595         /* Fill in the bits that were looked at. */
1596         *flow_u32_lvalue(&wc->masks, idx) |= mask;
1597     }
1598
1599     return true;
1600 }
1601
1602 /* Unwildcard the fields looked up so far, if any. */
1603 static void
1604 fill_range_wc(const struct cls_subtable *subtable, struct flow_wildcards *wc,
1605               uint8_t to)
1606 {
1607     if (to) {
1608         flow_wildcards_fold_minimask_range(wc, &subtable->mask, 0, to);
1609     }
1610 }
1611
1612 static struct cls_match *
1613 find_match_wc(const struct cls_subtable *subtable, const struct flow *flow,
1614               struct trie_ctx trie_ctx[CLS_MAX_TRIES], unsigned int n_tries,
1615               struct flow_wildcards *wc)
1616 {
1617     uint32_t basis = 0, hash;
1618     struct cls_match *rule;
1619     int i;
1620     struct range ofs;
1621
1622     if (OVS_UNLIKELY(!wc)) {
1623         return find_match(subtable, flow,
1624                           flow_hash_in_minimask(flow, &subtable->mask, 0));
1625     }
1626
1627     ofs.start = 0;
1628     /* Try to finish early by checking fields in segments. */
1629     for (i = 0; i < subtable->n_indices; i++) {
1630         struct cmap_node *inode;
1631
1632         ofs.end = subtable->index_ofs[i];
1633
1634         if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow,
1635                         wc)) {
1636             /* 'wc' bits for the trie field set, now unwildcard the preceding
1637              * bits used so far. */
1638             fill_range_wc(subtable, wc, ofs.start);
1639             return NULL;
1640         }
1641         hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1642                                            ofs.end, &basis);
1643         inode = cmap_find(&subtable->indices[i], hash);
1644         if (!inode) {
1645             /* No match, can stop immediately, but must fold in the bits
1646              * used in lookup so far. */
1647             fill_range_wc(subtable, wc, ofs.end);
1648             return NULL;
1649         }
1650
1651         /* If we have narrowed down to a single rule already, check whether
1652          * that rule matches.  Either way, we're done.
1653          *
1654          * (Rare) hash collisions may cause us to miss the opportunity for this
1655          * optimization. */
1656         if (!cmap_node_next(inode)) {
1657             ASSIGN_CONTAINER(rule, inode - i, index_nodes);
1658             if (miniflow_and_mask_matches_flow_wc(&rule->flow, &subtable->mask,
1659                                                   flow, wc)) {
1660                 return rule;
1661             }
1662             return NULL;
1663         }
1664         ofs.start = ofs.end;
1665     }
1666     ofs.end = FLOW_U32S;
1667     /* Trie check for the final range. */
1668     if (check_tries(trie_ctx, n_tries, subtable->trie_plen, ofs, flow, wc)) {
1669         fill_range_wc(subtable, wc, ofs.start);
1670         return NULL;
1671     }
1672     hash = flow_hash_in_minimask_range(flow, &subtable->mask, ofs.start,
1673                                        ofs.end, &basis);
1674     rule = find_match(subtable, flow, hash);
1675     if (!rule && subtable->ports_mask_len) {
1676         /* Ports are always part of the final range, if any.
1677          * No match was found for the ports.  Use the ports trie to figure out
1678          * which ports bits to unwildcard. */
1679         unsigned int mbits;
1680         ovs_be32 value, mask;
1681
1682         mask = MINIFLOW_GET_BE32(&subtable->mask.masks, tp_src);
1683         value = ((OVS_FORCE ovs_be32 *)flow)[TP_PORTS_OFS32] & mask;
1684         trie_lookup_value(&subtable->ports_trie, &value, 32, &mbits);
1685
1686         ((OVS_FORCE ovs_be32 *)&wc->masks)[TP_PORTS_OFS32] |=
1687             mask & htonl(~0 << (32 - mbits));
1688
1689         /* Unwildcard all bits in the mask upto the ports, as they were used
1690          * to determine there is no match. */
1691         fill_range_wc(subtable, wc, TP_PORTS_OFS32);
1692         return NULL;
1693     }
1694
1695     /* Must unwildcard all the fields, as they were looked at. */
1696     flow_wildcards_fold_minimask(wc, &subtable->mask);
1697     return rule;
1698 }
1699
1700 static struct cls_match *
1701 find_equal(struct cls_subtable *subtable, const struct miniflow *flow,
1702            uint32_t hash)
1703 {
1704     struct cls_match *head;
1705
1706     CMAP_FOR_EACH_WITH_HASH (head, cmap_node, hash, &subtable->rules) {
1707         if (miniflow_equal(&head->flow, flow)) {
1708             return head;
1709         }
1710     }
1711     return NULL;
1712 }
1713
1714 static struct cls_match *
1715 insert_rule(struct cls_classifier *cls, struct cls_subtable *subtable,
1716             struct cls_rule *new_rule)
1717     OVS_REQUIRES(cls->mutex)
1718 {
1719     struct cls_match *old = NULL;
1720     struct cls_match *new = cls_match_alloc(new_rule);
1721     struct cls_match *head;
1722     int i;
1723     uint32_t basis = 0, hash, ihash[CLS_MAX_INDICES];
1724     uint8_t prev_be32ofs = 0;
1725
1726     /* Add new node to segment indices. */
1727     for (i = 0; i < subtable->n_indices; i++) {
1728         ihash[i] = minimatch_hash_range(&new_rule->match, prev_be32ofs,
1729                                         subtable->index_ofs[i], &basis);
1730         cmap_insert(&subtable->indices[i], &new->index_nodes[i], ihash[i]);
1731         prev_be32ofs = subtable->index_ofs[i];
1732     }
1733     hash = minimatch_hash_range(&new_rule->match, prev_be32ofs, FLOW_U32S,
1734                                 &basis);
1735     head = find_equal(subtable, &new_rule->match.flow, hash);
1736     if (!head) {
1737         cmap_insert(&subtable->rules, &new->cmap_node, hash);
1738         list_init(&new->list);
1739         goto out;
1740     } else {
1741         /* Scan the list for the insertion point that will keep the list in
1742          * order of decreasing priority. */
1743         struct cls_match *rule;
1744
1745         FOR_EACH_RULE_IN_LIST (rule, head) {
1746             if (new->priority >= rule->priority) {
1747                 if (rule == head) {
1748                     /* 'new' is the new highest-priority flow in the list. */
1749                     cmap_replace(&subtable->rules, &rule->cmap_node,
1750                                  &new->cmap_node, hash);
1751                 }
1752
1753                 if (new->priority == rule->priority) {
1754                     list_replace(&new->list, &rule->list);
1755                     old = rule;
1756                 } else {
1757                     list_insert(&rule->list, &new->list);
1758                 }
1759                 goto out;
1760             }
1761         }
1762
1763         /* Insert 'new' at the end of the list. */
1764         list_push_back(&head->list, &new->list);
1765     }
1766
1767  out:
1768     if (!old) {
1769         subtable->n_rules++;
1770
1771         /* Rule was added, not replaced.  Update 'subtable's 'max_priority'
1772          * and 'max_count', if necessary. */
1773         if (subtable->n_rules == 1) {
1774             subtable->max_priority = new->priority;
1775             subtable->max_count = 1;
1776             pvector_insert(&cls->subtables, subtable, new->priority);
1777         } else if (subtable->max_priority == new->priority) {
1778             ++subtable->max_count;
1779         } else if (new->priority > subtable->max_priority) {
1780             subtable->max_priority = new->priority;
1781             subtable->max_count = 1;
1782             pvector_change_priority(&cls->subtables, subtable, new->priority);
1783         }
1784     } else {
1785         /* Remove old node from indices. */
1786         for (i = 0; i < subtable->n_indices; i++) {
1787             cmap_remove(&subtable->indices[i], &old->index_nodes[i], ihash[i]);
1788         }
1789     }
1790     return old;
1791 }
1792
1793 static struct cls_match *
1794 next_rule_in_list__(struct cls_match *rule)
1795     OVS_NO_THREAD_SAFETY_ANALYSIS
1796 {
1797     struct cls_match *next = OBJECT_CONTAINING(rule->list.next, next, list);
1798     return next;
1799 }
1800
1801 static struct cls_match *
1802 next_rule_in_list(struct cls_match *rule)
1803 {
1804     struct cls_match *next = next_rule_in_list__(rule);
1805     return next->priority < rule->priority ? next : NULL;
1806 }
1807 \f
1808 /* A longest-prefix match tree. */
1809 struct trie_node {
1810     uint32_t prefix;           /* Prefix bits for this node, MSB first. */
1811     uint8_t  n_bits;           /* Never zero, except for the root node. */
1812     unsigned int n_rules;      /* Number of rules that have this prefix. */
1813     rcu_trie_ptr edges[2];     /* Both NULL if leaf. */
1814 };
1815
1816 /* Max bits per node.  Must fit in struct trie_node's 'prefix'.
1817  * Also tested with 16, 8, and 5 to stress the implementation. */
1818 #define TRIE_PREFIX_BITS 32
1819
1820 /* Return at least 'plen' bits of the 'prefix', starting at bit offset 'ofs'.
1821  * Prefixes are in the network byte order, and the offset 0 corresponds to
1822  * the most significant bit of the first byte.  The offset can be read as
1823  * "how many bits to skip from the start of the prefix starting at 'pr'". */
1824 static uint32_t
1825 raw_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1826 {
1827     uint32_t prefix;
1828
1829     pr += ofs / 32; /* Where to start. */
1830     ofs %= 32;      /* How many bits to skip at 'pr'. */
1831
1832     prefix = ntohl(*pr) << ofs; /* Get the first 32 - ofs bits. */
1833     if (plen > 32 - ofs) {      /* Need more than we have already? */
1834         prefix |= ntohl(*++pr) >> (32 - ofs);
1835     }
1836     /* Return with possible unwanted bits at the end. */
1837     return prefix;
1838 }
1839
1840 /* Return min(TRIE_PREFIX_BITS, plen) bits of the 'prefix', starting at bit
1841  * offset 'ofs'.  Prefixes are in the network byte order, and the offset 0
1842  * corresponds to the most significant bit of the first byte.  The offset can
1843  * be read as "how many bits to skip from the start of the prefix starting at
1844  * 'pr'". */
1845 static uint32_t
1846 trie_get_prefix(const ovs_be32 pr[], unsigned int ofs, unsigned int plen)
1847 {
1848     if (!plen) {
1849         return 0;
1850     }
1851     if (plen > TRIE_PREFIX_BITS) {
1852         plen = TRIE_PREFIX_BITS; /* Get at most TRIE_PREFIX_BITS. */
1853     }
1854     /* Return with unwanted bits cleared. */
1855     return raw_get_prefix(pr, ofs, plen) & ~0u << (32 - plen);
1856 }
1857
1858 /* Return the number of equal bits in 'n_bits' of 'prefix's MSBs and a 'value'
1859  * starting at "MSB 0"-based offset 'ofs'. */
1860 static unsigned int
1861 prefix_equal_bits(uint32_t prefix, unsigned int n_bits, const ovs_be32 value[],
1862                   unsigned int ofs)
1863 {
1864     uint64_t diff = prefix ^ raw_get_prefix(value, ofs, n_bits);
1865     /* Set the bit after the relevant bits to limit the result. */
1866     return raw_clz64(diff << 32 | UINT64_C(1) << (63 - n_bits));
1867 }
1868
1869 /* Return the number of equal bits in 'node' prefix and a 'prefix' of length
1870  * 'plen', starting at "MSB 0"-based offset 'ofs'. */
1871 static unsigned int
1872 trie_prefix_equal_bits(const struct trie_node *node, const ovs_be32 prefix[],
1873                        unsigned int ofs, unsigned int plen)
1874 {
1875     return prefix_equal_bits(node->prefix, MIN(node->n_bits, plen - ofs),
1876                              prefix, ofs);
1877 }
1878
1879 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int.  'ofs' can
1880  * be greater than 31. */
1881 static unsigned int
1882 be_get_bit_at(const ovs_be32 value[], unsigned int ofs)
1883 {
1884     return (((const uint8_t *)value)[ofs / 8] >> (7 - ofs % 8)) & 1u;
1885 }
1886
1887 /* Return the bit at ("MSB 0"-based) offset 'ofs' as an int.  'ofs' must
1888  * be between 0 and 31, inclusive. */
1889 static unsigned int
1890 get_bit_at(const uint32_t prefix, unsigned int ofs)
1891 {
1892     return (prefix >> (31 - ofs)) & 1u;
1893 }
1894
1895 /* Create new branch. */
1896 static struct trie_node *
1897 trie_branch_create(const ovs_be32 *prefix, unsigned int ofs, unsigned int plen,
1898                    unsigned int n_rules)
1899 {
1900     struct trie_node *node = xmalloc(sizeof *node);
1901
1902     node->prefix = trie_get_prefix(prefix, ofs, plen);
1903
1904     if (plen <= TRIE_PREFIX_BITS) {
1905         node->n_bits = plen;
1906         ovsrcu_set_hidden(&node->edges[0], NULL);
1907         ovsrcu_set_hidden(&node->edges[1], NULL);
1908         node->n_rules = n_rules;
1909     } else { /* Need intermediate nodes. */
1910         struct trie_node *subnode = trie_branch_create(prefix,
1911                                                        ofs + TRIE_PREFIX_BITS,
1912                                                        plen - TRIE_PREFIX_BITS,
1913                                                        n_rules);
1914         int bit = get_bit_at(subnode->prefix, 0);
1915         node->n_bits = TRIE_PREFIX_BITS;
1916         ovsrcu_set_hidden(&node->edges[bit], subnode);
1917         ovsrcu_set_hidden(&node->edges[!bit], NULL);
1918         node->n_rules = 0;
1919     }
1920     return node;
1921 }
1922
1923 static void
1924 trie_node_destroy(const struct trie_node *node)
1925 {
1926     ovsrcu_postpone(free, CONST_CAST(struct trie_node *, node));
1927 }
1928
1929 /* Copy a trie node for modification and postpone delete the old one. */
1930 static struct trie_node *
1931 trie_node_rcu_realloc(const struct trie_node *node)
1932 {
1933     struct trie_node *new_node = xmalloc(sizeof *node);
1934
1935     *new_node = *node;
1936     trie_node_destroy(node);
1937
1938     return new_node;
1939 }
1940
1941 /* May only be called while holding the cls_classifier mutex. */
1942 static void
1943 trie_destroy(rcu_trie_ptr *trie)
1944 {
1945     struct trie_node *node = ovsrcu_get_protected(struct trie_node *, trie);
1946
1947     if (node) {
1948         ovsrcu_set_hidden(trie, NULL);
1949         trie_destroy(&node->edges[0]);
1950         trie_destroy(&node->edges[1]);
1951         trie_node_destroy(node);
1952     }
1953 }
1954
1955 static bool
1956 trie_is_leaf(const struct trie_node *trie)
1957 {
1958     /* No children? */
1959     return !ovsrcu_get(struct trie_node *, &trie->edges[0])
1960         && !ovsrcu_get(struct trie_node *, &trie->edges[1]);
1961 }
1962
1963 static void
1964 mask_set_prefix_bits(struct flow_wildcards *wc, uint8_t be32ofs,
1965                      unsigned int n_bits)
1966 {
1967     ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1968     unsigned int i;
1969
1970     for (i = 0; i < n_bits / 32; i++) {
1971         mask[i] = OVS_BE32_MAX;
1972     }
1973     if (n_bits % 32) {
1974         mask[i] |= htonl(~0u << (32 - n_bits % 32));
1975     }
1976 }
1977
1978 static bool
1979 mask_prefix_bits_set(const struct flow_wildcards *wc, uint8_t be32ofs,
1980                      unsigned int n_bits)
1981 {
1982     ovs_be32 *mask = &((ovs_be32 *)&wc->masks)[be32ofs];
1983     unsigned int i;
1984     ovs_be32 zeroes = 0;
1985
1986     for (i = 0; i < n_bits / 32; i++) {
1987         zeroes |= ~mask[i];
1988     }
1989     if (n_bits % 32) {
1990         zeroes |= ~mask[i] & htonl(~0u << (32 - n_bits % 32));
1991     }
1992
1993     return !zeroes; /* All 'n_bits' bits set. */
1994 }
1995
1996 static rcu_trie_ptr *
1997 trie_next_edge(struct trie_node *node, const ovs_be32 value[],
1998                unsigned int ofs)
1999 {
2000     return node->edges + be_get_bit_at(value, ofs);
2001 }
2002
2003 static const struct trie_node *
2004 trie_next_node(const struct trie_node *node, const ovs_be32 value[],
2005                unsigned int ofs)
2006 {
2007     return ovsrcu_get(struct trie_node *,
2008                       &node->edges[be_get_bit_at(value, ofs)]);
2009 }
2010
2011 /* Return the prefix mask length necessary to find the longest-prefix match for
2012  * the '*value' in the prefix tree 'node'.
2013  * '*checkbits' is set to the number of bits in the prefix mask necessary to
2014  * determine a mismatch, in case there are longer prefixes in the tree below
2015  * the one that matched.
2016  */
2017 static unsigned int
2018 trie_lookup_value(const rcu_trie_ptr *trie, const ovs_be32 value[],
2019                   unsigned int n_bits, unsigned int *checkbits)
2020 {
2021     const struct trie_node *node = ovsrcu_get(struct trie_node *, trie);
2022     unsigned int ofs = 0, match_len = 0;
2023     const struct trie_node *prev = NULL;
2024
2025     for (; node; prev = node, node = trie_next_node(node, value, ofs)) {
2026         unsigned int eqbits;
2027         /* Check if this edge can be followed. */
2028         eqbits = prefix_equal_bits(node->prefix, node->n_bits, value, ofs);
2029         ofs += eqbits;
2030         if (eqbits < node->n_bits) { /* Mismatch, nothing more to be found. */
2031             /* Bit at offset 'ofs' differed. */
2032             *checkbits = ofs + 1; /* Includes the first mismatching bit. */
2033             return match_len;
2034         }
2035         /* Full match, check if rules exist at this prefix length. */
2036         if (node->n_rules > 0) {
2037             match_len = ofs;
2038         }
2039         if (ofs >= n_bits) {
2040             *checkbits = n_bits; /* Full prefix. */
2041             return match_len;
2042         }
2043     }
2044     /* node == NULL.  Full match so far, but we came to a dead end.
2045      * need to exclude the other branch if it exists. */
2046     *checkbits = !prev || trie_is_leaf(prev) ? ofs : ofs + 1;
2047     return match_len;
2048 }
2049
2050 static unsigned int
2051 trie_lookup(const struct cls_trie *trie, const struct flow *flow,
2052             unsigned int *checkbits)
2053 {
2054     const struct mf_field *mf = trie->field;
2055
2056     /* Check that current flow matches the prerequisites for the trie
2057      * field.  Some match fields are used for multiple purposes, so we
2058      * must check that the trie is relevant for this flow. */
2059     if (mf_are_prereqs_ok(mf, flow)) {
2060         return trie_lookup_value(&trie->root,
2061                                  &((ovs_be32 *)flow)[mf->flow_be32ofs],
2062                                  mf->n_bits, checkbits);
2063     }
2064     *checkbits = 0; /* Value not used in this case. */
2065     return UINT_MAX;
2066 }
2067
2068 /* Returns the length of a prefix match mask for the field 'mf' in 'minimask'.
2069  * Returns the u32 offset to the miniflow data in '*miniflow_index', if
2070  * 'miniflow_index' is not NULL. */
2071 static unsigned int
2072 minimask_get_prefix_len(const struct minimask *minimask,
2073                         const struct mf_field *mf)
2074 {
2075     unsigned int n_bits = 0, mask_tz = 0; /* Non-zero when end of mask seen. */
2076     uint8_t u32_ofs = mf->flow_be32ofs;
2077     uint8_t u32_end = u32_ofs + mf->n_bytes / 4;
2078
2079     for (; u32_ofs < u32_end; ++u32_ofs) {
2080         uint32_t mask;
2081         mask = ntohl((OVS_FORCE ovs_be32)minimask_get(minimask, u32_ofs));
2082
2083         /* Validate mask, count the mask length. */
2084         if (mask_tz) {
2085             if (mask) {
2086                 return 0; /* No bits allowed after mask ended. */
2087             }
2088         } else {
2089             if (~mask & (~mask + 1)) {
2090                 return 0; /* Mask not contiguous. */
2091             }
2092             mask_tz = ctz32(mask);
2093             n_bits += 32 - mask_tz;
2094         }
2095     }
2096
2097     return n_bits;
2098 }
2099
2100 /*
2101  * This is called only when mask prefix is known to be CIDR and non-zero.
2102  * Relies on the fact that the flow and mask have the same map, and since
2103  * the mask is CIDR, the storage for the flow field exists even if it
2104  * happened to be zeros.
2105  */
2106 static const ovs_be32 *
2107 minimatch_get_prefix(const struct minimatch *match, const struct mf_field *mf)
2108 {
2109     return miniflow_get_be32_values(&match->flow) +
2110         count_1bits(match->flow.map & ((UINT64_C(1) << mf->flow_be32ofs) - 1));
2111 }
2112
2113 /* Insert rule in to the prefix tree.
2114  * 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2115  * in 'rule'. */
2116 static void
2117 trie_insert(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2118 {
2119     trie_insert_prefix(&trie->root,
2120                        minimatch_get_prefix(&rule->match, trie->field), mlen);
2121 }
2122
2123 static void
2124 trie_insert_prefix(rcu_trie_ptr *edge, const ovs_be32 *prefix, int mlen)
2125 {
2126     struct trie_node *node;
2127     int ofs = 0;
2128
2129     /* Walk the tree. */
2130     for (; (node = ovsrcu_get_protected(struct trie_node *, edge));
2131          edge = trie_next_edge(node, prefix, ofs)) {
2132         unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2133         ofs += eqbits;
2134         if (eqbits < node->n_bits) {
2135             /* Mismatch, new node needs to be inserted above. */
2136             int old_branch = get_bit_at(node->prefix, eqbits);
2137             struct trie_node *new_parent;
2138
2139             new_parent = trie_branch_create(prefix, ofs - eqbits, eqbits,
2140                                             ofs == mlen ? 1 : 0);
2141             /* Copy the node to modify it. */
2142             node = trie_node_rcu_realloc(node);
2143             /* Adjust the new node for its new position in the tree. */
2144             node->prefix <<= eqbits;
2145             node->n_bits -= eqbits;
2146             ovsrcu_set_hidden(&new_parent->edges[old_branch], node);
2147
2148             /* Check if need a new branch for the new rule. */
2149             if (ofs < mlen) {
2150                 ovsrcu_set_hidden(&new_parent->edges[!old_branch],
2151                                   trie_branch_create(prefix, ofs, mlen - ofs,
2152                                                      1));
2153             }
2154             ovsrcu_set(edge, new_parent); /* Publish changes. */
2155             return;
2156         }
2157         /* Full match so far. */
2158
2159         if (ofs == mlen) {
2160             /* Full match at the current node, rule needs to be added here. */
2161             node->n_rules++;
2162             return;
2163         }
2164     }
2165     /* Must insert a new tree branch for the new rule. */
2166     ovsrcu_set(edge, trie_branch_create(prefix, ofs, mlen - ofs, 1));
2167 }
2168
2169 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2170  * in 'rule'. */
2171 static void
2172 trie_remove(struct cls_trie *trie, const struct cls_rule *rule, int mlen)
2173 {
2174     trie_remove_prefix(&trie->root,
2175                        minimatch_get_prefix(&rule->match, trie->field), mlen);
2176 }
2177
2178 /* 'mlen' must be the (non-zero) CIDR prefix length of the 'trie->field' mask
2179  * in 'rule'. */
2180 static void
2181 trie_remove_prefix(rcu_trie_ptr *root, const ovs_be32 *prefix, int mlen)
2182 {
2183     struct trie_node *node;
2184     rcu_trie_ptr *edges[sizeof(union mf_value) * 8];
2185     int depth = 0, ofs = 0;
2186
2187     /* Walk the tree. */
2188     for (edges[0] = root;
2189          (node = ovsrcu_get_protected(struct trie_node *, edges[depth]));
2190          edges[++depth] = trie_next_edge(node, prefix, ofs)) {
2191         unsigned int eqbits = trie_prefix_equal_bits(node, prefix, ofs, mlen);
2192
2193         if (eqbits < node->n_bits) {
2194             /* Mismatch, nothing to be removed.  This should never happen, as
2195              * only rules in the classifier are ever removed. */
2196             break; /* Log a warning. */
2197         }
2198         /* Full match so far. */
2199         ofs += eqbits;
2200
2201         if (ofs == mlen) {
2202             /* Full prefix match at the current node, remove rule here. */
2203             if (!node->n_rules) {
2204                 break; /* Log a warning. */
2205             }
2206             node->n_rules--;
2207
2208             /* Check if can prune the tree. */
2209             while (!node->n_rules) {
2210                 struct trie_node *next,
2211                     *edge0 = ovsrcu_get_protected(struct trie_node *,
2212                                                   &node->edges[0]),
2213                     *edge1 = ovsrcu_get_protected(struct trie_node *,
2214                                                   &node->edges[1]);
2215
2216                 if (edge0 && edge1) {
2217                     break; /* A branching point, cannot prune. */
2218                 }
2219
2220                 /* Else have at most one child node, remove this node. */
2221                 next = edge0 ? edge0 : edge1;
2222
2223                 if (next) {
2224                     if (node->n_bits + next->n_bits > TRIE_PREFIX_BITS) {
2225                         break;   /* Cannot combine. */
2226                     }
2227                     next = trie_node_rcu_realloc(next); /* Modify. */
2228
2229                     /* Combine node with next. */
2230                     next->prefix = node->prefix | next->prefix >> node->n_bits;
2231                     next->n_bits += node->n_bits;
2232                 }
2233                 /* Update the parent's edge. */
2234                 ovsrcu_set(edges[depth], next); /* Publish changes. */
2235                 trie_node_destroy(node);
2236
2237                 if (next || !depth) {
2238                     /* Branch not pruned or at root, nothing more to do. */
2239                     break;
2240                 }
2241                 node = ovsrcu_get_protected(struct trie_node *,
2242                                             edges[--depth]);
2243             }
2244             return;
2245         }
2246     }
2247     /* Cannot go deeper. This should never happen, since only rules
2248      * that actually exist in the classifier are ever removed. */
2249     VLOG_WARN("Trying to remove non-existing rule from a prefix trie.");
2250 }