Prepend "nw_" to "frag" and "tos" elements.
[sliver-openvswitch.git] / tests / test-classifier.c
1 /*
2  * Copyright (c) 2009, 2010, 2011 Nicira Networks.
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     /*        FWW_* bit(s)                member name  name     */  \
46     /*        --------------------------  -----------  -------- */  \
47     CLS_FIELD(0,                          tun_id,      TUN_ID)      \
48     CLS_FIELD(0,                          nw_src,      NW_SRC)      \
49     CLS_FIELD(0,                          nw_dst,      NW_DST)      \
50     CLS_FIELD(FWW_IN_PORT,                in_port,     IN_PORT)     \
51     CLS_FIELD(0,                          vlan_tci,    VLAN_TCI)    \
52     CLS_FIELD(FWW_DL_TYPE,                dl_type,     DL_TYPE)     \
53     CLS_FIELD(FWW_TP_SRC,                 tp_src,      TP_SRC)      \
54     CLS_FIELD(FWW_TP_DST,                 tp_dst,      TP_DST)      \
55     CLS_FIELD(FWW_DL_SRC,                 dl_src,      DL_SRC)      \
56     CLS_FIELD(FWW_DL_DST | FWW_ETH_MCAST, dl_dst,      DL_DST)      \
57     CLS_FIELD(FWW_NW_PROTO,               nw_proto,    NW_PROTO)    \
58     CLS_FIELD(0,                          nw_tos,      NW_TOS)
59
60 /* Field indexes.
61  *
62  * (These are also indexed into struct classifier's 'tables' array.) */
63 enum {
64 #define CLS_FIELD(WILDCARDS, MEMBER, NAME) CLS_F_IDX_##NAME,
65     CLS_FIELDS
66 #undef CLS_FIELD
67     CLS_N_FIELDS
68 };
69
70 /* Field information. */
71 struct cls_field {
72     int ofs;                    /* Offset in struct flow. */
73     int len;                    /* Length in bytes. */
74     flow_wildcards_t wildcards; /* FWW_* bit or bits for this field. */
75     const char *name;           /* Name (for debugging). */
76 };
77
78 static const struct cls_field cls_fields[CLS_N_FIELDS] = {
79 #define CLS_FIELD(WILDCARDS, MEMBER, NAME)      \
80     { offsetof(struct flow, MEMBER),            \
81       sizeof ((struct flow *)0)->MEMBER,        \
82       WILDCARDS,                                \
83       #NAME },
84     CLS_FIELDS
85 #undef CLS_FIELD
86 };
87
88 struct test_rule {
89     int aux;                    /* Auxiliary data. */
90     struct cls_rule cls_rule;   /* Classifier rule data. */
91 };
92
93 static struct test_rule *
94 test_rule_from_cls_rule(const struct cls_rule *rule)
95 {
96     return rule ? CONTAINER_OF(rule, struct test_rule, cls_rule) : NULL;
97 }
98
99 /* Trivial (linear) classifier. */
100 struct tcls {
101     size_t n_rules;
102     size_t allocated_rules;
103     struct test_rule **rules;
104 };
105
106 static void
107 tcls_init(struct tcls *tcls)
108 {
109     tcls->n_rules = 0;
110     tcls->allocated_rules = 0;
111     tcls->rules = NULL;
112 }
113
114 static void
115 tcls_destroy(struct tcls *tcls)
116 {
117     if (tcls) {
118         size_t i;
119
120         for (i = 0; i < tcls->n_rules; i++) {
121             free(tcls->rules[i]);
122         }
123         free(tcls->rules);
124     }
125 }
126
127 static bool
128 tcls_is_empty(const struct tcls *tcls)
129 {
130     return tcls->n_rules == 0;
131 }
132
133 static struct test_rule *
134 tcls_insert(struct tcls *tcls, const struct test_rule *rule)
135 {
136     size_t i;
137
138     assert(!flow_wildcards_is_exact(&rule->cls_rule.wc)
139            || rule->cls_rule.priority == UINT_MAX);
140     for (i = 0; i < tcls->n_rules; i++) {
141         const struct cls_rule *pos = &tcls->rules[i]->cls_rule;
142         if (cls_rule_equal(pos, &rule->cls_rule)) {
143             /* Exact match. */
144             free(tcls->rules[i]);
145             tcls->rules[i] = xmemdup(rule, sizeof *rule);
146             return tcls->rules[i];
147         } else if (pos->priority < rule->cls_rule.priority) {
148             break;
149         }
150     }
151
152     if (tcls->n_rules >= tcls->allocated_rules) {
153         tcls->rules = x2nrealloc(tcls->rules, &tcls->allocated_rules,
154                                  sizeof *tcls->rules);
155     }
156     if (i != tcls->n_rules) {
157         memmove(&tcls->rules[i + 1], &tcls->rules[i],
158                 sizeof *tcls->rules * (tcls->n_rules - i));
159     }
160     tcls->rules[i] = xmemdup(rule, sizeof *rule);
161     tcls->n_rules++;
162     return tcls->rules[i];
163 }
164
165 static void
166 tcls_remove(struct tcls *cls, const struct test_rule *rule)
167 {
168     size_t i;
169
170     for (i = 0; i < cls->n_rules; i++) {
171         struct test_rule *pos = cls->rules[i];
172         if (pos == rule) {
173             free(pos);
174             memmove(&cls->rules[i], &cls->rules[i + 1],
175                     sizeof *cls->rules * (cls->n_rules - i - 1));
176             cls->n_rules--;
177             return;
178         }
179     }
180     NOT_REACHED();
181 }
182
183 static bool
184 match(const struct cls_rule *wild, const struct flow *fixed)
185 {
186     int f_idx;
187
188     for (f_idx = 0; f_idx < CLS_N_FIELDS; f_idx++) {
189         const struct cls_field *f = &cls_fields[f_idx];
190         bool eq;
191
192         if (f->wildcards) {
193             void *wild_field = (char *) &wild->flow + f->ofs;
194             void *fixed_field = (char *) fixed + f->ofs;
195             eq = ((wild->wc.wildcards & f->wildcards) == f->wildcards
196                   || !memcmp(wild_field, fixed_field, f->len));
197         } else if (f_idx == CLS_F_IDX_NW_SRC) {
198             eq = !((fixed->nw_src ^ wild->flow.nw_src) & wild->wc.nw_src_mask);
199         } else if (f_idx == CLS_F_IDX_NW_DST) {
200             eq = !((fixed->nw_dst ^ wild->flow.nw_dst) & wild->wc.nw_dst_mask);
201         } else if (f_idx == CLS_F_IDX_VLAN_TCI) {
202             eq = !((fixed->vlan_tci ^ wild->flow.vlan_tci)
203                    & wild->wc.vlan_tci_mask);
204         } else if (f_idx == CLS_F_IDX_TUN_ID) {
205             eq = !((fixed->tun_id ^ wild->flow.tun_id) & wild->wc.tun_id_mask);
206         } else if (f_idx == CLS_F_IDX_NW_TOS) {
207             eq = !((fixed->nw_tos ^ wild->flow.nw_tos)
208                    & wild->wc.nw_tos_mask);
209         } else {
210             NOT_REACHED();
211         }
212
213         if (!eq) {
214             return false;
215         }
216     }
217     return true;
218 }
219
220 static struct cls_rule *
221 tcls_lookup(const struct tcls *cls, const struct flow *flow)
222 {
223     size_t i;
224
225     for (i = 0; i < cls->n_rules; i++) {
226         struct test_rule *pos = cls->rules[i];
227         if (match(&pos->cls_rule, flow)) {
228             return &pos->cls_rule;
229         }
230     }
231     return NULL;
232 }
233
234 static void
235 tcls_delete_matches(struct tcls *cls, const struct cls_rule *target)
236 {
237     size_t i;
238
239     for (i = 0; i < cls->n_rules; ) {
240         struct test_rule *pos = cls->rules[i];
241         if (!flow_wildcards_has_extra(&pos->cls_rule.wc, &target->wc)
242             && match(target, &pos->cls_rule.flow)) {
243             tcls_remove(cls, pos);
244         } else {
245             i++;
246         }
247     }
248 }
249 \f
250 static ovs_be32 nw_src_values[] = { CONSTANT_HTONL(0xc0a80001),
251                                     CONSTANT_HTONL(0xc0a04455) };
252 static ovs_be32 nw_dst_values[] = { CONSTANT_HTONL(0xc0a80002),
253                                     CONSTANT_HTONL(0xc0a04455) };
254 static ovs_be64 tun_id_values[] = {
255     0,
256     CONSTANT_HTONLL(UINT64_C(0xfedcba9876543210)) };
257 static uint16_t in_port_values[] = { 1, OFPP_LOCAL };
258 static ovs_be16 vlan_tci_values[] = { CONSTANT_HTONS(101), CONSTANT_HTONS(0) };
259 static ovs_be16 dl_type_values[]
260             = { CONSTANT_HTONS(ETH_TYPE_IP), CONSTANT_HTONS(ETH_TYPE_ARP) };
261 static ovs_be16 tp_src_values[] = { CONSTANT_HTONS(49362),
262                                     CONSTANT_HTONS(80) };
263 static ovs_be16 tp_dst_values[] = { CONSTANT_HTONS(6667), CONSTANT_HTONS(22) };
264 static uint8_t dl_src_values[][6] = { { 0x00, 0x02, 0xe3, 0x0f, 0x80, 0xa4 },
265                                       { 0x5e, 0x33, 0x7f, 0x5f, 0x1e, 0x99 } };
266 static uint8_t dl_dst_values[][6] = { { 0x4a, 0x27, 0x71, 0xae, 0x64, 0xc1 },
267                                       { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } };
268 static uint8_t nw_proto_values[] = { IPPROTO_TCP, IPPROTO_ICMP };
269 static uint8_t nw_tos_values[] = { 48, 0 };
270
271 static void *values[CLS_N_FIELDS][2];
272
273 static void
274 init_values(void)
275 {
276     values[CLS_F_IDX_TUN_ID][0] = &tun_id_values[0];
277     values[CLS_F_IDX_TUN_ID][1] = &tun_id_values[1];
278
279     values[CLS_F_IDX_IN_PORT][0] = &in_port_values[0];
280     values[CLS_F_IDX_IN_PORT][1] = &in_port_values[1];
281
282     values[CLS_F_IDX_VLAN_TCI][0] = &vlan_tci_values[0];
283     values[CLS_F_IDX_VLAN_TCI][1] = &vlan_tci_values[1];
284
285     values[CLS_F_IDX_DL_SRC][0] = dl_src_values[0];
286     values[CLS_F_IDX_DL_SRC][1] = dl_src_values[1];
287
288     values[CLS_F_IDX_DL_DST][0] = dl_dst_values[0];
289     values[CLS_F_IDX_DL_DST][1] = dl_dst_values[1];
290
291     values[CLS_F_IDX_DL_TYPE][0] = &dl_type_values[0];
292     values[CLS_F_IDX_DL_TYPE][1] = &dl_type_values[1];
293
294     values[CLS_F_IDX_NW_SRC][0] = &nw_src_values[0];
295     values[CLS_F_IDX_NW_SRC][1] = &nw_src_values[1];
296
297     values[CLS_F_IDX_NW_DST][0] = &nw_dst_values[0];
298     values[CLS_F_IDX_NW_DST][1] = &nw_dst_values[1];
299
300     values[CLS_F_IDX_NW_PROTO][0] = &nw_proto_values[0];
301     values[CLS_F_IDX_NW_PROTO][1] = &nw_proto_values[1];
302
303     values[CLS_F_IDX_NW_TOS][0] = &nw_tos_values[0];
304     values[CLS_F_IDX_NW_TOS][1] = &nw_tos_values[1];
305
306     values[CLS_F_IDX_TP_SRC][0] = &tp_src_values[0];
307     values[CLS_F_IDX_TP_SRC][1] = &tp_src_values[1];
308
309     values[CLS_F_IDX_TP_DST][0] = &tp_dst_values[0];
310     values[CLS_F_IDX_TP_DST][1] = &tp_dst_values[1];
311 }
312
313 #define N_NW_SRC_VALUES ARRAY_SIZE(nw_src_values)
314 #define N_NW_DST_VALUES ARRAY_SIZE(nw_dst_values)
315 #define N_TUN_ID_VALUES ARRAY_SIZE(tun_id_values)
316 #define N_IN_PORT_VALUES ARRAY_SIZE(in_port_values)
317 #define N_VLAN_TCI_VALUES ARRAY_SIZE(vlan_tci_values)
318 #define N_DL_TYPE_VALUES ARRAY_SIZE(dl_type_values)
319 #define N_TP_SRC_VALUES ARRAY_SIZE(tp_src_values)
320 #define N_TP_DST_VALUES ARRAY_SIZE(tp_dst_values)
321 #define N_DL_SRC_VALUES ARRAY_SIZE(dl_src_values)
322 #define N_DL_DST_VALUES ARRAY_SIZE(dl_dst_values)
323 #define N_NW_PROTO_VALUES ARRAY_SIZE(nw_proto_values)
324 #define N_NW_TOS_VALUES ARRAY_SIZE(nw_tos_values)
325
326 #define N_FLOW_VALUES (N_NW_SRC_VALUES *        \
327                        N_NW_DST_VALUES *        \
328                        N_TUN_ID_VALUES *        \
329                        N_IN_PORT_VALUES *       \
330                        N_VLAN_TCI_VALUES *       \
331                        N_DL_TYPE_VALUES *       \
332                        N_TP_SRC_VALUES *        \
333                        N_TP_DST_VALUES *        \
334                        N_DL_SRC_VALUES *        \
335                        N_DL_DST_VALUES *        \
336                        N_NW_PROTO_VALUES *      \
337                        N_NW_TOS_VALUES)
338
339 static unsigned int
340 get_value(unsigned int *x, unsigned n_values)
341 {
342     unsigned int rem = *x % n_values;
343     *x /= n_values;
344     return rem;
345 }
346
347 static void
348 compare_classifiers(struct classifier *cls, struct tcls *tcls)
349 {
350     static const int confidence = 500;
351     unsigned int i;
352
353     assert(classifier_count(cls) == tcls->n_rules);
354     for (i = 0; i < confidence; i++) {
355         struct cls_rule *cr0, *cr1;
356         struct flow flow;
357         unsigned int x;
358
359         x = rand () % N_FLOW_VALUES;
360         flow.nw_src = nw_src_values[get_value(&x, N_NW_SRC_VALUES)];
361         flow.nw_dst = nw_dst_values[get_value(&x, N_NW_DST_VALUES)];
362         flow.tun_id = tun_id_values[get_value(&x, N_TUN_ID_VALUES)];
363         flow.in_port = in_port_values[get_value(&x, N_IN_PORT_VALUES)];
364         flow.vlan_tci = vlan_tci_values[get_value(&x, N_VLAN_TCI_VALUES)];
365         flow.dl_type = dl_type_values[get_value(&x, N_DL_TYPE_VALUES)];
366         flow.tp_src = tp_src_values[get_value(&x, N_TP_SRC_VALUES)];
367         flow.tp_dst = tp_dst_values[get_value(&x, N_TP_DST_VALUES)];
368         memcpy(flow.dl_src, dl_src_values[get_value(&x, N_DL_SRC_VALUES)],
369                ETH_ADDR_LEN);
370         memcpy(flow.dl_dst, dl_dst_values[get_value(&x, N_DL_DST_VALUES)],
371                ETH_ADDR_LEN);
372         flow.nw_proto = nw_proto_values[get_value(&x, N_NW_PROTO_VALUES)];
373         flow.nw_tos = nw_tos_values[get_value(&x, N_NW_TOS_VALUES)];
374
375         cr0 = classifier_lookup(cls, &flow);
376         cr1 = tcls_lookup(tcls, &flow);
377         assert((cr0 == NULL) == (cr1 == NULL));
378         if (cr0 != NULL) {
379             const struct test_rule *tr0 = test_rule_from_cls_rule(cr0);
380             const struct test_rule *tr1 = test_rule_from_cls_rule(cr1);
381
382             assert(cls_rule_equal(cr0, cr1));
383             assert(tr0->aux == tr1->aux);
384         }
385     }
386 }
387
388 static void
389 destroy_classifier(struct classifier *cls)
390 {
391     struct test_rule *rule, *next_rule;
392     struct cls_cursor cursor;
393
394     cls_cursor_init(&cursor, cls, NULL);
395     CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cls_rule, &cursor) {
396         classifier_remove(cls, &rule->cls_rule);
397         free(rule);
398     }
399     classifier_destroy(cls);
400 }
401
402 static void
403 check_tables(const struct classifier *cls,
404              int n_tables, int n_rules, int n_dups)
405 {
406     const struct cls_table *table;
407     struct test_rule *test_rule;
408     struct cls_cursor cursor;
409     int found_tables = 0;
410     int found_rules = 0;
411     int found_dups = 0;
412     int found_rules2 = 0;
413
414     HMAP_FOR_EACH (table, hmap_node, &cls->tables) {
415         const struct cls_rule *head;
416
417         assert(!hmap_is_empty(&table->rules));
418
419         found_tables++;
420         HMAP_FOR_EACH (head, hmap_node, &table->rules) {
421             unsigned int prev_priority = UINT_MAX;
422             const struct cls_rule *rule;
423
424             found_rules++;
425             LIST_FOR_EACH (rule, list, &head->list) {
426                 assert(rule->priority < prev_priority);
427                 prev_priority = rule->priority;
428                 found_rules++;
429                 found_dups++;
430                 assert(classifier_find_rule_exactly(cls, rule) == rule);
431             }
432         }
433     }
434
435     assert(found_tables == hmap_count(&cls->tables));
436     assert(n_tables == -1 || n_tables == hmap_count(&cls->tables));
437     assert(n_rules == -1 || found_rules == n_rules);
438     assert(n_dups == -1 || found_dups == n_dups);
439
440     cls_cursor_init(&cursor, cls, NULL);
441     CLS_CURSOR_FOR_EACH (test_rule, cls_rule, &cursor) {
442         found_rules2++;
443     }
444     assert(found_rules == found_rules2);
445 }
446
447 static struct test_rule *
448 make_rule(int wc_fields, unsigned int priority, int value_pat)
449 {
450     const struct cls_field *f;
451     struct test_rule *rule;
452
453     rule = xzalloc(sizeof *rule);
454     cls_rule_init_catchall(&rule->cls_rule, wc_fields ? priority : UINT_MAX);
455     for (f = &cls_fields[0]; f < &cls_fields[CLS_N_FIELDS]; f++) {
456         int f_idx = f - cls_fields;
457         int value_idx = (value_pat & (1u << f_idx)) != 0;
458         memcpy((char *) &rule->cls_rule.flow + f->ofs,
459                values[f_idx][value_idx], f->len);
460
461         if (f->wildcards) {
462             rule->cls_rule.wc.wildcards &= ~f->wildcards;
463         } else if (f_idx == CLS_F_IDX_NW_SRC) {
464             rule->cls_rule.wc.nw_src_mask = htonl(UINT32_MAX);
465         } else if (f_idx == CLS_F_IDX_NW_DST) {
466             rule->cls_rule.wc.nw_dst_mask = htonl(UINT32_MAX);
467         } else if (f_idx == CLS_F_IDX_VLAN_TCI) {
468             rule->cls_rule.wc.vlan_tci_mask = htons(UINT16_MAX);
469         } else if (f_idx == CLS_F_IDX_TUN_ID) {
470             rule->cls_rule.wc.tun_id_mask = htonll(UINT64_MAX);
471         } else if (f_idx == CLS_F_IDX_NW_TOS) {
472             rule->cls_rule.wc.nw_tos_mask = UINT8_MAX;
473         } else {
474             NOT_REACHED();
475         }
476     }
477     return rule;
478 }
479
480 static void
481 shuffle(unsigned int *p, size_t n)
482 {
483     for (; n > 1; n--, p++) {
484         unsigned int *q = &p[rand() % n];
485         unsigned int tmp = *p;
486         *p = *q;
487         *q = tmp;
488     }
489 }
490 \f
491 /* Tests an empty classifier. */
492 static void
493 test_empty(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
494 {
495     struct classifier cls;
496     struct tcls tcls;
497
498     classifier_init(&cls);
499     tcls_init(&tcls);
500     assert(classifier_is_empty(&cls));
501     assert(tcls_is_empty(&tcls));
502     compare_classifiers(&cls, &tcls);
503     classifier_destroy(&cls);
504     tcls_destroy(&tcls);
505 }
506
507 /* Destroys a null classifier. */
508 static void
509 test_destroy_null(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
510 {
511     classifier_destroy(NULL);
512 }
513
514 /* Tests classification with one rule at a time. */
515 static void
516 test_single_rule(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
517 {
518     unsigned int wc_fields;     /* Hilarious. */
519
520     for (wc_fields = 0; wc_fields < (1u << CLS_N_FIELDS); wc_fields++) {
521         struct classifier cls;
522         struct test_rule *rule, *tcls_rule;
523         struct tcls tcls;
524
525         rule = make_rule(wc_fields,
526                          hash_bytes(&wc_fields, sizeof wc_fields, 0), 0);
527
528         classifier_init(&cls);
529         tcls_init(&tcls);
530
531         tcls_rule = tcls_insert(&tcls, rule);
532         classifier_insert(&cls, &rule->cls_rule);
533         check_tables(&cls, 1, 1, 0);
534         compare_classifiers(&cls, &tcls);
535
536         classifier_remove(&cls, &rule->cls_rule);
537         tcls_remove(&tcls, tcls_rule);
538         assert(classifier_is_empty(&cls));
539         assert(tcls_is_empty(&tcls));
540         compare_classifiers(&cls, &tcls);
541
542         free(rule);
543         classifier_destroy(&cls);
544         tcls_destroy(&tcls);
545     }
546 }
547
548 /* Tests replacing one rule by another. */
549 static void
550 test_rule_replacement(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
551 {
552     unsigned int wc_fields;
553
554     for (wc_fields = 0; wc_fields < (1u << CLS_N_FIELDS); wc_fields++) {
555         struct classifier cls;
556         struct test_rule *rule1;
557         struct test_rule *rule2;
558         struct tcls tcls;
559
560         rule1 = make_rule(wc_fields, OFP_DEFAULT_PRIORITY, UINT_MAX);
561         rule2 = make_rule(wc_fields, OFP_DEFAULT_PRIORITY, UINT_MAX);
562         rule2->aux += 5;
563         rule2->aux += 5;
564
565         classifier_init(&cls);
566         tcls_init(&tcls);
567         tcls_insert(&tcls, rule1);
568         classifier_insert(&cls, &rule1->cls_rule);
569         check_tables(&cls, 1, 1, 0);
570         compare_classifiers(&cls, &tcls);
571         tcls_destroy(&tcls);
572
573         tcls_init(&tcls);
574         tcls_insert(&tcls, rule2);
575         assert(test_rule_from_cls_rule(
576                    classifier_replace(&cls, &rule2->cls_rule)) == rule1);
577         free(rule1);
578         check_tables(&cls, 1, 1, 0);
579         compare_classifiers(&cls, &tcls);
580         tcls_destroy(&tcls);
581         destroy_classifier(&cls);
582     }
583 }
584
585 static int
586 factorial(int n_items)
587 {
588     int n, i;
589
590     n = 1;
591     for (i = 2; i <= n_items; i++) {
592         n *= i;
593     }
594     return n;
595 }
596
597 static void
598 swap(int *a, int *b)
599 {
600     int tmp = *a;
601     *a = *b;
602     *b = tmp;
603 }
604
605 static void
606 reverse(int *a, int n)
607 {
608     int i;
609
610     for (i = 0; i < n / 2; i++) {
611         int j = n - (i + 1);
612         swap(&a[i], &a[j]);
613     }
614 }
615
616 static bool
617 next_permutation(int *a, int n)
618 {
619     int k;
620
621     for (k = n - 2; k >= 0; k--) {
622         if (a[k] < a[k + 1]) {
623             int l;
624
625             for (l = n - 1; ; l--) {
626                 if (a[l] > a[k]) {
627                     swap(&a[k], &a[l]);
628                     reverse(a + (k + 1), n - (k + 1));
629                     return true;
630                 }
631             }
632         }
633     }
634     return false;
635 }
636
637 /* Tests classification with rules that have the same matching criteria. */
638 static void
639 test_many_rules_in_one_list (int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
640 {
641     enum { N_RULES = 3 };
642     int n_pris;
643
644     for (n_pris = N_RULES; n_pris >= 1; n_pris--) {
645         int ops[N_RULES * 2];
646         int pris[N_RULES];
647         int n_permutations;
648         int i;
649
650         pris[0] = 0;
651         for (i = 1; i < N_RULES; i++) {
652             pris[i] = pris[i - 1] + (n_pris > i);
653         }
654
655         for (i = 0; i < N_RULES * 2; i++) {
656             ops[i] = i / 2;
657         }
658
659         n_permutations = 0;
660         do {
661             struct test_rule *rules[N_RULES];
662             struct test_rule *tcls_rules[N_RULES];
663             int pri_rules[N_RULES];
664             struct classifier cls;
665             struct tcls tcls;
666
667             n_permutations++;
668
669             for (i = 0; i < N_RULES; i++) {
670                 rules[i] = make_rule(456, pris[i], 0);
671                 tcls_rules[i] = NULL;
672                 pri_rules[i] = -1;
673             }
674
675             classifier_init(&cls);
676             tcls_init(&tcls);
677
678             for (i = 0; i < ARRAY_SIZE(ops); i++) {
679                 int j = ops[i];
680                 int m, n;
681
682                 if (!tcls_rules[j]) {
683                     struct test_rule *displaced_rule;
684
685                     tcls_rules[j] = tcls_insert(&tcls, rules[j]);
686                     displaced_rule = test_rule_from_cls_rule(
687                         classifier_replace(&cls, &rules[j]->cls_rule));
688                     if (pri_rules[pris[j]] >= 0) {
689                         int k = pri_rules[pris[j]];
690                         assert(displaced_rule != NULL);
691                         assert(displaced_rule != rules[j]);
692                         assert(pris[j] == displaced_rule->cls_rule.priority);
693                         tcls_rules[k] = NULL;
694                     } else {
695                         assert(displaced_rule == NULL);
696                     }
697                     pri_rules[pris[j]] = j;
698                 } else {
699                     classifier_remove(&cls, &rules[j]->cls_rule);
700                     tcls_remove(&tcls, tcls_rules[j]);
701                     tcls_rules[j] = NULL;
702                     pri_rules[pris[j]] = -1;
703                 }
704
705                 n = 0;
706                 for (m = 0; m < N_RULES; m++) {
707                     n += tcls_rules[m] != NULL;
708                 }
709                 check_tables(&cls, n > 0, n, n - 1);
710
711                 compare_classifiers(&cls, &tcls);
712             }
713
714             classifier_destroy(&cls);
715             tcls_destroy(&tcls);
716
717             for (i = 0; i < N_RULES; i++) {
718                 free(rules[i]);
719             }
720         } while (next_permutation(ops, ARRAY_SIZE(ops)));
721         assert(n_permutations == (factorial(N_RULES * 2) >> N_RULES));
722     }
723 }
724
725 static int
726 count_ones(unsigned long int x)
727 {
728     int n = 0;
729
730     while (x) {
731         x &= x - 1;
732         n++;
733     }
734
735     return n;
736 }
737
738 static bool
739 array_contains(int *array, int n, int value)
740 {
741     int i;
742
743     for (i = 0; i < n; i++) {
744         if (array[i] == value) {
745             return true;
746         }
747     }
748
749     return false;
750 }
751
752 /* Tests classification with two rules at a time that fall into the same
753  * table but different lists. */
754 static void
755 test_many_rules_in_one_table(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
756 {
757     int iteration;
758
759     for (iteration = 0; iteration < 50; iteration++) {
760         enum { N_RULES = 20 };
761         struct test_rule *rules[N_RULES];
762         struct test_rule *tcls_rules[N_RULES];
763         struct classifier cls;
764         struct tcls tcls;
765         int value_pats[N_RULES];
766         int value_mask;
767         int wcf;
768         int i;
769
770         do {
771             wcf = rand() & ((1u << CLS_N_FIELDS) - 1);
772             value_mask = ~wcf & ((1u << CLS_N_FIELDS) - 1);
773         } while ((1 << count_ones(value_mask)) < N_RULES);
774
775         classifier_init(&cls);
776         tcls_init(&tcls);
777
778         for (i = 0; i < N_RULES; i++) {
779             unsigned int priority = rand();
780
781             do {
782                 value_pats[i] = rand() & value_mask;
783             } while (array_contains(value_pats, i, value_pats[i]));
784
785             rules[i] = make_rule(wcf, priority, value_pats[i]);
786             tcls_rules[i] = tcls_insert(&tcls, rules[i]);
787             classifier_insert(&cls, &rules[i]->cls_rule);
788
789             check_tables(&cls, 1, i + 1, 0);
790             compare_classifiers(&cls, &tcls);
791         }
792
793         for (i = 0; i < N_RULES; i++) {
794             tcls_remove(&tcls, tcls_rules[i]);
795             classifier_remove(&cls, &rules[i]->cls_rule);
796             free(rules[i]);
797
798             check_tables(&cls, i < N_RULES - 1, N_RULES - (i + 1), 0);
799             compare_classifiers(&cls, &tcls);
800         }
801
802         classifier_destroy(&cls);
803         tcls_destroy(&tcls);
804     }
805 }
806
807 /* Tests classification with many rules at a time that fall into random lists
808  * in 'n' tables. */
809 static void
810 test_many_rules_in_n_tables(int n_tables)
811 {
812     enum { MAX_RULES = 50 };
813     int wcfs[10];
814     int iteration;
815     int i;
816
817     assert(n_tables < 10);
818     for (i = 0; i < n_tables; i++) {
819         do {
820             wcfs[i] = rand() & ((1u << CLS_N_FIELDS) - 1);
821         } while (array_contains(wcfs, i, wcfs[i]));
822     }
823
824     for (iteration = 0; iteration < 30; iteration++) {
825         unsigned int priorities[MAX_RULES];
826         struct classifier cls;
827         struct tcls tcls;
828
829         srand(iteration);
830         for (i = 0; i < MAX_RULES; i++) {
831             priorities[i] = i * 129;
832         }
833         shuffle(priorities, ARRAY_SIZE(priorities));
834
835         classifier_init(&cls);
836         tcls_init(&tcls);
837
838         for (i = 0; i < MAX_RULES; i++) {
839             struct test_rule *rule;
840             unsigned int priority = priorities[i];
841             int wcf = wcfs[rand() % n_tables];
842             int value_pat = rand() & ((1u << CLS_N_FIELDS) - 1);
843             rule = make_rule(wcf, priority, value_pat);
844             tcls_insert(&tcls, rule);
845             classifier_insert(&cls, &rule->cls_rule);
846             check_tables(&cls, -1, i + 1, -1);
847             compare_classifiers(&cls, &tcls);
848         }
849
850         while (!classifier_is_empty(&cls)) {
851             struct test_rule *rule, *next_rule;
852             struct test_rule *target;
853             struct cls_cursor cursor;
854
855             target = xmemdup(tcls.rules[rand() % tcls.n_rules],
856                              sizeof(struct test_rule));
857
858             cls_cursor_init(&cursor, &cls, &target->cls_rule);
859             CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cls_rule, &cursor) {
860                 classifier_remove(&cls, &rule->cls_rule);
861                 free(rule);
862             }
863             tcls_delete_matches(&tcls, &target->cls_rule);
864             compare_classifiers(&cls, &tcls);
865             check_tables(&cls, -1, -1, -1);
866             free(target);
867         }
868
869         destroy_classifier(&cls);
870         tcls_destroy(&tcls);
871     }
872 }
873
874 static void
875 test_many_rules_in_two_tables(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
876 {
877     test_many_rules_in_n_tables(2);
878 }
879
880 static void
881 test_many_rules_in_five_tables(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
882 {
883     test_many_rules_in_n_tables(5);
884 }
885 \f
886 static const struct command commands[] = {
887     {"empty", 0, 0, test_empty},
888     {"destroy-null", 0, 0, test_destroy_null},
889     {"single-rule", 0, 0, test_single_rule},
890     {"rule-replacement", 0, 0, test_rule_replacement},
891     {"many-rules-in-one-list", 0, 0, test_many_rules_in_one_list},
892     {"many-rules-in-one-table", 0, 0, test_many_rules_in_one_table},
893     {"many-rules-in-two-tables", 0, 0, test_many_rules_in_two_tables},
894     {"many-rules-in-five-tables", 0, 0, test_many_rules_in_five_tables},
895     {NULL, 0, 0, NULL},
896 };
897
898 int
899 main(int argc, char *argv[])
900 {
901     set_program_name(argv[0]);
902     init_values();
903     run_command(argc - 1, argv + 1, commands);
904     return 0;
905 }