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