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