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