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