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