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