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