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