Introduce sparse flows and masks, to reduce memory usage and improve speed.
[sliver-openvswitch.git] / tests / test-classifier.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012 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 #include "classifier.h"
30 #include <errno.h>
31 #include <limits.h>
32 #include "byte-order.h"
33 #include "command-line.h"
34 #include "flow.h"
35 #include "ofp-util.h"
36 #include "packets.h"
37 #include "unaligned.h"
38
39 #undef NDEBUG
40 #include <assert.h>
41
42 /* Fields in a rule. */
43 #define CLS_FIELDS                                                  \
44     /*        struct flow  all-caps */  \
45     /*        member name  name     */  \
46     /*        -----------  -------- */  \
47     CLS_FIELD(tun_id,      TUN_ID)      \
48     CLS_FIELD(metadata,    METADATA)    \
49     CLS_FIELD(nw_src,      NW_SRC)      \
50     CLS_FIELD(nw_dst,      NW_DST)      \
51     CLS_FIELD(in_port,     IN_PORT)     \
52     CLS_FIELD(vlan_tci,    VLAN_TCI)    \
53     CLS_FIELD(dl_type,     DL_TYPE)     \
54     CLS_FIELD(tp_src,      TP_SRC)      \
55     CLS_FIELD(tp_dst,      TP_DST)      \
56     CLS_FIELD(dl_src,      DL_SRC)      \
57     CLS_FIELD(dl_dst,      DL_DST)      \
58     CLS_FIELD(nw_proto,    NW_PROTO)    \
59     CLS_FIELD(nw_tos,      NW_DSCP)
60
61 /* Field indexes.
62  *
63  * (These are also indexed into struct classifier's 'tables' array.) */
64 enum {
65 #define CLS_FIELD(MEMBER, NAME) CLS_F_IDX_##NAME,
66     CLS_FIELDS
67 #undef CLS_FIELD
68     CLS_N_FIELDS
69 };
70
71 /* Field information. */
72 struct cls_field {
73     int ofs;                    /* Offset in struct flow. */
74     int len;                    /* Length in bytes. */
75     const char *name;           /* Name (for debugging). */
76 };
77
78 static const struct cls_field cls_fields[CLS_N_FIELDS] = {
79 #define CLS_FIELD(MEMBER, NAME)                 \
80     { offsetof(struct flow, MEMBER),            \
81       sizeof ((struct flow *)0)->MEMBER,        \
82       #NAME },
83     CLS_FIELDS
84 #undef CLS_FIELD
85 };
86
87 struct test_rule {
88     int aux;                    /* Auxiliary data. */
89     struct cls_rule cls_rule;   /* Classifier rule data. */
90 };
91
92 static struct test_rule *
93 test_rule_from_cls_rule(const struct cls_rule *rule)
94 {
95     return rule ? CONTAINER_OF(rule, struct test_rule, cls_rule) : NULL;
96 }
97
98 static struct test_rule *make_rule(int wc_fields, unsigned int priority,
99                                    int value_pat);
100 static void free_rule(struct test_rule *);
101 static struct test_rule *clone_rule(const struct test_rule *);
102
103 /* Trivial (linear) classifier. */
104 struct tcls {
105     size_t n_rules;
106     size_t allocated_rules;
107     struct test_rule **rules;
108 };
109
110 static void
111 tcls_init(struct tcls *tcls)
112 {
113     tcls->n_rules = 0;
114     tcls->allocated_rules = 0;
115     tcls->rules = NULL;
116 }
117
118 static void
119 tcls_destroy(struct tcls *tcls)
120 {
121     if (tcls) {
122         size_t i;
123
124         for (i = 0; i < tcls->n_rules; i++) {
125             free(tcls->rules[i]);
126         }
127         free(tcls->rules);
128     }
129 }
130
131 static bool
132 tcls_is_empty(const struct tcls *tcls)
133 {
134     return tcls->n_rules == 0;
135 }
136
137 static struct test_rule *
138 tcls_insert(struct tcls *tcls, const struct test_rule *rule)
139 {
140     size_t i;
141
142     for (i = 0; i < tcls->n_rules; i++) {
143         const struct cls_rule *pos = &tcls->rules[i]->cls_rule;
144         if (cls_rule_equal(pos, &rule->cls_rule)) {
145             /* Exact match. */
146             free_rule(tcls->rules[i]);
147             tcls->rules[i] = clone_rule(rule);
148             return tcls->rules[i];
149         } else if (pos->priority < rule->cls_rule.priority) {
150             break;
151         }
152     }
153
154     if (tcls->n_rules >= tcls->allocated_rules) {
155         tcls->rules = x2nrealloc(tcls->rules, &tcls->allocated_rules,
156                                  sizeof *tcls->rules);
157     }
158     if (i != tcls->n_rules) {
159         memmove(&tcls->rules[i + 1], &tcls->rules[i],
160                 sizeof *tcls->rules * (tcls->n_rules - i));
161     }
162     tcls->rules[i] = clone_rule(rule);
163     tcls->n_rules++;
164     return tcls->rules[i];
165 }
166
167 static void
168 tcls_remove(struct tcls *cls, const struct test_rule *rule)
169 {
170     size_t i;
171
172     for (i = 0; i < cls->n_rules; i++) {
173         struct test_rule *pos = cls->rules[i];
174         if (pos == rule) {
175             free(pos);
176             memmove(&cls->rules[i], &cls->rules[i + 1],
177                     sizeof *cls->rules * (cls->n_rules - i - 1));
178             cls->n_rules--;
179             return;
180         }
181     }
182     NOT_REACHED();
183 }
184
185 static bool
186 match(const struct cls_rule *wild_, const struct flow *fixed)
187 {
188     struct match wild;
189     int f_idx;
190
191     minimatch_expand(&wild_->match, &wild);
192     for (f_idx = 0; f_idx < CLS_N_FIELDS; f_idx++) {
193         bool eq;
194
195         if (f_idx == CLS_F_IDX_NW_SRC) {
196             eq = !((fixed->nw_src ^ wild.flow.nw_src)
197                    & wild.wc.masks.nw_src);
198         } else if (f_idx == CLS_F_IDX_NW_DST) {
199             eq = !((fixed->nw_dst ^ wild.flow.nw_dst)
200                    & wild.wc.masks.nw_dst);
201         } else if (f_idx == CLS_F_IDX_TP_SRC) {
202             eq = !((fixed->tp_src ^ wild.flow.tp_src)
203                    & wild.wc.masks.tp_src);
204         } else if (f_idx == CLS_F_IDX_TP_DST) {
205             eq = !((fixed->tp_dst ^ wild.flow.tp_dst)
206                    & wild.wc.masks.tp_dst);
207         } else if (f_idx == CLS_F_IDX_DL_SRC) {
208             eq = eth_addr_equal_except(fixed->dl_src, wild.flow.dl_src,
209                                        wild.wc.masks.dl_src);
210         } else if (f_idx == CLS_F_IDX_DL_DST) {
211             eq = eth_addr_equal_except(fixed->dl_dst, wild.flow.dl_dst,
212                                        wild.wc.masks.dl_dst);
213         } else if (f_idx == CLS_F_IDX_VLAN_TCI) {
214             eq = !((fixed->vlan_tci ^ wild.flow.vlan_tci)
215                    & wild.wc.masks.vlan_tci);
216         } else if (f_idx == CLS_F_IDX_TUN_ID) {
217             eq = !((fixed->tun_id ^ wild.flow.tun_id)
218                    & wild.wc.masks.tun_id);
219         } else if (f_idx == CLS_F_IDX_METADATA) {
220             eq = !((fixed->metadata ^ wild.flow.metadata)
221                    & wild.wc.masks.metadata);
222         } else if (f_idx == CLS_F_IDX_NW_DSCP) {
223             eq = !((fixed->nw_tos ^ wild.flow.nw_tos) &
224                    (wild.wc.masks.nw_tos & IP_DSCP_MASK));
225         } else if (f_idx == CLS_F_IDX_NW_PROTO) {
226             eq = !((fixed->nw_proto ^ wild.flow.nw_proto)
227                    & wild.wc.masks.nw_proto);
228         } else if (f_idx == CLS_F_IDX_DL_TYPE) {
229             eq = !((fixed->dl_type ^ wild.flow.dl_type)
230                    & wild.wc.masks.dl_type);
231         } else if (f_idx == CLS_F_IDX_IN_PORT) {
232             eq = !((fixed->in_port ^ wild.flow.in_port)
233                    & wild.wc.masks.in_port);
234         } else {
235             NOT_REACHED();
236         }
237
238         if (!eq) {
239             return false;
240         }
241     }
242     return true;
243 }
244
245 static struct cls_rule *
246 tcls_lookup(const struct tcls *cls, const struct flow *flow)
247 {
248     size_t i;
249
250     for (i = 0; i < cls->n_rules; i++) {
251         struct test_rule *pos = cls->rules[i];
252         if (match(&pos->cls_rule, flow)) {
253             return &pos->cls_rule;
254         }
255     }
256     return NULL;
257 }
258
259 static void
260 tcls_delete_matches(struct tcls *cls, const struct cls_rule *target)
261 {
262     size_t i;
263
264     for (i = 0; i < cls->n_rules; ) {
265         struct test_rule *pos = cls->rules[i];
266         if (!minimask_has_extra(&pos->cls_rule.match.mask,
267                                 &target->match.mask)) {
268             struct flow flow;
269
270             miniflow_expand(&pos->cls_rule.match.flow, &flow);
271             if (match(target, &flow)) {
272                 tcls_remove(cls, pos);
273                 continue;
274             }
275         }
276         i++;
277     }
278 }
279 \f
280 static ovs_be32 nw_src_values[] = { CONSTANT_HTONL(0xc0a80001),
281                                     CONSTANT_HTONL(0xc0a04455) };
282 static ovs_be32 nw_dst_values[] = { CONSTANT_HTONL(0xc0a80002),
283                                     CONSTANT_HTONL(0xc0a04455) };
284 static ovs_be64 tun_id_values[] = {
285     0,
286     CONSTANT_HTONLL(UINT64_C(0xfedcba9876543210)) };
287 static ovs_be64 metadata_values[] = {
288     0,
289     CONSTANT_HTONLL(UINT64_C(0xfedcba9876543210)) };
290 static uint16_t in_port_values[] = { 1, OFPP_LOCAL };
291 static ovs_be16 vlan_tci_values[] = { CONSTANT_HTONS(101), CONSTANT_HTONS(0) };
292 static ovs_be16 dl_type_values[]
293             = { CONSTANT_HTONS(ETH_TYPE_IP), CONSTANT_HTONS(ETH_TYPE_ARP) };
294 static ovs_be16 tp_src_values[] = { CONSTANT_HTONS(49362),
295                                     CONSTANT_HTONS(80) };
296 static ovs_be16 tp_dst_values[] = { CONSTANT_HTONS(6667), CONSTANT_HTONS(22) };
297 static uint8_t dl_src_values[][6] = { { 0x00, 0x02, 0xe3, 0x0f, 0x80, 0xa4 },
298                                       { 0x5e, 0x33, 0x7f, 0x5f, 0x1e, 0x99 } };
299 static uint8_t dl_dst_values[][6] = { { 0x4a, 0x27, 0x71, 0xae, 0x64, 0xc1 },
300                                       { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } };
301 static uint8_t nw_proto_values[] = { IPPROTO_TCP, IPPROTO_ICMP };
302 static uint8_t nw_dscp_values[] = { 48, 0 };
303
304 static void *values[CLS_N_FIELDS][2];
305
306 static void
307 init_values(void)
308 {
309     values[CLS_F_IDX_TUN_ID][0] = &tun_id_values[0];
310     values[CLS_F_IDX_TUN_ID][1] = &tun_id_values[1];
311
312     values[CLS_F_IDX_METADATA][0] = &metadata_values[0];
313     values[CLS_F_IDX_METADATA][1] = &metadata_values[1];
314
315     values[CLS_F_IDX_IN_PORT][0] = &in_port_values[0];
316     values[CLS_F_IDX_IN_PORT][1] = &in_port_values[1];
317
318     values[CLS_F_IDX_VLAN_TCI][0] = &vlan_tci_values[0];
319     values[CLS_F_IDX_VLAN_TCI][1] = &vlan_tci_values[1];
320
321     values[CLS_F_IDX_DL_SRC][0] = dl_src_values[0];
322     values[CLS_F_IDX_DL_SRC][1] = dl_src_values[1];
323
324     values[CLS_F_IDX_DL_DST][0] = dl_dst_values[0];
325     values[CLS_F_IDX_DL_DST][1] = dl_dst_values[1];
326
327     values[CLS_F_IDX_DL_TYPE][0] = &dl_type_values[0];
328     values[CLS_F_IDX_DL_TYPE][1] = &dl_type_values[1];
329
330     values[CLS_F_IDX_NW_SRC][0] = &nw_src_values[0];
331     values[CLS_F_IDX_NW_SRC][1] = &nw_src_values[1];
332
333     values[CLS_F_IDX_NW_DST][0] = &nw_dst_values[0];
334     values[CLS_F_IDX_NW_DST][1] = &nw_dst_values[1];
335
336     values[CLS_F_IDX_NW_PROTO][0] = &nw_proto_values[0];
337     values[CLS_F_IDX_NW_PROTO][1] = &nw_proto_values[1];
338
339     values[CLS_F_IDX_NW_DSCP][0] = &nw_dscp_values[0];
340     values[CLS_F_IDX_NW_DSCP][1] = &nw_dscp_values[1];
341
342     values[CLS_F_IDX_TP_SRC][0] = &tp_src_values[0];
343     values[CLS_F_IDX_TP_SRC][1] = &tp_src_values[1];
344
345     values[CLS_F_IDX_TP_DST][0] = &tp_dst_values[0];
346     values[CLS_F_IDX_TP_DST][1] = &tp_dst_values[1];
347 }
348
349 #define N_NW_SRC_VALUES ARRAY_SIZE(nw_src_values)
350 #define N_NW_DST_VALUES ARRAY_SIZE(nw_dst_values)
351 #define N_TUN_ID_VALUES ARRAY_SIZE(tun_id_values)
352 #define N_METADATA_VALUES ARRAY_SIZE(metadata_values)
353 #define N_IN_PORT_VALUES ARRAY_SIZE(in_port_values)
354 #define N_VLAN_TCI_VALUES ARRAY_SIZE(vlan_tci_values)
355 #define N_DL_TYPE_VALUES ARRAY_SIZE(dl_type_values)
356 #define N_TP_SRC_VALUES ARRAY_SIZE(tp_src_values)
357 #define N_TP_DST_VALUES ARRAY_SIZE(tp_dst_values)
358 #define N_DL_SRC_VALUES ARRAY_SIZE(dl_src_values)
359 #define N_DL_DST_VALUES ARRAY_SIZE(dl_dst_values)
360 #define N_NW_PROTO_VALUES ARRAY_SIZE(nw_proto_values)
361 #define N_NW_DSCP_VALUES ARRAY_SIZE(nw_dscp_values)
362
363 #define N_FLOW_VALUES (N_NW_SRC_VALUES *        \
364                        N_NW_DST_VALUES *        \
365                        N_TUN_ID_VALUES *        \
366                        N_IN_PORT_VALUES *       \
367                        N_VLAN_TCI_VALUES *       \
368                        N_DL_TYPE_VALUES *       \
369                        N_TP_SRC_VALUES *        \
370                        N_TP_DST_VALUES *        \
371                        N_DL_SRC_VALUES *        \
372                        N_DL_DST_VALUES *        \
373                        N_NW_PROTO_VALUES *      \
374                        N_NW_DSCP_VALUES)
375
376 static unsigned int
377 get_value(unsigned int *x, unsigned n_values)
378 {
379     unsigned int rem = *x % n_values;
380     *x /= n_values;
381     return rem;
382 }
383
384 static void
385 compare_classifiers(struct classifier *cls, struct tcls *tcls)
386 {
387     static const int confidence = 500;
388     unsigned int i;
389
390     assert(classifier_count(cls) == tcls->n_rules);
391     for (i = 0; i < confidence; i++) {
392         struct cls_rule *cr0, *cr1;
393         struct flow flow;
394         unsigned int x;
395
396         x = rand () % N_FLOW_VALUES;
397         memset(&flow, 0, sizeof flow);
398         flow.nw_src = nw_src_values[get_value(&x, N_NW_SRC_VALUES)];
399         flow.nw_dst = nw_dst_values[get_value(&x, N_NW_DST_VALUES)];
400         flow.tun_id = tun_id_values[get_value(&x, N_TUN_ID_VALUES)];
401         flow.metadata = metadata_values[get_value(&x, N_METADATA_VALUES)];
402         flow.in_port = in_port_values[get_value(&x, N_IN_PORT_VALUES)];
403         flow.vlan_tci = vlan_tci_values[get_value(&x, N_VLAN_TCI_VALUES)];
404         flow.dl_type = dl_type_values[get_value(&x, N_DL_TYPE_VALUES)];
405         flow.tp_src = tp_src_values[get_value(&x, N_TP_SRC_VALUES)];
406         flow.tp_dst = tp_dst_values[get_value(&x, N_TP_DST_VALUES)];
407         memcpy(flow.dl_src, dl_src_values[get_value(&x, N_DL_SRC_VALUES)],
408                ETH_ADDR_LEN);
409         memcpy(flow.dl_dst, dl_dst_values[get_value(&x, N_DL_DST_VALUES)],
410                ETH_ADDR_LEN);
411         flow.nw_proto = nw_proto_values[get_value(&x, N_NW_PROTO_VALUES)];
412         flow.nw_tos = nw_dscp_values[get_value(&x, N_NW_DSCP_VALUES)];
413
414         cr0 = classifier_lookup(cls, &flow);
415         cr1 = tcls_lookup(tcls, &flow);
416         assert((cr0 == NULL) == (cr1 == NULL));
417         if (cr0 != NULL) {
418             const struct test_rule *tr0 = test_rule_from_cls_rule(cr0);
419             const struct test_rule *tr1 = test_rule_from_cls_rule(cr1);
420
421             assert(cls_rule_equal(cr0, cr1));
422             assert(tr0->aux == tr1->aux);
423         }
424     }
425 }
426
427 static void
428 destroy_classifier(struct classifier *cls)
429 {
430     struct test_rule *rule, *next_rule;
431     struct cls_cursor cursor;
432
433     cls_cursor_init(&cursor, cls, NULL);
434     CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cls_rule, &cursor) {
435         classifier_remove(cls, &rule->cls_rule);
436         free_rule(rule);
437     }
438     classifier_destroy(cls);
439 }
440
441 static void
442 check_tables(const struct classifier *cls,
443              int n_tables, int n_rules, int n_dups)
444 {
445     const struct cls_table *table;
446     struct test_rule *test_rule;
447     struct cls_cursor cursor;
448     int found_tables = 0;
449     int found_rules = 0;
450     int found_dups = 0;
451     int found_rules2 = 0;
452
453     HMAP_FOR_EACH (table, hmap_node, &cls->tables) {
454         const struct cls_rule *head;
455
456         assert(!hmap_is_empty(&table->rules));
457
458         found_tables++;
459         HMAP_FOR_EACH (head, hmap_node, &table->rules) {
460             unsigned int prev_priority = UINT_MAX;
461             const struct cls_rule *rule;
462
463             found_rules++;
464             LIST_FOR_EACH (rule, list, &head->list) {
465                 assert(rule->priority < prev_priority);
466                 prev_priority = rule->priority;
467                 found_rules++;
468                 found_dups++;
469                 assert(classifier_find_rule_exactly(cls, rule) == rule);
470             }
471         }
472     }
473
474     assert(found_tables == hmap_count(&cls->tables));
475     assert(n_tables == -1 || n_tables == hmap_count(&cls->tables));
476     assert(n_rules == -1 || found_rules == n_rules);
477     assert(n_dups == -1 || found_dups == n_dups);
478
479     cls_cursor_init(&cursor, cls, NULL);
480     CLS_CURSOR_FOR_EACH (test_rule, cls_rule, &cursor) {
481         found_rules2++;
482     }
483     assert(found_rules == found_rules2);
484 }
485
486 static struct test_rule *
487 make_rule(int wc_fields, unsigned int priority, int value_pat)
488 {
489     const struct cls_field *f;
490     struct test_rule *rule;
491     struct match match;
492
493     match_init_catchall(&match);
494     for (f = &cls_fields[0]; f < &cls_fields[CLS_N_FIELDS]; f++) {
495         int f_idx = f - cls_fields;
496         int value_idx = (value_pat & (1u << f_idx)) != 0;
497         memcpy((char *) &match.flow + f->ofs,
498                values[f_idx][value_idx], f->len);
499
500         if (f_idx == CLS_F_IDX_NW_SRC) {
501             match.wc.masks.nw_src = htonl(UINT32_MAX);
502         } else if (f_idx == CLS_F_IDX_NW_DST) {
503             match.wc.masks.nw_dst = htonl(UINT32_MAX);
504         } else if (f_idx == CLS_F_IDX_TP_SRC) {
505             match.wc.masks.tp_src = htons(UINT16_MAX);
506         } else if (f_idx == CLS_F_IDX_TP_DST) {
507             match.wc.masks.tp_dst = htons(UINT16_MAX);
508         } else if (f_idx == CLS_F_IDX_DL_SRC) {
509             memset(match.wc.masks.dl_src, 0xff, ETH_ADDR_LEN);
510         } else if (f_idx == CLS_F_IDX_DL_DST) {
511             memset(match.wc.masks.dl_dst, 0xff, ETH_ADDR_LEN);
512         } else if (f_idx == CLS_F_IDX_VLAN_TCI) {
513             match.wc.masks.vlan_tci = htons(UINT16_MAX);
514         } else if (f_idx == CLS_F_IDX_TUN_ID) {
515             match.wc.masks.tun_id = htonll(UINT64_MAX);
516         } else if (f_idx == CLS_F_IDX_METADATA) {
517             match.wc.masks.metadata = htonll(UINT64_MAX);
518         } else if (f_idx == CLS_F_IDX_NW_DSCP) {
519             match.wc.masks.nw_tos |= IP_DSCP_MASK;
520         } else if (f_idx == CLS_F_IDX_NW_PROTO) {
521             match.wc.masks.nw_proto = UINT8_MAX;
522         } else if (f_idx == CLS_F_IDX_DL_TYPE) {
523             match.wc.masks.dl_type = htons(UINT16_MAX);
524         } else if (f_idx == CLS_F_IDX_IN_PORT) {
525             match.wc.masks.in_port = UINT16_MAX;
526         } else {
527             NOT_REACHED();
528         }
529     }
530
531     rule = xzalloc(sizeof *rule);
532     cls_rule_init(&rule->cls_rule, &match, wc_fields ? priority : UINT_MAX);
533     return rule;
534 }
535
536 static struct test_rule *
537 clone_rule(const struct test_rule *src)
538 {
539     struct test_rule *dst;
540
541     dst = xmalloc(sizeof *dst);
542     dst->aux = src->aux;
543     cls_rule_clone(&dst->cls_rule, &src->cls_rule);
544     return dst;
545 }
546
547 static void
548 free_rule(struct test_rule *rule)
549 {
550     cls_rule_destroy(&rule->cls_rule);
551     free(rule);
552 }
553
554 static void
555 shuffle(unsigned int *p, size_t n)
556 {
557     for (; n > 1; n--, p++) {
558         unsigned int *q = &p[rand() % n];
559         unsigned int tmp = *p;
560         *p = *q;
561         *q = tmp;
562     }
563 }
564
565 static void
566 shuffle_u32s(uint32_t *p, size_t n)
567 {
568     for (; n > 1; n--, p++) {
569         uint32_t *q = &p[rand() % n];
570         uint32_t tmp = *p;
571         *p = *q;
572         *q = tmp;
573     }
574 }
575 \f
576 /* Classifier tests. */
577
578 /* Tests an empty classifier. */
579 static void
580 test_empty(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
581 {
582     struct classifier cls;
583     struct tcls tcls;
584
585     classifier_init(&cls);
586     tcls_init(&tcls);
587     assert(classifier_is_empty(&cls));
588     assert(tcls_is_empty(&tcls));
589     compare_classifiers(&cls, &tcls);
590     classifier_destroy(&cls);
591     tcls_destroy(&tcls);
592 }
593
594 /* Destroys a null classifier. */
595 static void
596 test_destroy_null(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
597 {
598     classifier_destroy(NULL);
599 }
600
601 /* Tests classification with one rule at a time. */
602 static void
603 test_single_rule(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
604 {
605     unsigned int wc_fields;     /* Hilarious. */
606
607     for (wc_fields = 0; wc_fields < (1u << CLS_N_FIELDS); wc_fields++) {
608         struct classifier cls;
609         struct test_rule *rule, *tcls_rule;
610         struct tcls tcls;
611
612         rule = make_rule(wc_fields,
613                          hash_bytes(&wc_fields, sizeof wc_fields, 0), 0);
614
615         classifier_init(&cls);
616         tcls_init(&tcls);
617
618         tcls_rule = tcls_insert(&tcls, rule);
619         classifier_insert(&cls, &rule->cls_rule);
620         check_tables(&cls, 1, 1, 0);
621         compare_classifiers(&cls, &tcls);
622
623         classifier_remove(&cls, &rule->cls_rule);
624         tcls_remove(&tcls, tcls_rule);
625         assert(classifier_is_empty(&cls));
626         assert(tcls_is_empty(&tcls));
627         compare_classifiers(&cls, &tcls);
628
629         free_rule(rule);
630         classifier_destroy(&cls);
631         tcls_destroy(&tcls);
632     }
633 }
634
635 /* Tests replacing one rule by another. */
636 static void
637 test_rule_replacement(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
638 {
639     unsigned int wc_fields;
640
641     for (wc_fields = 0; wc_fields < (1u << CLS_N_FIELDS); wc_fields++) {
642         struct classifier cls;
643         struct test_rule *rule1;
644         struct test_rule *rule2;
645         struct tcls tcls;
646
647         rule1 = make_rule(wc_fields, OFP_DEFAULT_PRIORITY, UINT_MAX);
648         rule2 = make_rule(wc_fields, OFP_DEFAULT_PRIORITY, UINT_MAX);
649         rule2->aux += 5;
650         rule2->aux += 5;
651
652         classifier_init(&cls);
653         tcls_init(&tcls);
654         tcls_insert(&tcls, rule1);
655         classifier_insert(&cls, &rule1->cls_rule);
656         check_tables(&cls, 1, 1, 0);
657         compare_classifiers(&cls, &tcls);
658         tcls_destroy(&tcls);
659
660         tcls_init(&tcls);
661         tcls_insert(&tcls, rule2);
662         assert(test_rule_from_cls_rule(
663                    classifier_replace(&cls, &rule2->cls_rule)) == rule1);
664         free_rule(rule1);
665         check_tables(&cls, 1, 1, 0);
666         compare_classifiers(&cls, &tcls);
667         tcls_destroy(&tcls);
668         destroy_classifier(&cls);
669     }
670 }
671
672 static int
673 factorial(int n_items)
674 {
675     int n, i;
676
677     n = 1;
678     for (i = 2; i <= n_items; i++) {
679         n *= i;
680     }
681     return n;
682 }
683
684 static void
685 swap(int *a, int *b)
686 {
687     int tmp = *a;
688     *a = *b;
689     *b = tmp;
690 }
691
692 static void
693 reverse(int *a, int n)
694 {
695     int i;
696
697     for (i = 0; i < n / 2; i++) {
698         int j = n - (i + 1);
699         swap(&a[i], &a[j]);
700     }
701 }
702
703 static bool
704 next_permutation(int *a, int n)
705 {
706     int k;
707
708     for (k = n - 2; k >= 0; k--) {
709         if (a[k] < a[k + 1]) {
710             int l;
711
712             for (l = n - 1; ; l--) {
713                 if (a[l] > a[k]) {
714                     swap(&a[k], &a[l]);
715                     reverse(a + (k + 1), n - (k + 1));
716                     return true;
717                 }
718             }
719         }
720     }
721     return false;
722 }
723
724 /* Tests classification with rules that have the same matching criteria. */
725 static void
726 test_many_rules_in_one_list (int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
727 {
728     enum { N_RULES = 3 };
729     int n_pris;
730
731     for (n_pris = N_RULES; n_pris >= 1; n_pris--) {
732         int ops[N_RULES * 2];
733         int pris[N_RULES];
734         int n_permutations;
735         int i;
736
737         pris[0] = 0;
738         for (i = 1; i < N_RULES; i++) {
739             pris[i] = pris[i - 1] + (n_pris > i);
740         }
741
742         for (i = 0; i < N_RULES * 2; i++) {
743             ops[i] = i / 2;
744         }
745
746         n_permutations = 0;
747         do {
748             struct test_rule *rules[N_RULES];
749             struct test_rule *tcls_rules[N_RULES];
750             int pri_rules[N_RULES];
751             struct classifier cls;
752             struct tcls tcls;
753
754             n_permutations++;
755
756             for (i = 0; i < N_RULES; i++) {
757                 rules[i] = make_rule(456, pris[i], 0);
758                 tcls_rules[i] = NULL;
759                 pri_rules[i] = -1;
760             }
761
762             classifier_init(&cls);
763             tcls_init(&tcls);
764
765             for (i = 0; i < ARRAY_SIZE(ops); i++) {
766                 int j = ops[i];
767                 int m, n;
768
769                 if (!tcls_rules[j]) {
770                     struct test_rule *displaced_rule;
771
772                     tcls_rules[j] = tcls_insert(&tcls, rules[j]);
773                     displaced_rule = test_rule_from_cls_rule(
774                         classifier_replace(&cls, &rules[j]->cls_rule));
775                     if (pri_rules[pris[j]] >= 0) {
776                         int k = pri_rules[pris[j]];
777                         assert(displaced_rule != NULL);
778                         assert(displaced_rule != rules[j]);
779                         assert(pris[j] == displaced_rule->cls_rule.priority);
780                         tcls_rules[k] = NULL;
781                     } else {
782                         assert(displaced_rule == NULL);
783                     }
784                     pri_rules[pris[j]] = j;
785                 } else {
786                     classifier_remove(&cls, &rules[j]->cls_rule);
787                     tcls_remove(&tcls, tcls_rules[j]);
788                     tcls_rules[j] = NULL;
789                     pri_rules[pris[j]] = -1;
790                 }
791
792                 n = 0;
793                 for (m = 0; m < N_RULES; m++) {
794                     n += tcls_rules[m] != NULL;
795                 }
796                 check_tables(&cls, n > 0, n, n - 1);
797
798                 compare_classifiers(&cls, &tcls);
799             }
800
801             classifier_destroy(&cls);
802             tcls_destroy(&tcls);
803
804             for (i = 0; i < N_RULES; i++) {
805                 free_rule(rules[i]);
806             }
807         } while (next_permutation(ops, ARRAY_SIZE(ops)));
808         assert(n_permutations == (factorial(N_RULES * 2) >> N_RULES));
809     }
810 }
811
812 static int
813 count_ones(unsigned long int x)
814 {
815     int n = 0;
816
817     while (x) {
818         x = zero_rightmost_1bit(x);
819         n++;
820     }
821
822     return n;
823 }
824
825 static bool
826 array_contains(int *array, int n, int value)
827 {
828     int i;
829
830     for (i = 0; i < n; i++) {
831         if (array[i] == value) {
832             return true;
833         }
834     }
835
836     return false;
837 }
838
839 /* Tests classification with two rules at a time that fall into the same
840  * table but different lists. */
841 static void
842 test_many_rules_in_one_table(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
843 {
844     int iteration;
845
846     for (iteration = 0; iteration < 50; iteration++) {
847         enum { N_RULES = 20 };
848         struct test_rule *rules[N_RULES];
849         struct test_rule *tcls_rules[N_RULES];
850         struct classifier cls;
851         struct tcls tcls;
852         int value_pats[N_RULES];
853         int value_mask;
854         int wcf;
855         int i;
856
857         do {
858             wcf = rand() & ((1u << CLS_N_FIELDS) - 1);
859             value_mask = ~wcf & ((1u << CLS_N_FIELDS) - 1);
860         } while ((1 << count_ones(value_mask)) < N_RULES);
861
862         classifier_init(&cls);
863         tcls_init(&tcls);
864
865         for (i = 0; i < N_RULES; i++) {
866             unsigned int priority = rand();
867
868             do {
869                 value_pats[i] = rand() & value_mask;
870             } while (array_contains(value_pats, i, value_pats[i]));
871
872             rules[i] = make_rule(wcf, priority, value_pats[i]);
873             tcls_rules[i] = tcls_insert(&tcls, rules[i]);
874             classifier_insert(&cls, &rules[i]->cls_rule);
875
876             check_tables(&cls, 1, i + 1, 0);
877             compare_classifiers(&cls, &tcls);
878         }
879
880         for (i = 0; i < N_RULES; i++) {
881             tcls_remove(&tcls, tcls_rules[i]);
882             classifier_remove(&cls, &rules[i]->cls_rule);
883             free_rule(rules[i]);
884
885             check_tables(&cls, i < N_RULES - 1, N_RULES - (i + 1), 0);
886             compare_classifiers(&cls, &tcls);
887         }
888
889         classifier_destroy(&cls);
890         tcls_destroy(&tcls);
891     }
892 }
893
894 /* Tests classification with many rules at a time that fall into random lists
895  * in 'n' tables. */
896 static void
897 test_many_rules_in_n_tables(int n_tables)
898 {
899     enum { MAX_RULES = 50 };
900     int wcfs[10];
901     int iteration;
902     int i;
903
904     assert(n_tables < 10);
905     for (i = 0; i < n_tables; i++) {
906         do {
907             wcfs[i] = rand() & ((1u << CLS_N_FIELDS) - 1);
908         } while (array_contains(wcfs, i, wcfs[i]));
909     }
910
911     for (iteration = 0; iteration < 30; iteration++) {
912         unsigned int priorities[MAX_RULES];
913         struct classifier cls;
914         struct tcls tcls;
915
916         srand(iteration);
917         for (i = 0; i < MAX_RULES; i++) {
918             priorities[i] = i * 129;
919         }
920         shuffle(priorities, ARRAY_SIZE(priorities));
921
922         classifier_init(&cls);
923         tcls_init(&tcls);
924
925         for (i = 0; i < MAX_RULES; i++) {
926             struct test_rule *rule;
927             unsigned int priority = priorities[i];
928             int wcf = wcfs[rand() % n_tables];
929             int value_pat = rand() & ((1u << CLS_N_FIELDS) - 1);
930             rule = make_rule(wcf, priority, value_pat);
931             tcls_insert(&tcls, rule);
932             classifier_insert(&cls, &rule->cls_rule);
933             check_tables(&cls, -1, i + 1, -1);
934             compare_classifiers(&cls, &tcls);
935         }
936
937         while (!classifier_is_empty(&cls)) {
938             struct test_rule *rule, *next_rule;
939             struct test_rule *target;
940             struct cls_cursor cursor;
941
942             target = clone_rule(tcls.rules[rand() % tcls.n_rules]);
943
944             cls_cursor_init(&cursor, &cls, &target->cls_rule);
945             CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cls_rule, &cursor) {
946                 classifier_remove(&cls, &rule->cls_rule);
947                 free_rule(rule);
948             }
949             tcls_delete_matches(&tcls, &target->cls_rule);
950             compare_classifiers(&cls, &tcls);
951             check_tables(&cls, -1, -1, -1);
952             free_rule(target);
953         }
954
955         destroy_classifier(&cls);
956         tcls_destroy(&tcls);
957     }
958 }
959
960 static void
961 test_many_rules_in_two_tables(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
962 {
963     test_many_rules_in_n_tables(2);
964 }
965
966 static void
967 test_many_rules_in_five_tables(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
968 {
969     test_many_rules_in_n_tables(5);
970 }
971 \f
972 /* Miniflow tests. */
973
974 static uint32_t
975 random_value(void)
976 {
977     static const uint32_t values[] =
978         { 0xffffffff, 0xaaaaaaaa, 0x55555555, 0x80000000,
979           0x00000001, 0xface0000, 0x00d00d1e, 0xdeadbeef };
980
981     return values[random_uint32() % ARRAY_SIZE(values)];
982 }
983
984 static bool
985 choose(unsigned int n, unsigned int *idxp)
986 {
987     if (*idxp < n) {
988         return true;
989     } else {
990         *idxp -= n;
991         return false;
992     }
993 }
994
995 static bool
996 init_consecutive_values(int n_consecutive, struct flow *flow,
997                         unsigned int *idxp)
998 {
999     uint32_t *flow_u32 = (uint32_t *) flow;
1000
1001     if (choose(FLOW_U32S - n_consecutive + 1, idxp)) {
1002         int i;
1003
1004         for (i = 0; i < n_consecutive; i++) {
1005             flow_u32[*idxp + i] = random_value();
1006         }
1007         return true;
1008     } else {
1009         return false;
1010     }
1011 }
1012
1013 static bool
1014 next_random_flow(struct flow *flow, unsigned int idx)
1015 {
1016     uint32_t *flow_u32 = (uint32_t *) flow;
1017     int i;
1018
1019     memset(flow, 0, sizeof *flow);
1020
1021     /* Empty flow. */
1022     if (choose(1, &idx)) {
1023         return true;
1024     }
1025
1026     /* All flows with a small number of consecutive nonzero values. */
1027     for (i = 1; i <= 4; i++) {
1028         if (init_consecutive_values(i, flow, &idx)) {
1029             return true;
1030         }
1031     }
1032
1033     /* All flows with a large number of consecutive nonzero values. */
1034     for (i = FLOW_U32S - 4; i <= FLOW_U32S; i++) {
1035         if (init_consecutive_values(i, flow, &idx)) {
1036             return true;
1037         }
1038     }
1039
1040     /* All flows with exactly two nonconsecutive nonzero values. */
1041     if (choose((FLOW_U32S - 1) * (FLOW_U32S - 2) / 2, &idx)) {
1042         int ofs1;
1043
1044         for (ofs1 = 0; ofs1 < FLOW_U32S - 2; ofs1++) {
1045             int ofs2;
1046
1047             for (ofs2 = ofs1 + 2; ofs2 < FLOW_U32S; ofs2++) {
1048                 if (choose(1, &idx)) {
1049                     flow_u32[ofs1] = random_value();
1050                     flow_u32[ofs2] = random_value();
1051                     return true;
1052                 }
1053             }
1054         }
1055         NOT_REACHED();
1056     }
1057
1058     /* 16 randomly chosen flows with N >= 3 nonzero values. */
1059     if (choose(16 * (FLOW_U32S - 4), &idx)) {
1060         int n = idx / 16 + 3;
1061         int i;
1062
1063         for (i = 0; i < n; i++) {
1064             flow_u32[i] = random_value();
1065         }
1066         shuffle_u32s(flow_u32, FLOW_U32S);
1067
1068         return true;
1069     }
1070
1071     return false;
1072 }
1073
1074 static void
1075 any_random_flow(struct flow *flow)
1076 {
1077     static unsigned int max;
1078     if (!max) {
1079         while (next_random_flow(flow, max)) {
1080             max++;
1081         }
1082     }
1083
1084     next_random_flow(flow, random_range(max));
1085 }
1086
1087 static void
1088 toggle_masked_flow_bits(struct flow *flow, const struct flow_wildcards *mask)
1089 {
1090     const uint32_t *mask_u32 = (const uint32_t *) &mask->masks;
1091     uint32_t *flow_u32 = (uint32_t *) flow;
1092     int i;
1093
1094     for (i = 0; i < FLOW_U32S; i++) {
1095         if (mask_u32[i] != 0) {
1096             uint32_t bit;
1097
1098             do {
1099                 bit = 1u << random_range(32);
1100             } while (!(bit & mask_u32[i]));
1101             flow_u32[i] ^= bit;
1102         }
1103     }
1104 }
1105
1106 static void
1107 wildcard_extra_bits(struct flow_wildcards *mask)
1108 {
1109     uint32_t *mask_u32 = (uint32_t *) &mask->masks;
1110     int i;
1111
1112     for (i = 0; i < FLOW_U32S; i++) {
1113         if (mask_u32[i] != 0) {
1114             uint32_t bit;
1115
1116             do {
1117                 bit = 1u << random_range(32);
1118             } while (!(bit & mask_u32[i]));
1119             mask_u32[i] &= ~bit;
1120         }
1121     }
1122 }
1123
1124 static void
1125 test_miniflow(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1126 {
1127     struct flow flow;
1128     unsigned int idx;
1129
1130     random_set_seed(0xb3faca38);
1131     for (idx = 0; next_random_flow(&flow, idx); idx++) {
1132         const uint32_t *flow_u32 = (const uint32_t *) &flow;
1133         struct miniflow miniflow, miniflow2, miniflow3;
1134         struct flow flow2, flow3;
1135         struct flow_wildcards mask;
1136         struct minimask minimask;
1137         int i;
1138
1139         /* Convert flow to miniflow. */
1140         miniflow_init(&miniflow, &flow);
1141
1142         /* Check that the flow equals its miniflow. */
1143         assert(miniflow_get_vid(&miniflow) == vlan_tci_to_vid(flow.vlan_tci));
1144         for (i = 0; i < FLOW_U32S; i++) {
1145             assert(miniflow_get(&miniflow, i) == flow_u32[i]);
1146         }
1147
1148         /* Check that the miniflow equals itself. */
1149         assert(miniflow_equal(&miniflow, &miniflow));
1150
1151         /* Convert miniflow back to flow and verify that it's the same. */
1152         miniflow_expand(&miniflow, &flow2);
1153         assert(flow_equal(&flow, &flow2));
1154
1155         /* Check that copying a miniflow works properly. */
1156         miniflow_clone(&miniflow2, &miniflow);
1157         assert(miniflow_equal(&miniflow, &miniflow2));
1158         assert(miniflow_hash(&miniflow, 0) == miniflow_hash(&miniflow2, 0));
1159         miniflow_expand(&miniflow2, &flow3);
1160         assert(flow_equal(&flow, &flow3));
1161
1162         /* Check that masked matches work as expected for identical flows and
1163          * miniflows. */
1164         do {
1165             next_random_flow(&mask.masks, 1);
1166         } while (flow_wildcards_is_catchall(&mask));
1167         minimask_init(&minimask, &mask);
1168         assert(minimask_is_catchall(&minimask)
1169                == flow_wildcards_is_catchall(&mask));
1170         assert(miniflow_equal_in_minimask(&miniflow, &miniflow2, &minimask));
1171         assert(miniflow_equal_flow_in_minimask(&miniflow, &flow2, &minimask));
1172         assert(miniflow_hash_in_minimask(&miniflow, &minimask, 0x12345678) ==
1173                flow_hash_in_minimask(&flow, &minimask, 0x12345678));
1174
1175         /* Check that masked matches work as expected for differing flows and
1176          * miniflows. */
1177         toggle_masked_flow_bits(&flow2, &mask);
1178         assert(!miniflow_equal_flow_in_minimask(&miniflow, &flow2, &minimask));
1179         miniflow_init(&miniflow3, &flow2);
1180         assert(!miniflow_equal_in_minimask(&miniflow, &miniflow3, &minimask));
1181
1182         /* Clean up. */
1183         miniflow_destroy(&miniflow);
1184         miniflow_destroy(&miniflow2);
1185         miniflow_destroy(&miniflow3);
1186         minimask_destroy(&minimask);
1187     }
1188 }
1189
1190 static void
1191 test_minimask_has_extra(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1192 {
1193     struct flow_wildcards catchall;
1194     struct minimask minicatchall;
1195     struct flow flow;
1196     unsigned int idx;
1197
1198     flow_wildcards_init_catchall(&catchall);
1199     minimask_init(&minicatchall, &catchall);
1200     assert(minimask_is_catchall(&minicatchall));
1201
1202     random_set_seed(0x2ec7905b);
1203     for (idx = 0; next_random_flow(&flow, idx); idx++) {
1204         struct flow_wildcards mask;
1205         struct minimask minimask;
1206
1207         mask.masks = flow;
1208         minimask_init(&minimask, &mask);
1209         assert(!minimask_has_extra(&minimask, &minimask));
1210         assert(minimask_has_extra(&minicatchall, &minimask)
1211                == !minimask_is_catchall(&minimask));
1212         if (!minimask_is_catchall(&minimask)) {
1213             struct minimask minimask2;
1214
1215             wildcard_extra_bits(&mask);
1216             minimask_init(&minimask2, &mask);
1217             assert(minimask_has_extra(&minimask2, &minimask));
1218             assert(!minimask_has_extra(&minimask, &minimask2));
1219             minimask_destroy(&minimask2);
1220         }
1221
1222         minimask_destroy(&minimask);
1223     }
1224 }
1225
1226 static void
1227 test_minimask_combine(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1228 {
1229     struct flow_wildcards catchall;
1230     struct minimask minicatchall;
1231     struct flow flow;
1232     unsigned int idx;
1233
1234     flow_wildcards_init_catchall(&catchall);
1235     minimask_init(&minicatchall, &catchall);
1236     assert(minimask_is_catchall(&minicatchall));
1237
1238     random_set_seed(0x181bf0cd);
1239     for (idx = 0; next_random_flow(&flow, idx); idx++) {
1240         struct minimask minimask, minimask2, minicombined;
1241         struct flow_wildcards mask, mask2, combined, combined2;
1242         uint32_t storage[FLOW_U32S];
1243         struct flow flow2;
1244
1245         mask.masks = flow;
1246         minimask_init(&minimask, &mask);
1247
1248         minimask_combine(&minicombined, &minimask, &minicatchall, storage);
1249         assert(minimask_is_catchall(&minicombined));
1250
1251         any_random_flow(&flow2);
1252         mask2.masks = flow2;
1253         minimask_init(&minimask2, &mask2);
1254
1255         minimask_combine(&minicombined, &minimask, &minimask2, storage);
1256         flow_wildcards_combine(&combined, &mask, &mask2);
1257         minimask_expand(&minicombined, &combined2);
1258         assert(flow_wildcards_equal(&combined, &combined2));
1259
1260         minimask_destroy(&minimask);
1261         minimask_destroy(&minimask2);
1262     }
1263 }
1264 \f
1265 static const struct command commands[] = {
1266     /* Classifier tests. */
1267     {"empty", 0, 0, test_empty},
1268     {"destroy-null", 0, 0, test_destroy_null},
1269     {"single-rule", 0, 0, test_single_rule},
1270     {"rule-replacement", 0, 0, test_rule_replacement},
1271     {"many-rules-in-one-list", 0, 0, test_many_rules_in_one_list},
1272     {"many-rules-in-one-table", 0, 0, test_many_rules_in_one_table},
1273     {"many-rules-in-two-tables", 0, 0, test_many_rules_in_two_tables},
1274     {"many-rules-in-five-tables", 0, 0, test_many_rules_in_five_tables},
1275
1276     /* Miniflow and minimask tests. */
1277     {"miniflow", 0, 0, test_miniflow},
1278         {"minimask_has_extra", 0, 0, test_minimask_has_extra},
1279         {"minimask_combine", 0, 0, test_minimask_combine},
1280
1281     {NULL, 0, 0, NULL},
1282 };
1283
1284 int
1285 main(int argc, char *argv[])
1286 {
1287     set_program_name(argv[0]);
1288     init_values();
1289     run_command(argc - 1, argv + 1, commands);
1290     return 0;
1291 }