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