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