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