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