~ubuntu-branches/ubuntu/wily/openvswitch/wily

« back to all changes in this revision

Viewing changes to lib/classifier.c

  • Committer: Package Import Robot
  • Author(s): James Page
  • Date: 2015-08-10 11:35:15 UTC
  • mfrom: (1.1.30)
  • Revision ID: package-import@ubuntu.com-20150810113515-575vj06oq29emxsn
Tags: 2.4.0~git20150810.97bab95-0ubuntu1
* New upstream snapshot from 2.4 branch:
  - d/*: Align any relevant packaging changes with upstream.
* d/*: wrap-and-sort.
* d/openvswitch-{common,vswitch}.install: Correct install location for
  bash completion files.
* d/tests/openflow.py: Explicitly use ovs-testcontroller as provided
  by 2.4.0 release.

Show diffs side-by-side

added added

removed removed

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