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