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