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