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