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