test-classifier: Test versioning features.
[cascardo/ovs.git] / tests / test-classifier.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /* "White box" tests for classifier.
18  *
19  * With very few exceptions, these tests obtain complete coverage of every
20  * basic block and every branch in the classifier implementation, e.g. a clean
21  * report from "gcov -b".  (Covering the exceptions would require finding
22  * collisions in the hash function used for flow data, etc.)
23  *
24  * This test should receive a clean report from "valgrind --leak-check=full":
25  * it frees every heap block that it allocates.
26  */
27
28 #include <config.h>
29 #undef NDEBUG
30 #include "classifier.h"
31 #include <assert.h>
32 #include <errno.h>
33 #include <limits.h>
34 #include "byte-order.h"
35 #include "classifier-private.h"
36 #include "command-line.h"
37 #include "flow.h"
38 #include "ofp-util.h"
39 #include "ovstest.h"
40 #include "packets.h"
41 #include "random.h"
42 #include "unaligned.h"
43 #include "util.h"
44
45 static bool versioned = false;
46
47 /* Fields in a rule. */
48 #define CLS_FIELDS                        \
49     /*        struct flow    all-caps */  \
50     /*        member name    name     */  \
51     /*        -----------    -------- */  \
52     CLS_FIELD(tunnel.tun_id, TUN_ID)      \
53     CLS_FIELD(metadata,      METADATA)    \
54     CLS_FIELD(nw_src,        NW_SRC)      \
55     CLS_FIELD(nw_dst,        NW_DST)      \
56     CLS_FIELD(in_port,       IN_PORT)     \
57     CLS_FIELD(vlan_tci,      VLAN_TCI)    \
58     CLS_FIELD(dl_type,       DL_TYPE)     \
59     CLS_FIELD(tp_src,        TP_SRC)      \
60     CLS_FIELD(tp_dst,        TP_DST)      \
61     CLS_FIELD(dl_src,        DL_SRC)      \
62     CLS_FIELD(dl_dst,        DL_DST)      \
63     CLS_FIELD(nw_proto,      NW_PROTO)    \
64     CLS_FIELD(nw_tos,        NW_DSCP)
65
66 /* Field indexes.
67  *
68  * (These are also indexed into struct classifier's 'tables' array.) */
69 enum {
70 #define CLS_FIELD(MEMBER, NAME) CLS_F_IDX_##NAME,
71     CLS_FIELDS
72 #undef CLS_FIELD
73     CLS_N_FIELDS
74 };
75
76 /* Field information. */
77 struct cls_field {
78     int ofs;                    /* Offset in struct flow. */
79     int len;                    /* Length in bytes. */
80     const char *name;           /* Name (for debugging). */
81 };
82
83 static const struct cls_field cls_fields[CLS_N_FIELDS] = {
84 #define CLS_FIELD(MEMBER, NAME)                 \
85     { offsetof(struct flow, MEMBER),            \
86       sizeof ((struct flow *)0)->MEMBER,        \
87       #NAME },
88     CLS_FIELDS
89 #undef CLS_FIELD
90 };
91
92 struct test_rule {
93     struct ovs_list list_node;
94     int aux;                    /* Auxiliary data. */
95     struct cls_rule cls_rule;   /* Classifier rule data. */
96 };
97
98 static struct test_rule *
99 test_rule_from_cls_rule(const struct cls_rule *rule)
100 {
101     return rule ? CONTAINER_OF(rule, struct test_rule, cls_rule) : NULL;
102 }
103
104 static void
105 test_rule_destroy(struct test_rule *rule)
106 {
107     if (rule) {
108         cls_rule_destroy(&rule->cls_rule);
109         free(rule);
110     }
111 }
112
113 static struct test_rule *make_rule(int wc_fields, int priority, int value_pat,
114                                    long long version);
115 static void free_rule(struct test_rule *);
116 static struct test_rule *clone_rule(const struct test_rule *);
117
118 /* Trivial (linear) classifier. */
119 struct tcls {
120     size_t n_rules;
121     size_t allocated_rules;
122     struct test_rule **rules;
123 };
124
125 static void
126 tcls_init(struct tcls *tcls)
127 {
128     tcls->n_rules = 0;
129     tcls->allocated_rules = 0;
130     tcls->rules = NULL;
131 }
132
133 static void
134 tcls_destroy(struct tcls *tcls)
135 {
136     if (tcls) {
137         size_t i;
138
139         for (i = 0; i < tcls->n_rules; i++) {
140             test_rule_destroy(tcls->rules[i]);
141         }
142         free(tcls->rules);
143     }
144 }
145
146 static bool
147 tcls_is_empty(const struct tcls *tcls)
148 {
149     return tcls->n_rules == 0;
150 }
151
152 static struct test_rule *
153 tcls_insert(struct tcls *tcls, const struct test_rule *rule)
154 {
155     size_t i;
156
157     for (i = 0; i < tcls->n_rules; i++) {
158         const struct cls_rule *pos = &tcls->rules[i]->cls_rule;
159         if (cls_rule_equal(pos, &rule->cls_rule)) {
160             /* Exact match. */
161             ovsrcu_postpone(free_rule, tcls->rules[i]);
162             tcls->rules[i] = clone_rule(rule);
163             return tcls->rules[i];
164         } else if (pos->priority < rule->cls_rule.priority) {
165             break;
166         }
167     }
168
169     if (tcls->n_rules >= tcls->allocated_rules) {
170         tcls->rules = x2nrealloc(tcls->rules, &tcls->allocated_rules,
171                                  sizeof *tcls->rules);
172     }
173     if (i != tcls->n_rules) {
174         memmove(&tcls->rules[i + 1], &tcls->rules[i],
175                 sizeof *tcls->rules * (tcls->n_rules - i));
176     }
177     tcls->rules[i] = clone_rule(rule);
178     tcls->n_rules++;
179     return tcls->rules[i];
180 }
181
182 static void
183 tcls_remove(struct tcls *cls, const struct test_rule *rule)
184 {
185     size_t i;
186
187     for (i = 0; i < cls->n_rules; i++) {
188         struct test_rule *pos = cls->rules[i];
189         if (pos == rule) {
190             test_rule_destroy(pos);
191
192             memmove(&cls->rules[i], &cls->rules[i + 1],
193                     sizeof *cls->rules * (cls->n_rules - i - 1));
194
195             cls->n_rules--;
196             return;
197         }
198     }
199     OVS_NOT_REACHED();
200 }
201
202 static bool
203 match(const struct cls_rule *wild_, const struct flow *fixed)
204 {
205     struct match wild;
206     int f_idx;
207
208     minimatch_expand(&wild_->match, &wild);
209     for (f_idx = 0; f_idx < CLS_N_FIELDS; f_idx++) {
210         bool eq;
211
212         if (f_idx == CLS_F_IDX_NW_SRC) {
213             eq = !((fixed->nw_src ^ wild.flow.nw_src)
214                    & wild.wc.masks.nw_src);
215         } else if (f_idx == CLS_F_IDX_NW_DST) {
216             eq = !((fixed->nw_dst ^ wild.flow.nw_dst)
217                    & wild.wc.masks.nw_dst);
218         } else if (f_idx == CLS_F_IDX_TP_SRC) {
219             eq = !((fixed->tp_src ^ wild.flow.tp_src)
220                    & wild.wc.masks.tp_src);
221         } else if (f_idx == CLS_F_IDX_TP_DST) {
222             eq = !((fixed->tp_dst ^ wild.flow.tp_dst)
223                    & wild.wc.masks.tp_dst);
224         } else if (f_idx == CLS_F_IDX_DL_SRC) {
225             eq = eth_addr_equal_except(fixed->dl_src, wild.flow.dl_src,
226                                        wild.wc.masks.dl_src);
227         } else if (f_idx == CLS_F_IDX_DL_DST) {
228             eq = eth_addr_equal_except(fixed->dl_dst, wild.flow.dl_dst,
229                                        wild.wc.masks.dl_dst);
230         } else if (f_idx == CLS_F_IDX_VLAN_TCI) {
231             eq = !((fixed->vlan_tci ^ wild.flow.vlan_tci)
232                    & wild.wc.masks.vlan_tci);
233         } else if (f_idx == CLS_F_IDX_TUN_ID) {
234             eq = !((fixed->tunnel.tun_id ^ wild.flow.tunnel.tun_id)
235                    & wild.wc.masks.tunnel.tun_id);
236         } else if (f_idx == CLS_F_IDX_METADATA) {
237             eq = !((fixed->metadata ^ wild.flow.metadata)
238                    & wild.wc.masks.metadata);
239         } else if (f_idx == CLS_F_IDX_NW_DSCP) {
240             eq = !((fixed->nw_tos ^ wild.flow.nw_tos) &
241                    (wild.wc.masks.nw_tos & IP_DSCP_MASK));
242         } else if (f_idx == CLS_F_IDX_NW_PROTO) {
243             eq = !((fixed->nw_proto ^ wild.flow.nw_proto)
244                    & wild.wc.masks.nw_proto);
245         } else if (f_idx == CLS_F_IDX_DL_TYPE) {
246             eq = !((fixed->dl_type ^ wild.flow.dl_type)
247                    & wild.wc.masks.dl_type);
248         } else if (f_idx == CLS_F_IDX_IN_PORT) {
249             eq = !((fixed->in_port.ofp_port
250                     ^ wild.flow.in_port.ofp_port)
251                    & wild.wc.masks.in_port.ofp_port);
252         } else {
253             OVS_NOT_REACHED();
254         }
255
256         if (!eq) {
257             return false;
258         }
259     }
260     return true;
261 }
262
263 static struct cls_rule *
264 tcls_lookup(const struct tcls *cls, const struct flow *flow)
265 {
266     size_t i;
267
268     for (i = 0; i < cls->n_rules; i++) {
269         struct test_rule *pos = cls->rules[i];
270         if (match(&pos->cls_rule, flow)) {
271             return &pos->cls_rule;
272         }
273     }
274     return NULL;
275 }
276
277 static void
278 tcls_delete_matches(struct tcls *cls, const struct cls_rule *target)
279 {
280     size_t i;
281
282     for (i = 0; i < cls->n_rules; ) {
283         struct test_rule *pos = cls->rules[i];
284         if (!minimask_has_extra(&pos->cls_rule.match.mask,
285                                 &target->match.mask)) {
286             struct flow flow;
287
288             miniflow_expand(&pos->cls_rule.match.flow, &flow);
289             if (match(target, &flow)) {
290                 tcls_remove(cls, pos);
291                 continue;
292             }
293         }
294         i++;
295     }
296 }
297 \f
298 static ovs_be32 nw_src_values[] = { CONSTANT_HTONL(0xc0a80001),
299                                     CONSTANT_HTONL(0xc0a04455) };
300 static ovs_be32 nw_dst_values[] = { CONSTANT_HTONL(0xc0a80002),
301                                     CONSTANT_HTONL(0xc0a04455) };
302 static ovs_be64 tun_id_values[] = {
303     0,
304     CONSTANT_HTONLL(UINT64_C(0xfedcba9876543210)) };
305 static ovs_be64 metadata_values[] = {
306     0,
307     CONSTANT_HTONLL(UINT64_C(0xfedcba9876543210)) };
308 static ofp_port_t in_port_values[] = { OFP_PORT_C(1), OFPP_LOCAL };
309 static ovs_be16 vlan_tci_values[] = { CONSTANT_HTONS(101), CONSTANT_HTONS(0) };
310 static ovs_be16 dl_type_values[]
311             = { CONSTANT_HTONS(ETH_TYPE_IP), CONSTANT_HTONS(ETH_TYPE_ARP) };
312 static ovs_be16 tp_src_values[] = { CONSTANT_HTONS(49362),
313                                     CONSTANT_HTONS(80) };
314 static ovs_be16 tp_dst_values[] = { CONSTANT_HTONS(6667), CONSTANT_HTONS(22) };
315 static uint8_t dl_src_values[][ETH_ADDR_LEN] = {
316                                       { 0x00, 0x02, 0xe3, 0x0f, 0x80, 0xa4 },
317                                       { 0x5e, 0x33, 0x7f, 0x5f, 0x1e, 0x99 } };
318 static uint8_t dl_dst_values[][ETH_ADDR_LEN] = {
319                                       { 0x4a, 0x27, 0x71, 0xae, 0x64, 0xc1 },
320                                       { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } };
321 static uint8_t nw_proto_values[] = { IPPROTO_TCP, IPPROTO_ICMP };
322 static uint8_t nw_dscp_values[] = { 48, 0 };
323
324 static void *values[CLS_N_FIELDS][2];
325
326 static void
327 init_values(void)
328 {
329     values[CLS_F_IDX_TUN_ID][0] = &tun_id_values[0];
330     values[CLS_F_IDX_TUN_ID][1] = &tun_id_values[1];
331
332     values[CLS_F_IDX_METADATA][0] = &metadata_values[0];
333     values[CLS_F_IDX_METADATA][1] = &metadata_values[1];
334
335     values[CLS_F_IDX_IN_PORT][0] = &in_port_values[0];
336     values[CLS_F_IDX_IN_PORT][1] = &in_port_values[1];
337
338     values[CLS_F_IDX_VLAN_TCI][0] = &vlan_tci_values[0];
339     values[CLS_F_IDX_VLAN_TCI][1] = &vlan_tci_values[1];
340
341     values[CLS_F_IDX_DL_SRC][0] = dl_src_values[0];
342     values[CLS_F_IDX_DL_SRC][1] = dl_src_values[1];
343
344     values[CLS_F_IDX_DL_DST][0] = dl_dst_values[0];
345     values[CLS_F_IDX_DL_DST][1] = dl_dst_values[1];
346
347     values[CLS_F_IDX_DL_TYPE][0] = &dl_type_values[0];
348     values[CLS_F_IDX_DL_TYPE][1] = &dl_type_values[1];
349
350     values[CLS_F_IDX_NW_SRC][0] = &nw_src_values[0];
351     values[CLS_F_IDX_NW_SRC][1] = &nw_src_values[1];
352
353     values[CLS_F_IDX_NW_DST][0] = &nw_dst_values[0];
354     values[CLS_F_IDX_NW_DST][1] = &nw_dst_values[1];
355
356     values[CLS_F_IDX_NW_PROTO][0] = &nw_proto_values[0];
357     values[CLS_F_IDX_NW_PROTO][1] = &nw_proto_values[1];
358
359     values[CLS_F_IDX_NW_DSCP][0] = &nw_dscp_values[0];
360     values[CLS_F_IDX_NW_DSCP][1] = &nw_dscp_values[1];
361
362     values[CLS_F_IDX_TP_SRC][0] = &tp_src_values[0];
363     values[CLS_F_IDX_TP_SRC][1] = &tp_src_values[1];
364
365     values[CLS_F_IDX_TP_DST][0] = &tp_dst_values[0];
366     values[CLS_F_IDX_TP_DST][1] = &tp_dst_values[1];
367 }
368
369 #define N_NW_SRC_VALUES ARRAY_SIZE(nw_src_values)
370 #define N_NW_DST_VALUES ARRAY_SIZE(nw_dst_values)
371 #define N_TUN_ID_VALUES ARRAY_SIZE(tun_id_values)
372 #define N_METADATA_VALUES ARRAY_SIZE(metadata_values)
373 #define N_IN_PORT_VALUES ARRAY_SIZE(in_port_values)
374 #define N_VLAN_TCI_VALUES ARRAY_SIZE(vlan_tci_values)
375 #define N_DL_TYPE_VALUES ARRAY_SIZE(dl_type_values)
376 #define N_TP_SRC_VALUES ARRAY_SIZE(tp_src_values)
377 #define N_TP_DST_VALUES ARRAY_SIZE(tp_dst_values)
378 #define N_DL_SRC_VALUES ARRAY_SIZE(dl_src_values)
379 #define N_DL_DST_VALUES ARRAY_SIZE(dl_dst_values)
380 #define N_NW_PROTO_VALUES ARRAY_SIZE(nw_proto_values)
381 #define N_NW_DSCP_VALUES ARRAY_SIZE(nw_dscp_values)
382
383 #define N_FLOW_VALUES (N_NW_SRC_VALUES *        \
384                        N_NW_DST_VALUES *        \
385                        N_TUN_ID_VALUES *        \
386                        N_IN_PORT_VALUES *       \
387                        N_VLAN_TCI_VALUES *       \
388                        N_DL_TYPE_VALUES *       \
389                        N_TP_SRC_VALUES *        \
390                        N_TP_DST_VALUES *        \
391                        N_DL_SRC_VALUES *        \
392                        N_DL_DST_VALUES *        \
393                        N_NW_PROTO_VALUES *      \
394                        N_NW_DSCP_VALUES)
395
396 static unsigned int
397 get_value(unsigned int *x, unsigned n_values)
398 {
399     unsigned int rem = *x % n_values;
400     *x /= n_values;
401     return rem;
402 }
403
404 static void
405 compare_classifiers(struct classifier *cls, size_t n_invisible_rules,
406                     long long version, struct tcls *tcls)
407 {
408     static const int confidence = 500;
409     unsigned int i;
410
411     assert(classifier_count(cls) == tcls->n_rules + n_invisible_rules);
412     for (i = 0; i < confidence; i++) {
413         const struct cls_rule *cr0, *cr1, *cr2;
414         struct flow flow;
415         struct flow_wildcards wc;
416         unsigned int x;
417
418         flow_wildcards_init_catchall(&wc);
419         x = random_range(N_FLOW_VALUES);
420         memset(&flow, 0, sizeof flow);
421         flow.nw_src = nw_src_values[get_value(&x, N_NW_SRC_VALUES)];
422         flow.nw_dst = nw_dst_values[get_value(&x, N_NW_DST_VALUES)];
423         flow.tunnel.tun_id = tun_id_values[get_value(&x, N_TUN_ID_VALUES)];
424         flow.metadata = metadata_values[get_value(&x, N_METADATA_VALUES)];
425         flow.in_port.ofp_port = in_port_values[get_value(&x,
426                                                    N_IN_PORT_VALUES)];
427         flow.vlan_tci = vlan_tci_values[get_value(&x, N_VLAN_TCI_VALUES)];
428         flow.dl_type = dl_type_values[get_value(&x, N_DL_TYPE_VALUES)];
429         flow.tp_src = tp_src_values[get_value(&x, N_TP_SRC_VALUES)];
430         flow.tp_dst = tp_dst_values[get_value(&x, N_TP_DST_VALUES)];
431         memcpy(flow.dl_src, dl_src_values[get_value(&x, N_DL_SRC_VALUES)],
432                ETH_ADDR_LEN);
433         memcpy(flow.dl_dst, dl_dst_values[get_value(&x, N_DL_DST_VALUES)],
434                ETH_ADDR_LEN);
435         flow.nw_proto = nw_proto_values[get_value(&x, N_NW_PROTO_VALUES)];
436         flow.nw_tos = nw_dscp_values[get_value(&x, N_NW_DSCP_VALUES)];
437
438         /* This assertion is here to suppress a GCC 4.9 array-bounds warning */
439         ovs_assert(cls->n_tries <= CLS_MAX_TRIES);
440
441         cr0 = classifier_lookup(cls, version, &flow, &wc);
442         cr1 = tcls_lookup(tcls, &flow);
443         assert((cr0 == NULL) == (cr1 == NULL));
444         if (cr0 != NULL) {
445             const struct test_rule *tr0 = test_rule_from_cls_rule(cr0);
446             const struct test_rule *tr1 = test_rule_from_cls_rule(cr1);
447
448             assert(cls_rule_equal(cr0, cr1));
449             assert(tr0->aux == tr1->aux);
450
451             /* Make sure the rule should have been visible. */
452             assert(cr0->cls_match);
453             assert(cls_match_visible_in_version(cr0->cls_match, version));
454         }
455         cr2 = classifier_lookup(cls, version, &flow, NULL);
456         assert(cr2 == cr0);
457     }
458 }
459
460 static void
461 destroy_classifier(struct classifier *cls)
462 {
463     struct test_rule *rule;
464
465     classifier_defer(cls);
466     CLS_FOR_EACH (rule, cls_rule, cls) {
467         if (classifier_remove(cls, &rule->cls_rule)) {
468             ovsrcu_postpone(free_rule, rule);
469         }
470     }
471     classifier_destroy(cls);
472 }
473
474 static void
475 pvector_verify(const struct pvector *pvec)
476 {
477     void *ptr OVS_UNUSED;
478     int prev_priority = INT_MAX;
479
480     PVECTOR_FOR_EACH (ptr, pvec) {
481         int priority = cursor__.vector[cursor__.entry_idx].priority;
482         if (priority > prev_priority) {
483             ovs_abort(0, "Priority vector is out of order (%u > %u)",
484                       priority, prev_priority);
485         }
486         prev_priority = priority;
487     }
488 }
489
490 static unsigned int
491 trie_verify(const rcu_trie_ptr *trie, unsigned int ofs, unsigned int n_bits)
492 {
493     const struct trie_node *node = ovsrcu_get(struct trie_node *, trie);
494
495     if (node) {
496         assert(node->n_rules == 0 || node->n_bits > 0);
497         ofs += node->n_bits;
498         assert((ofs > 0 || (ofs == 0 && node->n_bits == 0)) && ofs <= n_bits);
499
500         return node->n_rules
501             + trie_verify(&node->edges[0], ofs, n_bits)
502             + trie_verify(&node->edges[1], ofs, n_bits);
503     }
504     return 0;
505 }
506
507 static void
508 verify_tries(struct classifier *cls)
509     OVS_NO_THREAD_SAFETY_ANALYSIS
510 {
511     unsigned int n_rules = 0;
512     int i;
513
514     for (i = 0; i < cls->n_tries; i++) {
515         n_rules += trie_verify(&cls->tries[i].root, 0,
516                                cls->tries[i].field->n_bits);
517     }
518     assert(n_rules <= cls->n_rules);
519 }
520
521 static void
522 check_tables(const struct classifier *cls, int n_tables, int n_rules,
523              int n_dups, int n_invisible, long long version)
524     OVS_NO_THREAD_SAFETY_ANALYSIS
525 {
526     const struct cls_subtable *table;
527     struct test_rule *test_rule;
528     int found_tables = 0;
529     int found_tables_with_visible_rules = 0;
530     int found_rules = 0;
531     int found_dups = 0;
532     int found_invisible = 0;
533     int found_visible_but_removable = 0;
534     int found_rules2 = 0;
535
536     pvector_verify(&cls->subtables);
537     CMAP_FOR_EACH (table, cmap_node, &cls->subtables_map) {
538         const struct cls_match *head;
539         int max_priority = INT_MIN;
540         unsigned int max_count = 0;
541         bool found = false;
542         bool found_visible_rules = false;
543         const struct cls_subtable *iter;
544
545         /* Locate the subtable from 'subtables'. */
546         PVECTOR_FOR_EACH (iter, &cls->subtables) {
547             if (iter == table) {
548                 if (found) {
549                     ovs_abort(0, "Subtable %p duplicated in 'subtables'.",
550                               table);
551                 }
552                 found = true;
553             }
554         }
555         if (!found) {
556             ovs_abort(0, "Subtable %p not found from 'subtables'.", table);
557         }
558
559         assert(!cmap_is_empty(&table->rules));
560         assert(trie_verify(&table->ports_trie, 0, table->ports_mask_len)
561                == (table->ports_mask_len ? cmap_count(&table->rules) : 0));
562
563         found_tables++;
564
565         CMAP_FOR_EACH (head, cmap_node, &table->rules) {
566             int prev_priority = INT_MAX;
567             long long prev_version = 0;
568             const struct cls_match *rule, *prev;
569             bool found_visible_rules_in_list = false;
570
571             assert(head->priority <= table->max_priority);
572
573             if (head->priority > max_priority) {
574                 max_priority = head->priority;
575                 max_count = 0;
576             }
577
578             FOR_EACH_RULE_IN_LIST_PROTECTED(rule, prev, head) {
579                 long long rule_version;
580                 const struct cls_rule *found_rule;
581
582                 /* Priority may not increase. */
583                 assert(rule->priority <= prev_priority);
584
585                 if (rule->priority == max_priority) {
586                     ++max_count;
587                 }
588
589                 /* Count invisible rules and visible duplicates. */
590                 if (!cls_match_visible_in_version(rule, version)) {
591                     found_invisible++;
592                 } else {
593                     if (cls_match_is_eventually_invisible(rule)) {
594                         found_visible_but_removable++;
595                     }
596                     if (found_visible_rules_in_list) {
597                         found_dups++;
598                     }
599                     found_visible_rules_in_list = true;
600                     found_visible_rules = true;
601                 }
602
603                 /* Rule must be visible in the version it was inserted. */
604                 rule_version = rule->cls_rule->version;
605                 assert(cls_match_visible_in_version(rule, rule_version));
606
607                 /* We should always find the latest version of the rule,
608                  * unless all rules have been marked for removal.
609                  * Later versions must always be later in the list. */
610                 found_rule = classifier_find_rule_exactly(cls, rule->cls_rule);
611                 if (found_rule && found_rule != rule->cls_rule) {
612
613                     assert(found_rule->priority == rule->priority);
614
615                     /* Found rule may not have a lower version. */
616                     assert(found_rule->version >= rule_version);
617
618                     /* This rule must not be visible in the found rule's
619                      * version. */
620                     assert(!cls_match_visible_in_version(rule,
621                                                          found_rule->version));
622                 }
623
624                 if (rule->priority == prev_priority) {
625                     /* Exact duplicate rule may not have a lower version. */
626                     assert(rule_version >= prev_version);
627
628                     /* Previous rule must not be visible in rule's version. */
629                     assert(!cls_match_visible_in_version(prev, rule_version));
630                 }
631
632                 prev_priority = rule->priority;
633                 prev_version = rule_version;
634                 found_rules++;
635             }
636         }
637
638         if (found_visible_rules) {
639             found_tables_with_visible_rules++;
640         }
641
642         assert(table->max_priority == max_priority);
643         assert(table->max_count == max_count);
644     }
645
646     assert(found_tables == cmap_count(&cls->subtables_map));
647     assert(found_tables == pvector_count(&cls->subtables));
648     assert(n_tables == -1 || n_tables == found_tables_with_visible_rules);
649     assert(n_rules == -1 || found_rules == n_rules + found_invisible);
650     assert(n_dups == -1 || found_dups == n_dups);
651     assert(found_invisible == n_invisible);
652
653     CLS_FOR_EACH (test_rule, cls_rule, cls) {
654         found_rules2++;
655     }
656     /* Iteration does not see removable rules. */
657     assert(found_rules
658            == found_rules2 + found_visible_but_removable + found_invisible);
659 }
660
661 static struct test_rule *
662 make_rule(int wc_fields, int priority, int value_pat, long long version)
663 {
664     const struct cls_field *f;
665     struct test_rule *rule;
666     struct match match;
667
668     match_init_catchall(&match);
669     for (f = &cls_fields[0]; f < &cls_fields[CLS_N_FIELDS]; f++) {
670         int f_idx = f - cls_fields;
671         int value_idx = (value_pat & (1u << f_idx)) != 0;
672         memcpy((char *) &match.flow + f->ofs,
673                values[f_idx][value_idx], f->len);
674
675         if (f_idx == CLS_F_IDX_NW_SRC) {
676             match.wc.masks.nw_src = OVS_BE32_MAX;
677         } else if (f_idx == CLS_F_IDX_NW_DST) {
678             match.wc.masks.nw_dst = OVS_BE32_MAX;
679         } else if (f_idx == CLS_F_IDX_TP_SRC) {
680             match.wc.masks.tp_src = OVS_BE16_MAX;
681         } else if (f_idx == CLS_F_IDX_TP_DST) {
682             match.wc.masks.tp_dst = OVS_BE16_MAX;
683         } else if (f_idx == CLS_F_IDX_DL_SRC) {
684             memset(match.wc.masks.dl_src, 0xff, ETH_ADDR_LEN);
685         } else if (f_idx == CLS_F_IDX_DL_DST) {
686             memset(match.wc.masks.dl_dst, 0xff, ETH_ADDR_LEN);
687         } else if (f_idx == CLS_F_IDX_VLAN_TCI) {
688             match.wc.masks.vlan_tci = OVS_BE16_MAX;
689         } else if (f_idx == CLS_F_IDX_TUN_ID) {
690             match.wc.masks.tunnel.tun_id = OVS_BE64_MAX;
691         } else if (f_idx == CLS_F_IDX_METADATA) {
692             match.wc.masks.metadata = OVS_BE64_MAX;
693         } else if (f_idx == CLS_F_IDX_NW_DSCP) {
694             match.wc.masks.nw_tos |= IP_DSCP_MASK;
695         } else if (f_idx == CLS_F_IDX_NW_PROTO) {
696             match.wc.masks.nw_proto = UINT8_MAX;
697         } else if (f_idx == CLS_F_IDX_DL_TYPE) {
698             match.wc.masks.dl_type = OVS_BE16_MAX;
699         } else if (f_idx == CLS_F_IDX_IN_PORT) {
700             match.wc.masks.in_port.ofp_port = u16_to_ofp(UINT16_MAX);
701         } else {
702             OVS_NOT_REACHED();
703         }
704     }
705
706     rule = xzalloc(sizeof *rule);
707     cls_rule_init(&rule->cls_rule, &match, wc_fields
708                   ? (priority == INT_MIN ? priority + 1 :
709                      priority == INT_MAX ? priority - 1 : priority)
710                   : 0, version);
711     return rule;
712 }
713
714 static struct test_rule *
715 clone_rule(const struct test_rule *src)
716 {
717     struct test_rule *dst;
718
719     dst = xmalloc(sizeof *dst);
720     dst->aux = src->aux;
721     cls_rule_clone(&dst->cls_rule, &src->cls_rule);
722     return dst;
723 }
724
725 static void
726 free_rule(struct test_rule *rule)
727 {
728     cls_rule_destroy(&rule->cls_rule);
729     free(rule);
730 }
731
732 static void
733 shuffle(int *p, size_t n)
734 {
735     for (; n > 1; n--, p++) {
736         int *q = &p[random_range(n)];
737         int tmp = *p;
738         *p = *q;
739         *q = tmp;
740     }
741 }
742
743 static void
744 shuffle_u32s(uint32_t *p, size_t n)
745 {
746     for (; n > 1; n--, p++) {
747         uint32_t *q = &p[random_range(n)];
748         uint32_t tmp = *p;
749         *p = *q;
750         *q = tmp;
751     }
752 }
753 \f
754 /* Classifier tests. */
755
756 static enum mf_field_id trie_fields[2] = {
757     MFF_IPV4_DST, MFF_IPV4_SRC
758 };
759
760 static void
761 set_prefix_fields(struct classifier *cls)
762 {
763     verify_tries(cls);
764     classifier_set_prefix_fields(cls, trie_fields, ARRAY_SIZE(trie_fields));
765     verify_tries(cls);
766 }
767
768 /* Tests an empty classifier. */
769 static void
770 test_empty(struct ovs_cmdl_context *ctx OVS_UNUSED)
771 {
772     struct classifier cls;
773     struct tcls tcls;
774
775     classifier_init(&cls, flow_segment_u64s);
776     set_prefix_fields(&cls);
777     tcls_init(&tcls);
778     assert(classifier_is_empty(&cls));
779     assert(tcls_is_empty(&tcls));
780     compare_classifiers(&cls, 0, CLS_MIN_VERSION, &tcls);
781     classifier_destroy(&cls);
782     tcls_destroy(&tcls);
783 }
784
785 /* Destroys a null classifier. */
786 static void
787 test_destroy_null(struct ovs_cmdl_context *ctx OVS_UNUSED)
788 {
789     classifier_destroy(NULL);
790 }
791
792 /* Tests classification with one rule at a time. */
793 static void
794 test_single_rule(struct ovs_cmdl_context *ctx OVS_UNUSED)
795 {
796     unsigned int wc_fields;     /* Hilarious. */
797
798     for (wc_fields = 0; wc_fields < (1u << CLS_N_FIELDS); wc_fields++) {
799         struct classifier cls;
800         struct test_rule *rule, *tcls_rule;
801         struct tcls tcls;
802
803         rule = make_rule(wc_fields,
804                          hash_bytes(&wc_fields, sizeof wc_fields, 0), 0,
805                          CLS_MIN_VERSION);
806         classifier_init(&cls, flow_segment_u64s);
807         set_prefix_fields(&cls);
808         tcls_init(&tcls);
809         tcls_rule = tcls_insert(&tcls, rule);
810
811         classifier_insert(&cls, &rule->cls_rule, NULL, 0);
812         compare_classifiers(&cls, 0, CLS_MIN_VERSION, &tcls);
813         check_tables(&cls, 1, 1, 0, 0, CLS_MIN_VERSION);
814
815         classifier_remove(&cls, &rule->cls_rule);
816         tcls_remove(&tcls, tcls_rule);
817         assert(classifier_is_empty(&cls));
818         assert(tcls_is_empty(&tcls));
819         compare_classifiers(&cls, 0, CLS_MIN_VERSION, &tcls);
820
821         ovsrcu_postpone(free_rule, rule);
822         classifier_destroy(&cls);
823         tcls_destroy(&tcls);
824     }
825 }
826
827 /* Tests replacing one rule by another. */
828 static void
829 test_rule_replacement(struct ovs_cmdl_context *ctx OVS_UNUSED)
830 {
831     unsigned int wc_fields;
832
833     for (wc_fields = 0; wc_fields < (1u << CLS_N_FIELDS); wc_fields++) {
834         struct classifier cls;
835         struct test_rule *rule1;
836         struct test_rule *rule2;
837         struct tcls tcls;
838
839         rule1 = make_rule(wc_fields, OFP_DEFAULT_PRIORITY, UINT_MAX,
840                           CLS_MIN_VERSION);
841         rule2 = make_rule(wc_fields, OFP_DEFAULT_PRIORITY, UINT_MAX,
842                           CLS_MIN_VERSION);
843         rule2->aux += 5;
844         rule2->aux += 5;
845
846         classifier_init(&cls, flow_segment_u64s);
847         set_prefix_fields(&cls);
848         tcls_init(&tcls);
849         tcls_insert(&tcls, rule1);
850         classifier_insert(&cls, &rule1->cls_rule, NULL, 0);
851         compare_classifiers(&cls, 0, CLS_MIN_VERSION, &tcls);
852         check_tables(&cls, 1, 1, 0, 0, CLS_MIN_VERSION);
853         tcls_destroy(&tcls);
854
855         tcls_init(&tcls);
856         tcls_insert(&tcls, rule2);
857
858         assert(test_rule_from_cls_rule(
859                    classifier_replace(&cls, &rule2->cls_rule,
860                                       NULL, 0)) == rule1);
861         ovsrcu_postpone(free_rule, rule1);
862         compare_classifiers(&cls, 0, CLS_MIN_VERSION, &tcls);
863         check_tables(&cls, 1, 1, 0, 0, CLS_MIN_VERSION);
864         classifier_defer(&cls);
865         classifier_remove(&cls, &rule2->cls_rule);
866
867         tcls_destroy(&tcls);
868         destroy_classifier(&cls);
869     }
870 }
871
872 static int
873 factorial(int n_items)
874 {
875     int n, i;
876
877     n = 1;
878     for (i = 2; i <= n_items; i++) {
879         n *= i;
880     }
881     return n;
882 }
883
884 static void
885 swap(int *a, int *b)
886 {
887     int tmp = *a;
888     *a = *b;
889     *b = tmp;
890 }
891
892 static void
893 reverse(int *a, int n)
894 {
895     int i;
896
897     for (i = 0; i < n / 2; i++) {
898         int j = n - (i + 1);
899         swap(&a[i], &a[j]);
900     }
901 }
902
903 static bool
904 next_permutation(int *a, int n)
905 {
906     int k;
907
908     for (k = n - 2; k >= 0; k--) {
909         if (a[k] < a[k + 1]) {
910             int l;
911
912             for (l = n - 1; ; l--) {
913                 if (a[l] > a[k]) {
914                     swap(&a[k], &a[l]);
915                     reverse(a + (k + 1), n - (k + 1));
916                     return true;
917                 }
918             }
919         }
920     }
921     return false;
922 }
923
924 /* Tests classification with rules that have the same matching criteria. */
925 static void
926 test_many_rules_in_one_list (struct ovs_cmdl_context *ctx OVS_UNUSED)
927 {
928     enum { N_RULES = 3 };
929     int n_pris;
930
931     for (n_pris = N_RULES; n_pris >= 1; n_pris--) {
932         int ops[N_RULES * 2];
933         int pris[N_RULES];
934         int n_permutations;
935         int i;
936
937         pris[0] = 0;
938         for (i = 1; i < N_RULES; i++) {
939             pris[i] = pris[i - 1] + (n_pris > i);
940         }
941
942         for (i = 0; i < N_RULES * 2; i++) {
943             ops[i] = i / 2;
944         }
945
946         n_permutations = 0;
947         do {
948             struct test_rule *rules[N_RULES];
949             struct test_rule *tcls_rules[N_RULES];
950             int pri_rules[N_RULES];
951             struct classifier cls;
952             struct tcls tcls;
953             long long version = CLS_MIN_VERSION;
954             size_t n_invisible_rules = 0;
955
956             n_permutations++;
957
958             for (i = 0; i < N_RULES; i++) {
959                 rules[i] = make_rule(456, pris[i], 0, version);
960                 tcls_rules[i] = NULL;
961                 pri_rules[i] = -1;
962             }
963
964             classifier_init(&cls, flow_segment_u64s);
965             set_prefix_fields(&cls);
966             tcls_init(&tcls);
967
968             for (i = 0; i < ARRAY_SIZE(ops); i++) {
969                 struct test_rule *displaced_rule = NULL;
970                 struct cls_rule *removable_rule = NULL;
971                 int j = ops[i];
972                 int m, n;
973
974                 if (!tcls_rules[j]) {
975                     tcls_rules[j] = tcls_insert(&tcls, rules[j]);
976                     if (versioned) {
977                         /* Insert the new rule in the next version. */
978                         *CONST_CAST(long long *, &rules[j]->cls_rule.version)
979                             = ++version;
980
981                         displaced_rule = test_rule_from_cls_rule(
982                             classifier_find_rule_exactly(&cls,
983                                                          &rules[j]->cls_rule));
984                         if (displaced_rule) {
985                             /* Mark the old rule for removal after the current
986                              * version. */
987                             cls_rule_make_invisible_in_version(
988                                 &displaced_rule->cls_rule, version,
989                                 version - 1);
990                             n_invisible_rules++;
991                             removable_rule = &displaced_rule->cls_rule;
992                         }
993                         classifier_insert(&cls, &rules[j]->cls_rule, NULL, 0);
994                     } else {
995                         displaced_rule = test_rule_from_cls_rule(
996                             classifier_replace(&cls, &rules[j]->cls_rule,
997                                                NULL, 0));
998                     }
999                     if (pri_rules[pris[j]] >= 0) {
1000                         int k = pri_rules[pris[j]];
1001                         assert(displaced_rule != NULL);
1002                         assert(displaced_rule != rules[j]);
1003                         assert(pris[j] == displaced_rule->cls_rule.priority);
1004                         tcls_rules[k] = NULL;
1005                     } else {
1006                         assert(displaced_rule == NULL);
1007                     }
1008                     pri_rules[pris[j]] = j;
1009                 } else {
1010                     if (versioned) {
1011                         /* Mark the rule for removal after the current
1012                          * version. */
1013                         cls_rule_make_invisible_in_version(
1014                             &rules[j]->cls_rule, version + 1, version);
1015                         ++version;
1016                         n_invisible_rules++;
1017                         removable_rule = &rules[j]->cls_rule;
1018                     } else {
1019                         classifier_remove(&cls, &rules[j]->cls_rule);
1020                     }
1021                     tcls_remove(&tcls, tcls_rules[j]);
1022                     tcls_rules[j] = NULL;
1023                     pri_rules[pris[j]] = -1;
1024                 }
1025                 compare_classifiers(&cls, n_invisible_rules, version, &tcls);
1026                 n = 0;
1027                 for (m = 0; m < N_RULES; m++) {
1028                     n += tcls_rules[m] != NULL;
1029                 }
1030                 check_tables(&cls, n > 0, n, n - 1, n_invisible_rules,
1031                              version);
1032
1033                 if (versioned && removable_rule) {
1034                     /* Removable rule is no longer visible. */
1035                     assert(removable_rule->cls_match);
1036                     assert(!cls_match_visible_in_version(
1037                                removable_rule->cls_match, version));
1038                     classifier_remove(&cls, removable_rule);
1039                     n_invisible_rules--;
1040                 }
1041             }
1042
1043             classifier_defer(&cls);
1044             for (i = 0; i < N_RULES; i++) {
1045                 if (classifier_remove(&cls, &rules[i]->cls_rule)) {
1046                     ovsrcu_postpone(free_rule, rules[i]);
1047                 }
1048             }
1049             classifier_destroy(&cls);
1050             tcls_destroy(&tcls);
1051         } while (next_permutation(ops, ARRAY_SIZE(ops)));
1052         assert(n_permutations == (factorial(N_RULES * 2) >> N_RULES));
1053     }
1054 }
1055
1056 static int
1057 count_ones(unsigned long int x)
1058 {
1059     int n = 0;
1060
1061     while (x) {
1062         x = zero_rightmost_1bit(x);
1063         n++;
1064     }
1065
1066     return n;
1067 }
1068
1069 static bool
1070 array_contains(int *array, int n, int value)
1071 {
1072     int i;
1073
1074     for (i = 0; i < n; i++) {
1075         if (array[i] == value) {
1076             return true;
1077         }
1078     }
1079
1080     return false;
1081 }
1082
1083 /* Tests classification with two rules at a time that fall into the same
1084  * table but different lists. */
1085 static void
1086 test_many_rules_in_one_table(struct ovs_cmdl_context *ctx OVS_UNUSED)
1087 {
1088     int iteration;
1089
1090     for (iteration = 0; iteration < 50; iteration++) {
1091         enum { N_RULES = 20 };
1092         struct test_rule *rules[N_RULES];
1093         struct test_rule *tcls_rules[N_RULES];
1094         struct classifier cls;
1095         struct tcls tcls;
1096         long long version = CLS_MIN_VERSION;
1097         size_t n_invisible_rules = 0;
1098         int value_pats[N_RULES];
1099         int value_mask;
1100         int wcf;
1101         int i;
1102
1103         do {
1104             wcf = random_uint32() & ((1u << CLS_N_FIELDS) - 1);
1105             value_mask = ~wcf & ((1u << CLS_N_FIELDS) - 1);
1106         } while ((1 << count_ones(value_mask)) < N_RULES);
1107
1108         classifier_init(&cls, flow_segment_u64s);
1109         set_prefix_fields(&cls);
1110         tcls_init(&tcls);
1111
1112         for (i = 0; i < N_RULES; i++) {
1113             int priority = random_range(INT_MAX);
1114
1115             do {
1116                 value_pats[i] = random_uint32() & value_mask;
1117             } while (array_contains(value_pats, i, value_pats[i]));
1118
1119             ++version;
1120             rules[i] = make_rule(wcf, priority, value_pats[i], version);
1121             tcls_rules[i] = tcls_insert(&tcls, rules[i]);
1122
1123             classifier_insert(&cls, &rules[i]->cls_rule, NULL, 0);
1124             compare_classifiers(&cls, n_invisible_rules, version, &tcls);
1125
1126             check_tables(&cls, 1, i + 1, 0, n_invisible_rules, version);
1127         }
1128
1129         for (i = 0; i < N_RULES; i++) {
1130             tcls_remove(&tcls, tcls_rules[i]);
1131             if (versioned) {
1132                 /* Mark the rule for removal after the current version. */
1133                 cls_rule_make_invisible_in_version(&rules[i]->cls_rule,
1134                                                    version + 1, version);
1135                 ++version;
1136                 n_invisible_rules++;
1137             } else {
1138                 classifier_remove(&cls, &rules[i]->cls_rule);
1139             }
1140             compare_classifiers(&cls, n_invisible_rules, version, &tcls);
1141             check_tables(&cls, i < N_RULES - 1, N_RULES - (i + 1), 0,
1142                          n_invisible_rules, version);
1143             if (!versioned) {
1144                 ovsrcu_postpone(free_rule, rules[i]);
1145             }
1146         }
1147
1148         if (versioned) {
1149             for (i = 0; i < N_RULES; i++) {
1150                 classifier_remove(&cls, &rules[i]->cls_rule);
1151                 n_invisible_rules--;
1152
1153                 compare_classifiers(&cls, n_invisible_rules, version, &tcls);
1154                 check_tables(&cls, 0, 0, 0, n_invisible_rules, version);
1155                 ovsrcu_postpone(free_rule, rules[i]);
1156             }
1157         }
1158
1159         classifier_destroy(&cls);
1160         tcls_destroy(&tcls);
1161     }
1162 }
1163
1164 /* Tests classification with many rules at a time that fall into random lists
1165  * in 'n' tables. */
1166 static void
1167 test_many_rules_in_n_tables(int n_tables)
1168 {
1169     enum { MAX_RULES = 50 };
1170     int wcfs[10];
1171     int iteration;
1172     int i;
1173
1174     assert(n_tables < 10);
1175     for (i = 0; i < n_tables; i++) {
1176         do {
1177             wcfs[i] = random_uint32() & ((1u << CLS_N_FIELDS) - 1);
1178         } while (array_contains(wcfs, i, wcfs[i]));
1179     }
1180
1181     for (iteration = 0; iteration < 30; iteration++) {
1182         int priorities[MAX_RULES];
1183         struct classifier cls;
1184         struct tcls tcls;
1185         long long version = CLS_MIN_VERSION;
1186         size_t n_invisible_rules = 0;
1187         struct ovs_list list = OVS_LIST_INITIALIZER(&list);
1188
1189         random_set_seed(iteration + 1);
1190         for (i = 0; i < MAX_RULES; i++) {
1191             priorities[i] = (i * 129) & INT_MAX;
1192         }
1193         shuffle(priorities, ARRAY_SIZE(priorities));
1194
1195         classifier_init(&cls, flow_segment_u64s);
1196         set_prefix_fields(&cls);
1197         tcls_init(&tcls);
1198
1199         for (i = 0; i < MAX_RULES; i++) {
1200             struct test_rule *rule;
1201             int priority = priorities[i];
1202             int wcf = wcfs[random_range(n_tables)];
1203             int value_pat = random_uint32() & ((1u << CLS_N_FIELDS) - 1);
1204             rule = make_rule(wcf, priority, value_pat, version);
1205             tcls_insert(&tcls, rule);
1206             classifier_insert(&cls, &rule->cls_rule, NULL, 0);
1207             compare_classifiers(&cls, n_invisible_rules, version, &tcls);
1208             check_tables(&cls, -1, i + 1, -1, n_invisible_rules, version);
1209         }
1210
1211         while (classifier_count(&cls) - n_invisible_rules > 0) {
1212             struct test_rule *target;
1213             struct test_rule *rule;
1214             size_t n_removable_rules = 0;
1215
1216             target = clone_rule(tcls.rules[random_range(tcls.n_rules)]);
1217
1218             CLS_FOR_EACH_TARGET (rule, cls_rule, &cls, &target->cls_rule) {
1219                 if (versioned) {
1220                     /* Mark the rule for removal after the current version. */
1221                     cls_rule_make_invisible_in_version(&rule->cls_rule,
1222                                                        version + 1, version);
1223                     n_removable_rules++;
1224                     compare_classifiers(&cls, n_invisible_rules, version,
1225                                         &tcls);
1226                     check_tables(&cls, -1, -1, -1, n_invisible_rules, version);
1227
1228                     list_push_back(&list, &rule->list_node);
1229                 } else if (classifier_remove(&cls, &rule->cls_rule)) {
1230                     ovsrcu_postpone(free_rule, rule);
1231                 }
1232             }
1233
1234             ++version;
1235             n_invisible_rules += n_removable_rules;
1236
1237             tcls_delete_matches(&tcls, &target->cls_rule);
1238             free_rule(target);
1239
1240             compare_classifiers(&cls, n_invisible_rules, version, &tcls);
1241             check_tables(&cls, -1, -1, -1, n_invisible_rules, version);
1242         }
1243         if (versioned) {
1244             struct test_rule *rule;
1245
1246             /* Remove rules that are no longer visible. */
1247             LIST_FOR_EACH_POP (rule, list_node, &list) {
1248                 classifier_remove(&cls, &rule->cls_rule);
1249                 n_invisible_rules--;
1250
1251                 compare_classifiers(&cls, n_invisible_rules, version,
1252                                     &tcls);
1253                 check_tables(&cls, -1, -1, -1, n_invisible_rules, version);
1254             }
1255         }
1256
1257         destroy_classifier(&cls);
1258         tcls_destroy(&tcls);
1259     }
1260 }
1261
1262 static void
1263 test_many_rules_in_two_tables(struct ovs_cmdl_context *ctx OVS_UNUSED)
1264 {
1265     test_many_rules_in_n_tables(2);
1266 }
1267
1268 static void
1269 test_many_rules_in_five_tables(struct ovs_cmdl_context *ctx OVS_UNUSED)
1270 {
1271     test_many_rules_in_n_tables(5);
1272 }
1273 \f
1274 /* Miniflow tests. */
1275
1276 static uint32_t
1277 random_value(void)
1278 {
1279     static const uint32_t values[] =
1280         { 0xffffffff, 0xaaaaaaaa, 0x55555555, 0x80000000,
1281           0x00000001, 0xface0000, 0x00d00d1e, 0xdeadbeef };
1282
1283     return values[random_range(ARRAY_SIZE(values))];
1284 }
1285
1286 static bool
1287 choose(unsigned int n, unsigned int *idxp)
1288 {
1289     if (*idxp < n) {
1290         return true;
1291     } else {
1292         *idxp -= n;
1293         return false;
1294     }
1295 }
1296
1297 #define FLOW_U32S (FLOW_U64S * 2)
1298
1299 static bool
1300 init_consecutive_values(int n_consecutive, struct flow *flow,
1301                         unsigned int *idxp)
1302 {
1303     uint32_t *flow_u32 = (uint32_t *) flow;
1304
1305     if (choose(FLOW_U32S - n_consecutive + 1, idxp)) {
1306         int i;
1307
1308         for (i = 0; i < n_consecutive; i++) {
1309             flow_u32[*idxp + i] = random_value();
1310         }
1311         return true;
1312     } else {
1313         return false;
1314     }
1315 }
1316
1317 static bool
1318 next_random_flow(struct flow *flow, unsigned int idx)
1319 {
1320     uint32_t *flow_u32 = (uint32_t *) flow;
1321     int i;
1322
1323     memset(flow, 0, sizeof *flow);
1324
1325     /* Empty flow. */
1326     if (choose(1, &idx)) {
1327         return true;
1328     }
1329
1330     /* All flows with a small number of consecutive nonzero values. */
1331     for (i = 1; i <= 4; i++) {
1332         if (init_consecutive_values(i, flow, &idx)) {
1333             return true;
1334         }
1335     }
1336
1337     /* All flows with a large number of consecutive nonzero values. */
1338     for (i = FLOW_U32S - 4; i <= FLOW_U32S; i++) {
1339         if (init_consecutive_values(i, flow, &idx)) {
1340             return true;
1341         }
1342     }
1343
1344     /* All flows with exactly two nonconsecutive nonzero values. */
1345     if (choose((FLOW_U32S - 1) * (FLOW_U32S - 2) / 2, &idx)) {
1346         int ofs1;
1347
1348         for (ofs1 = 0; ofs1 < FLOW_U32S - 2; ofs1++) {
1349             int ofs2;
1350
1351             for (ofs2 = ofs1 + 2; ofs2 < FLOW_U32S; ofs2++) {
1352                 if (choose(1, &idx)) {
1353                     flow_u32[ofs1] = random_value();
1354                     flow_u32[ofs2] = random_value();
1355                     return true;
1356                 }
1357             }
1358         }
1359         OVS_NOT_REACHED();
1360     }
1361
1362     /* 16 randomly chosen flows with N >= 3 nonzero values. */
1363     if (choose(16 * (FLOW_U32S - 4), &idx)) {
1364         int n = idx / 16 + 3;
1365         int i;
1366
1367         for (i = 0; i < n; i++) {
1368             flow_u32[i] = random_value();
1369         }
1370         shuffle_u32s(flow_u32, FLOW_U32S);
1371
1372         return true;
1373     }
1374
1375     return false;
1376 }
1377
1378 static void
1379 any_random_flow(struct flow *flow)
1380 {
1381     static unsigned int max;
1382     if (!max) {
1383         while (next_random_flow(flow, max)) {
1384             max++;
1385         }
1386     }
1387
1388     next_random_flow(flow, random_range(max));
1389 }
1390
1391 static void
1392 toggle_masked_flow_bits(struct flow *flow, const struct flow_wildcards *mask)
1393 {
1394     const uint32_t *mask_u32 = (const uint32_t *) &mask->masks;
1395     uint32_t *flow_u32 = (uint32_t *) flow;
1396     int i;
1397
1398     for (i = 0; i < FLOW_U32S; i++) {
1399         if (mask_u32[i] != 0) {
1400             uint32_t bit;
1401
1402             do {
1403                 bit = 1u << random_range(32);
1404             } while (!(bit & mask_u32[i]));
1405             flow_u32[i] ^= bit;
1406         }
1407     }
1408 }
1409
1410 static void
1411 wildcard_extra_bits(struct flow_wildcards *mask)
1412 {
1413     uint32_t *mask_u32 = (uint32_t *) &mask->masks;
1414     int i;
1415
1416     for (i = 0; i < FLOW_U32S; i++) {
1417         if (mask_u32[i] != 0) {
1418             uint32_t bit;
1419
1420             do {
1421                 bit = 1u << random_range(32);
1422             } while (!(bit & mask_u32[i]));
1423             mask_u32[i] &= ~bit;
1424         }
1425     }
1426 }
1427
1428 static void
1429 test_miniflow(struct ovs_cmdl_context *ctx OVS_UNUSED)
1430 {
1431     struct flow flow;
1432     unsigned int idx;
1433
1434     random_set_seed(0xb3faca38);
1435     for (idx = 0; next_random_flow(&flow, idx); idx++) {
1436         const uint64_t *flow_u64 = (const uint64_t *) &flow;
1437         struct miniflow miniflow, miniflow2, miniflow3;
1438         struct flow flow2, flow3;
1439         struct flow_wildcards mask;
1440         struct minimask minimask;
1441         int i;
1442
1443         /* Convert flow to miniflow. */
1444         miniflow_init(&miniflow, &flow);
1445
1446         /* Check that the flow equals its miniflow. */
1447         assert(miniflow_get_vid(&miniflow) == vlan_tci_to_vid(flow.vlan_tci));
1448         for (i = 0; i < FLOW_U64S; i++) {
1449             assert(miniflow_get(&miniflow, i) == flow_u64[i]);
1450         }
1451
1452         /* Check that the miniflow equals itself. */
1453         assert(miniflow_equal(&miniflow, &miniflow));
1454
1455         /* Convert miniflow back to flow and verify that it's the same. */
1456         miniflow_expand(&miniflow, &flow2);
1457         assert(flow_equal(&flow, &flow2));
1458
1459         /* Check that copying a miniflow works properly. */
1460         miniflow_clone(&miniflow2, &miniflow);
1461         assert(miniflow_equal(&miniflow, &miniflow2));
1462         assert(miniflow_hash(&miniflow, 0) == miniflow_hash(&miniflow2, 0));
1463         miniflow_expand(&miniflow2, &flow3);
1464         assert(flow_equal(&flow, &flow3));
1465
1466         /* Check that masked matches work as expected for identical flows and
1467          * miniflows. */
1468         do {
1469             next_random_flow(&mask.masks, 1);
1470         } while (flow_wildcards_is_catchall(&mask));
1471         minimask_init(&minimask, &mask);
1472         assert(minimask_is_catchall(&minimask)
1473                == flow_wildcards_is_catchall(&mask));
1474         assert(miniflow_equal_in_minimask(&miniflow, &miniflow2, &minimask));
1475         assert(miniflow_equal_flow_in_minimask(&miniflow, &flow2, &minimask));
1476         assert(miniflow_hash_in_minimask(&miniflow, &minimask, 0x12345678) ==
1477                flow_hash_in_minimask(&flow, &minimask, 0x12345678));
1478
1479         /* Check that masked matches work as expected for differing flows and
1480          * miniflows. */
1481         toggle_masked_flow_bits(&flow2, &mask);
1482         assert(!miniflow_equal_flow_in_minimask(&miniflow, &flow2, &minimask));
1483         miniflow_init(&miniflow3, &flow2);
1484         assert(!miniflow_equal_in_minimask(&miniflow, &miniflow3, &minimask));
1485
1486         /* Clean up. */
1487         miniflow_destroy(&miniflow);
1488         miniflow_destroy(&miniflow2);
1489         miniflow_destroy(&miniflow3);
1490         minimask_destroy(&minimask);
1491     }
1492 }
1493
1494 static void
1495 test_minimask_has_extra(struct ovs_cmdl_context *ctx OVS_UNUSED)
1496 {
1497     struct flow_wildcards catchall;
1498     struct minimask minicatchall;
1499     struct flow flow;
1500     unsigned int idx;
1501
1502     flow_wildcards_init_catchall(&catchall);
1503     minimask_init(&minicatchall, &catchall);
1504     assert(minimask_is_catchall(&minicatchall));
1505
1506     random_set_seed(0x2ec7905b);
1507     for (idx = 0; next_random_flow(&flow, idx); idx++) {
1508         struct flow_wildcards mask;
1509         struct minimask minimask;
1510
1511         mask.masks = flow;
1512         minimask_init(&minimask, &mask);
1513         assert(!minimask_has_extra(&minimask, &minimask));
1514         assert(minimask_has_extra(&minicatchall, &minimask)
1515                == !minimask_is_catchall(&minimask));
1516         if (!minimask_is_catchall(&minimask)) {
1517             struct minimask minimask2;
1518
1519             wildcard_extra_bits(&mask);
1520             minimask_init(&minimask2, &mask);
1521             assert(minimask_has_extra(&minimask2, &minimask));
1522             assert(!minimask_has_extra(&minimask, &minimask2));
1523             minimask_destroy(&minimask2);
1524         }
1525
1526         minimask_destroy(&minimask);
1527     }
1528
1529     minimask_destroy(&minicatchall);
1530 }
1531
1532 static void
1533 test_minimask_combine(struct ovs_cmdl_context *ctx OVS_UNUSED)
1534 {
1535     struct flow_wildcards catchall;
1536     struct minimask minicatchall;
1537     struct flow flow;
1538     unsigned int idx;
1539
1540     flow_wildcards_init_catchall(&catchall);
1541     minimask_init(&minicatchall, &catchall);
1542     assert(minimask_is_catchall(&minicatchall));
1543
1544     random_set_seed(0x181bf0cd);
1545     for (idx = 0; next_random_flow(&flow, idx); idx++) {
1546         struct minimask minimask, minimask2, minicombined;
1547         struct flow_wildcards mask, mask2, combined, combined2;
1548         uint64_t storage[FLOW_U64S];
1549         struct flow flow2;
1550
1551         mask.masks = flow;
1552         minimask_init(&minimask, &mask);
1553
1554         minimask_combine(&minicombined, &minimask, &minicatchall, storage);
1555         assert(minimask_is_catchall(&minicombined));
1556
1557         any_random_flow(&flow2);
1558         mask2.masks = flow2;
1559         minimask_init(&minimask2, &mask2);
1560
1561         minimask_combine(&minicombined, &minimask, &minimask2, storage);
1562         flow_wildcards_and(&combined, &mask, &mask2);
1563         minimask_expand(&minicombined, &combined2);
1564         assert(flow_wildcards_equal(&combined, &combined2));
1565
1566         minimask_destroy(&minimask);
1567         minimask_destroy(&minimask2);
1568     }
1569
1570     minimask_destroy(&minicatchall);
1571 }
1572 \f
1573 static const struct ovs_cmdl_command commands[] = {
1574     /* Classifier tests. */
1575     {"empty", NULL, 0, 0, test_empty},
1576     {"destroy-null", NULL, 0, 0, test_destroy_null},
1577     {"single-rule", NULL, 0, 0, test_single_rule},
1578     {"rule-replacement", NULL, 0, 0, test_rule_replacement},
1579     {"many-rules-in-one-list", NULL, 0, 1, test_many_rules_in_one_list},
1580     {"many-rules-in-one-table", NULL, 0, 1, test_many_rules_in_one_table},
1581     {"many-rules-in-two-tables", NULL, 0, 0, test_many_rules_in_two_tables},
1582     {"many-rules-in-five-tables", NULL, 0, 0, test_many_rules_in_five_tables},
1583
1584     /* Miniflow and minimask tests. */
1585     {"miniflow", NULL, 0, 0, test_miniflow},
1586     {"minimask_has_extra", NULL, 0, 0, test_minimask_has_extra},
1587     {"minimask_combine", NULL, 0, 0, test_minimask_combine},
1588
1589     {NULL, NULL, 0, 0, NULL},
1590 };
1591
1592 static void
1593 test_classifier_main(int argc, char *argv[])
1594 {
1595     struct ovs_cmdl_context ctx = {
1596         .argc = argc - 1,
1597         .argv = argv + 1,
1598     };
1599     set_program_name(argv[0]);
1600
1601     if (argc > 1 && !strcmp(argv[1], "--versioned")) {
1602         versioned = true;
1603         ctx.argc--;
1604         ctx.argv++;
1605     }
1606
1607     init_values();
1608     ovs_cmdl_run_command(&ctx, commands);
1609 }
1610
1611 OVSTEST_REGISTER("test-classifier", test_classifier_main);