aboutsummaryrefslogtreecommitdiff
path: root/lib/classifier.c
blob: dab8f620fbb6622422c8e6a37cdcf604462aec14 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
/*
 * Copyright (c) 2009, 2010, 2011 Nicira Networks.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <config.h>
#include "classifier.h"
#include <assert.h>
#include <errno.h>
#include <netinet/in.h>
#include "byte-order.h"
#include "dynamic-string.h"
#include "flow.h"
#include "hash.h"
#include "odp-util.h"
#include "ofp-util.h"
#include "packets.h"

static struct cls_table *find_table(const struct classifier *,
                                    const struct flow_wildcards *);
static struct cls_table *insert_table(struct classifier *,
                                      const struct flow_wildcards *);

static void destroy_table(struct classifier *, struct cls_table *);

static struct cls_rule *find_match(const struct cls_table *,
                                   const struct flow *);
static struct cls_rule *find_equal(struct cls_table *, const struct flow *,
                                   uint32_t hash);
static struct cls_rule *insert_rule(struct cls_table *, struct cls_rule *);

static bool flow_equal_except(const struct flow *, const struct flow *,
                                const struct flow_wildcards *);

/* Iterates RULE over HEAD and all of the cls_rules on HEAD->list. */
#define FOR_EACH_RULE_IN_LIST(RULE, HEAD)                               \
    for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
#define FOR_EACH_RULE_IN_LIST_SAFE(RULE, NEXT, HEAD)                    \
    for ((RULE) = (HEAD);                                               \
         (RULE) != NULL && ((NEXT) = next_rule_in_list(RULE), true);    \
         (RULE) = (NEXT))

static struct cls_rule *next_rule_in_list__(struct cls_rule *);
static struct cls_rule *next_rule_in_list(struct cls_rule *);

/* Converts the flow in 'flow' into a cls_rule in 'rule', with the given
 * 'wildcards' and 'priority'. */
void
cls_rule_init(const struct flow *flow, const struct flow_wildcards *wildcards,
              unsigned int priority, struct cls_rule *rule)
{
    rule->flow = *flow;
    rule->wc = *wildcards;
    rule->priority = priority;
    cls_rule_zero_wildcarded_fields(rule);
}

/* Converts the flow in 'flow' into an exact-match cls_rule in 'rule', with the
 * given 'priority'.  (For OpenFlow 1.0, exact-match rule are always highest
 * priority, so 'priority' should be at least 65535.) */
void
cls_rule_init_exact(const struct flow *flow,
                    unsigned int priority, struct cls_rule *rule)
{
    rule->flow = *flow;
    rule->flow.priority = 0;
    flow_wildcards_init_exact(&rule->wc);
    rule->priority = priority;
}

/* Initializes 'rule' as a "catch-all" rule that matches every packet, with
 * priority 'priority'. */
void
cls_rule_init_catchall(struct cls_rule *rule, unsigned int priority)
{
    memset(&rule->flow, 0, sizeof rule->flow);
    flow_wildcards_init_catchall(&rule->wc);
    rule->priority = priority;
}

/* For each bit or field wildcarded in 'rule', sets the corresponding bit or
 * field in 'flow' to all-0-bits.  It is important to maintain this invariant
 * in a clr_rule that might be inserted into a classifier.
 *
 * It is never necessary to call this function directly for a cls_rule that is
 * initialized or modified only by cls_rule_*() functions.  It is useful to
 * restore the invariant in a cls_rule whose 'wc' member is modified by hand.
 */
void
cls_rule_zero_wildcarded_fields(struct cls_rule *rule)
{
    flow_zero_wildcards(&rule->flow, &rule->wc);
}

void
cls_rule_set_reg(struct cls_rule *rule, unsigned int reg_idx, uint32_t value)
{
    cls_rule_set_reg_masked(rule, reg_idx, value, UINT32_MAX);
}

void
cls_rule_set_reg_masked(struct cls_rule *rule, unsigned int reg_idx,
                        uint32_t value, uint32_t mask)
{
    assert(reg_idx < FLOW_N_REGS);
    flow_wildcards_set_reg_mask(&rule->wc, reg_idx, mask);
    rule->flow.regs[reg_idx] = value & mask;
}

void
cls_rule_set_tun_id(struct cls_rule *rule, ovs_be64 tun_id)
{
    cls_rule_set_tun_id_masked(rule, tun_id, htonll(UINT64_MAX));
}

void
cls_rule_set_tun_id_masked(struct cls_rule *rule,
                           ovs_be64 tun_id, ovs_be64 mask)
{
    rule->wc.tun_id_mask = mask;
    rule->flow.tun_id = tun_id & mask;
}

void
cls_rule_set_in_port(struct cls_rule *rule, uint16_t ofp_port)
{
    rule->wc.wildcards &= ~FWW_IN_PORT;
    rule->flow.in_port = ofp_port;
}

void
cls_rule_set_dl_type(struct cls_rule *rule, ovs_be16 dl_type)
{
    rule->wc.wildcards &= ~FWW_DL_TYPE;
    rule->flow.dl_type = dl_type;
}

void
cls_rule_set_dl_src(struct cls_rule *rule, const uint8_t dl_src[ETH_ADDR_LEN])
{
    rule->wc.wildcards &= ~FWW_DL_SRC;
    memcpy(rule->flow.dl_src, dl_src, ETH_ADDR_LEN);
}

/* Modifies 'rule' so that the Ethernet address must match 'dl_dst' exactly. */
void
cls_rule_set_dl_dst(struct cls_rule *rule, const uint8_t dl_dst[ETH_ADDR_LEN])
{
    rule->wc.wildcards &= ~(FWW_DL_DST | FWW_ETH_MCAST);
    memcpy(rule->flow.dl_dst, dl_dst, ETH_ADDR_LEN);
}

/* Modifies 'rule' so that the Ethernet address must match 'dl_dst' after each
 * byte is ANDed with the appropriate byte in 'mask'.
 *
 * This function will assert-fail if 'mask' is invalid.  Only 'mask' values
 * accepted by flow_wildcards_is_dl_dst_mask_valid() are allowed. */
void
cls_rule_set_dl_dst_masked(struct cls_rule *rule,
                           const uint8_t dl_dst[ETH_ADDR_LEN],
                           const uint8_t mask[ETH_ADDR_LEN])
{
    flow_wildcards_t *wc = &rule->wc.wildcards;
    size_t i;

    *wc = flow_wildcards_set_dl_dst_mask(*wc, mask);
    for (i = 0; i < ETH_ADDR_LEN; i++) {
        rule->flow.dl_dst[i] = dl_dst[i] & mask[i];
    }
}

void
cls_rule_set_dl_tci(struct cls_rule *rule, ovs_be16 tci)
{
    cls_rule_set_dl_tci_masked(rule, tci, htons(0xffff));
}

void
cls_rule_set_dl_tci_masked(struct cls_rule *rule, ovs_be16 tci, ovs_be16 mask)
{
    rule->flow.vlan_tci = tci & mask;
    rule->wc.vlan_tci_mask = mask;
}

/* Modifies 'rule' so that the VLAN VID is wildcarded.  If the PCP is already
 * wildcarded, then 'rule' will match a packet regardless of whether it has an
 * 802.1Q header or not. */
void
cls_rule_set_any_vid(struct cls_rule *rule)
{
    if (rule->wc.vlan_tci_mask & htons(VLAN_PCP_MASK)) {
        rule->wc.vlan_tci_mask &= ~htons(VLAN_VID_MASK);
        rule->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
    } else {
        cls_rule_set_dl_tci_masked(rule, htons(0), htons(0));
    }
}

/* Modifies 'rule' depending on 'dl_vlan':
 *
 *   - If 'dl_vlan' is htons(OFP_VLAN_NONE), makes 'rule' match only packets
 *     without an 802.1Q header.
 *
 *   - Otherwise, makes 'rule' match only packets with an 802.1Q header whose
 *     VID equals the low 12 bits of 'dl_vlan'.
 */
void
cls_rule_set_dl_vlan(struct cls_rule *rule, ovs_be16 dl_vlan)
{
    flow_set_vlan_vid(&rule->flow, dl_vlan);
    if (dl_vlan == htons(OFP_VLAN_NONE)) {
        rule->wc.vlan_tci_mask = htons(UINT16_MAX);
    } else {
        rule->wc.vlan_tci_mask |= htons(VLAN_VID_MASK | VLAN_CFI);
    }
}

/* Modifies 'rule' so that the VLAN PCP is wildcarded.  If the VID is already
 * wildcarded, then 'rule' will match a packet regardless of whether it has an
 * 802.1Q header or not. */
void
cls_rule_set_any_pcp(struct cls_rule *rule)
{
    if (rule->wc.vlan_tci_mask & htons(VLAN_VID_MASK)) {
        rule->wc.vlan_tci_mask &= ~htons(VLAN_PCP_MASK);
        rule->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
    } else {
        cls_rule_set_dl_tci_masked(rule, htons(0), htons(0));
    }
}

/* Modifies 'rule' so that it matches only packets with an 802.1Q header whose
 * PCP equals the low 3 bits of 'dl_vlan_pcp'. */
void
cls_rule_set_dl_vlan_pcp(struct cls_rule *rule, uint8_t dl_vlan_pcp)
{
    flow_set_vlan_pcp(&rule->flow, dl_vlan_pcp);
    rule->wc.vlan_tci_mask |= htons(VLAN_CFI | VLAN_PCP_MASK);
}

void
cls_rule_set_tp_src(struct cls_rule *rule, ovs_be16 tp_src)
{
    rule->wc.wildcards &= ~FWW_TP_SRC;
    rule->flow.tp_src = tp_src;
}

void
cls_rule_set_tp_dst(struct cls_rule *rule, ovs_be16 tp_dst)
{
    rule->wc.wildcards &= ~FWW_TP_DST;
    rule->flow.tp_dst = tp_dst;
}

void
cls_rule_set_nw_proto(struct cls_rule *rule, uint8_t nw_proto)
{
    rule->wc.wildcards &= ~FWW_NW_PROTO;
    rule->flow.nw_proto = nw_proto;
}

void
cls_rule_set_nw_src(struct cls_rule *rule, ovs_be32 nw_src)
{
    rule->flow.nw_src = nw_src;
    rule->wc.nw_src_mask = htonl(UINT32_MAX);
}

void
cls_rule_set_nw_src_masked(struct cls_rule *rule,
                           ovs_be32 nw_src, ovs_be32 mask)
{
    rule->flow.nw_src = nw_src & mask;
    rule->wc.nw_src_mask = mask;
}

void
cls_rule_set_nw_dst(struct cls_rule *rule, ovs_be32 nw_dst)
{
    rule->flow.nw_dst = nw_dst;
    rule->wc.nw_dst_mask = htonl(UINT32_MAX);
}

void
cls_rule_set_nw_dst_masked(struct cls_rule *rule, ovs_be32 ip, ovs_be32 mask)
{
    rule->flow.nw_dst = ip & mask;
    rule->wc.nw_dst_mask = mask;
}

void
cls_rule_set_nw_dscp(struct cls_rule *rule, uint8_t nw_dscp)
{
    rule->wc.wildcards &= ~FWW_NW_DSCP;
    rule->flow.nw_tos &= ~IP_DSCP_MASK;
    rule->flow.nw_tos |= nw_dscp & IP_DSCP_MASK;
}

void
cls_rule_set_nw_ecn(struct cls_rule *rule, uint8_t nw_ecn)
{
    rule->wc.wildcards &= ~FWW_NW_ECN;
    rule->flow.nw_tos &= ~IP_ECN_MASK;
    rule->flow.nw_tos |= nw_ecn & IP_ECN_MASK;
}

void
cls_rule_set_nw_ttl(struct cls_rule *rule, uint8_t nw_ttl)
{
    rule->wc.wildcards &= ~FWW_NW_TTL;
    rule->flow.nw_ttl = nw_ttl;
}

void
cls_rule_set_nw_frag(struct cls_rule *rule, uint8_t nw_frag)
{
    rule->wc.nw_frag_mask |= FLOW_NW_FRAG_MASK;
    rule->flow.nw_frag = nw_frag;
}

void
cls_rule_set_nw_frag_masked(struct cls_rule *rule,
                            uint8_t nw_frag, uint8_t mask)
{
    rule->flow.nw_frag = nw_frag & mask;
    rule->wc.nw_frag_mask = mask;
}

void
cls_rule_set_icmp_type(struct cls_rule *rule, uint8_t icmp_type)
{
    rule->wc.wildcards &= ~FWW_TP_SRC;
    rule->flow.tp_src = htons(icmp_type);
}

void
cls_rule_set_icmp_code(struct cls_rule *rule, uint8_t icmp_code)
{
    rule->wc.wildcards &= ~FWW_TP_DST;
    rule->flow.tp_dst = htons(icmp_code);
}

void
cls_rule_set_arp_sha(struct cls_rule *rule, const uint8_t sha[ETH_ADDR_LEN])
{
    rule->wc.wildcards &= ~FWW_ARP_SHA;
    memcpy(rule->flow.arp_sha, sha, ETH_ADDR_LEN);
}

void
cls_rule_set_arp_tha(struct cls_rule *rule, const uint8_t tha[ETH_ADDR_LEN])
{
    rule->wc.wildcards &= ~FWW_ARP_THA;
    memcpy(rule->flow.arp_tha, tha, ETH_ADDR_LEN);
}

void
cls_rule_set_ipv6_src(struct cls_rule *rule, const struct in6_addr *src)
{
    rule->flow.ipv6_src = *src;
    rule->wc.ipv6_src_mask = in6addr_exact;
}

void
cls_rule_set_ipv6_src_masked(struct cls_rule *rule, const struct in6_addr *src,
                             const struct in6_addr *mask)
{
    rule->flow.ipv6_src = ipv6_addr_bitand(src, mask);
    rule->wc.ipv6_src_mask = *mask;
}

void
cls_rule_set_ipv6_dst(struct cls_rule *rule, const struct in6_addr *dst)
{
    rule->flow.ipv6_dst = *dst;
    rule->wc.ipv6_dst_mask = in6addr_exact;
}

void
cls_rule_set_ipv6_dst_masked(struct cls_rule *rule, const struct in6_addr *dst,
                             const struct in6_addr *mask)
{
    rule->flow.ipv6_dst = ipv6_addr_bitand(dst, mask);
    rule->wc.ipv6_dst_mask = *mask;
}

void
cls_rule_set_ipv6_label(struct cls_rule *rule, ovs_be32 ipv6_label)
{
    rule->wc.wildcards &= ~FWW_IPV6_LABEL;
    rule->flow.ipv6_label = ipv6_label;
}

void
cls_rule_set_nd_target(struct cls_rule *rule, const struct in6_addr *target)
{
    rule->wc.wildcards &= ~FWW_ND_TARGET;
    rule->flow.nd_target = *target;
}

/* Returns true if 'a' and 'b' have the same priority, wildcard the same
 * fields, and have the same values for fixed fields, otherwise false. */
bool
cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
{
    return (a->priority == b->priority
            && flow_wildcards_equal(&a->wc, &b->wc)
            && flow_equal(&a->flow, &b->flow));
}

/* Returns a hash value for the flow, wildcards, and priority in 'rule',
 * starting from 'basis'. */
uint32_t
cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
{
    uint32_t h0 = flow_hash(&rule->flow, basis);
    uint32_t h1 = flow_wildcards_hash(&rule->wc, h0);
    return hash_int(rule->priority, h1);
}

static void
format_ip_netmask(struct ds *s, const char *name, ovs_be32 ip,
                  ovs_be32 netmask)
{
    if (netmask) {
        ds_put_format(s, "%s=", name);
        ip_format_masked(ip, netmask, s);
        ds_put_char(s, ',');
    }
}

static void
format_ipv6_netmask(struct ds *s, const char *name,
                    const struct in6_addr *addr,
                    const struct in6_addr *netmask)
{
    if (!ipv6_mask_is_any(netmask)) {
        ds_put_format(s, "%s=", name);
        print_ipv6_masked(s, addr, netmask);
        ds_put_char(s, ',');
    }
}

void
cls_rule_format(const struct cls_rule *rule, struct ds *s)
{
    const struct flow_wildcards *wc = &rule->wc;
    size_t start_len = s->length;
    flow_wildcards_t w = wc->wildcards;
    const struct flow *f = &rule->flow;
    bool skip_type = false;
    bool skip_proto = false;

    int i;

    BUILD_ASSERT_DECL(FLOW_WC_SEQ == 7);

    if (rule->priority != OFP_DEFAULT_PRIORITY) {
        ds_put_format(s, "priority=%d,", rule->priority);
    }

    if (!(w & FWW_DL_TYPE)) {
        skip_type = true;
        if (f->dl_type == htons(ETH_TYPE_IP)) {
            if (!(w & FWW_NW_PROTO)) {
                skip_proto = true;
                if (f->nw_proto == IPPROTO_ICMP) {
                    ds_put_cstr(s, "icmp,");
                } else if (f->nw_proto == IPPROTO_TCP) {
                    ds_put_cstr(s, "tcp,");
                } else if (f->nw_proto == IPPROTO_UDP) {
                    ds_put_cstr(s, "udp,");
                } else {
                    ds_put_cstr(s, "ip,");
                    skip_proto = false;
                }
            } else {
                ds_put_cstr(s, "ip,");
            }
        } else if (f->dl_type == htons(ETH_TYPE_IPV6)) {
            if (!(w & FWW_NW_PROTO)) {
                skip_proto = true;
                if (f->nw_proto == IPPROTO_ICMPV6) {
                    ds_put_cstr(s, "icmp6,");
                } else if (f->nw_proto == IPPROTO_TCP) {
                    ds_put_cstr(s, "tcp6,");
                } else if (f->nw_proto == IPPROTO_UDP) {
                    ds_put_cstr(s, "udp6,");
                } else {
                    ds_put_cstr(s, "ipv6,");
                    skip_proto = false;
                }
            } else {
                ds_put_cstr(s, "ipv6,");
            }
        } else if (f->dl_type == htons(ETH_TYPE_ARP)) {
            ds_put_cstr(s, "arp,");
        } else {
            skip_type = false;
        }
    }
    for (i = 0; i < FLOW_N_REGS; i++) {
        switch (wc->reg_masks[i]) {
        case 0:
            break;
        case UINT32_MAX:
            ds_put_format(s, "reg%d=0x%"PRIx32",", i, f->regs[i]);
            break;
        default:
            ds_put_format(s, "reg%d=0x%"PRIx32"/0x%"PRIx32",",
                          i, f->regs[i], wc->reg_masks[i]);
            break;
        }
    }
    switch (wc->tun_id_mask) {
    case 0:
        break;
    case CONSTANT_HTONLL(UINT64_MAX):
        ds_put_format(s, "tun_id=%#"PRIx64",", ntohll(f->tun_id));
        break;
    default:
        ds_put_format(s, "tun_id=%#"PRIx64"/%#"PRIx64",",
                      ntohll(f->tun_id), ntohll(wc->tun_id_mask));
        break;
    }
    if (!(w & FWW_IN_PORT)) {
        ds_put_format(s, "in_port=%"PRIu16",", f->in_port);
    }
    if (wc->vlan_tci_mask) {
        ovs_be16 vid_mask = wc->vlan_tci_mask & htons(VLAN_VID_MASK);
        ovs_be16 pcp_mask = wc->vlan_tci_mask & htons(VLAN_PCP_MASK);
        ovs_be16 cfi = wc->vlan_tci_mask & htons(VLAN_CFI);

        if (cfi && f->vlan_tci & htons(VLAN_CFI)
            && (!vid_mask || vid_mask == htons(VLAN_VID_MASK))
            && (!pcp_mask || pcp_mask == htons(VLAN_PCP_MASK))
            && (vid_mask || pcp_mask)) {
            if (vid_mask) {
                ds_put_format(s, "dl_vlan=%"PRIu16",",
                              vlan_tci_to_vid(f->vlan_tci));
            }
            if (pcp_mask) {
                ds_put_format(s, "dl_vlan_pcp=%d,",
                              vlan_tci_to_pcp(f->vlan_tci));
            }
        } else if (wc->vlan_tci_mask == htons(0xffff)) {
            ds_put_format(s, "vlan_tci=0x%04"PRIx16",", ntohs(f->vlan_tci));
        } else {
            ds_put_format(s, "vlan_tci=0x%04"PRIx16"/0x%04"PRIx16",",
                          ntohs(f->vlan_tci), ntohs(wc->vlan_tci_mask));
        }
    }
    if (!(w & FWW_DL_SRC)) {
        ds_put_format(s, "dl_src="ETH_ADDR_FMT",", ETH_ADDR_ARGS(f->dl_src));
    }
    switch (w & (FWW_DL_DST | FWW_ETH_MCAST)) {
    case 0:
        ds_put_format(s, "dl_dst="ETH_ADDR_FMT",", ETH_ADDR_ARGS(f->dl_dst));
        break;
    case FWW_DL_DST:
        ds_put_format(s, "dl_dst="ETH_ADDR_FMT"/01:00:00:00:00:00,",
                      ETH_ADDR_ARGS(f->dl_dst));
        break;
    case FWW_ETH_MCAST:
        ds_put_format(s, "dl_dst="ETH_ADDR_FMT"/fe:ff:ff:ff:ff:ff,",
                      ETH_ADDR_ARGS(f->dl_dst));
        break;
    case FWW_DL_DST | FWW_ETH_MCAST:
        break;
    }
    if (!skip_type && !(w & FWW_DL_TYPE)) {
        ds_put_format(s, "dl_type=0x%04"PRIx16",", ntohs(f->dl_type));
    }
    if (f->dl_type == htons(ETH_TYPE_IPV6)) {
        format_ipv6_netmask(s, "ipv6_src", &f->ipv6_src, &wc->ipv6_src_mask);
        format_ipv6_netmask(s, "ipv6_dst", &f->ipv6_dst, &wc->ipv6_dst_mask);
        if (!(w & FWW_IPV6_LABEL)) {
            ds_put_format(s, "ipv6_label=0x%05"PRIx32",", ntohl(f->ipv6_label));
        }
    } else {
        format_ip_netmask(s, "nw_src", f->nw_src, wc->nw_src_mask);
        format_ip_netmask(s, "nw_dst", f->nw_dst, wc->nw_dst_mask);
    }
    if (!skip_proto && !(w & FWW_NW_PROTO)) {
        if (f->dl_type == htons(ETH_TYPE_ARP)) {
            ds_put_format(s, "arp_op=%"PRIu8",", f->nw_proto);
        } else {
            ds_put_format(s, "nw_proto=%"PRIu8",", f->nw_proto);
        }
    }
    if (f->dl_type == htons(ETH_TYPE_ARP)) {
        if (!(w & FWW_ARP_SHA)) {
            ds_put_format(s, "arp_sha="ETH_ADDR_FMT",",
                    ETH_ADDR_ARGS(f->arp_sha));
        }
        if (!(w & FWW_ARP_THA)) {
            ds_put_format(s, "arp_tha="ETH_ADDR_FMT",",
                    ETH_ADDR_ARGS(f->arp_tha));
        }
    }
    if (!(w & FWW_NW_DSCP)) {
        ds_put_format(s, "nw_tos=%"PRIu8",", f->nw_tos & IP_DSCP_MASK);
    }
    if (!(w & FWW_NW_ECN)) {
        ds_put_format(s, "nw_ecn=%"PRIu8",", f->nw_tos & IP_ECN_MASK);
    }
    if (!(w & FWW_NW_TTL)) {
        ds_put_format(s, "nw_ttl=%"PRIu8",", f->nw_ttl);
    }
    switch (wc->nw_frag_mask) {
    case FLOW_NW_FRAG_ANY | FLOW_NW_FRAG_LATER:
        ds_put_format(s, "nw_frag=%s,",
                      f->nw_frag & FLOW_NW_FRAG_ANY
                      ? (f->nw_frag & FLOW_NW_FRAG_LATER ? "later" : "first")
                      : (f->nw_frag & FLOW_NW_FRAG_LATER ? "<error>" : "no"));
        break;

    case FLOW_NW_FRAG_ANY:
        ds_put_format(s, "nw_frag=%s,",
                      f->nw_frag & FLOW_NW_FRAG_ANY ? "yes" : "no");
        break;

    case FLOW_NW_FRAG_LATER:
        ds_put_format(s, "nw_frag=%s,",
                      f->nw_frag & FLOW_NW_FRAG_LATER ? "later" : "not_later");
        break;
    }
    if (f->nw_proto == IPPROTO_ICMP) {
        if (!(w & FWW_TP_SRC)) {
            ds_put_format(s, "icmp_type=%"PRIu16",", ntohs(f->tp_src));
        }
        if (!(w & FWW_TP_DST)) {
            ds_put_format(s, "icmp_code=%"PRIu16",", ntohs(f->tp_dst));
        }
    } else if (f->nw_proto == IPPROTO_ICMPV6) {
        if (!(w & FWW_TP_SRC)) {
            ds_put_format(s, "icmp_type=%"PRIu16",", ntohs(f->tp_src));
        }
        if (!(w & FWW_TP_DST)) {
            ds_put_format(s, "icmp_code=%"PRIu16",", ntohs(f->tp_dst));
        }
        if (!(w & FWW_ND_TARGET)) {
            ds_put_cstr(s, "nd_target=");
            print_ipv6_addr(s, &f->nd_target);
            ds_put_char(s, ',');
        }
        if (!(w & FWW_ARP_SHA)) {
            ds_put_format(s, "nd_sll="ETH_ADDR_FMT",",
                    ETH_ADDR_ARGS(f->arp_sha));
        }
        if (!(w & FWW_ARP_THA)) {
            ds_put_format(s, "nd_tll="ETH_ADDR_FMT",",
                    ETH_ADDR_ARGS(f->arp_tha));
        }
   } else {
        if (!(w & FWW_TP_SRC)) {
            ds_put_format(s, "tp_src=%"PRIu16",", ntohs(f->tp_src));
        }
        if (!(w & FWW_TP_DST)) {
            ds_put_format(s, "tp_dst=%"PRIu16",", ntohs(f->tp_dst));
        }
    }

    if (s->length > start_len && ds_last(s) == ',') {
        s->length--;
    }
}

/* Converts 'rule' to a string and returns the string.  The caller must free
 * the string (with free()). */
char *
cls_rule_to_string(const struct cls_rule *rule)
{
    struct ds s = DS_EMPTY_INITIALIZER;
    cls_rule_format(rule, &s);
    return ds_steal_cstr(&s);
}

void
cls_rule_print(const struct cls_rule *rule)
{
    char *s = cls_rule_to_string(rule);
    puts(s);
    free(s);
}

/* Initializes 'cls' as a classifier that initially contains no classification
 * rules. */
void
classifier_init(struct classifier *cls)
{
    cls->n_rules = 0;
    hmap_init(&cls->tables);
}

/* Destroys 'cls'.  Rules within 'cls', if any, are not freed; this is the
 * caller's responsibility. */
void
classifier_destroy(struct classifier *cls)
{
    if (cls) {
        struct cls_table *table, *next_table;

        HMAP_FOR_EACH_SAFE (table, next_table, hmap_node, &cls->tables) {
            hmap_destroy(&table->rules);
            hmap_remove(&cls->tables, &table->hmap_node);
            free(table);
        }
        hmap_destroy(&cls->tables);
    }
}

/* Returns true if 'cls' contains no classification rules, false otherwise. */
bool
classifier_is_empty(const struct classifier *cls)
{
    return cls->n_rules == 0;
}

/* Returns the number of rules in 'classifier'. */
int
classifier_count(const struct classifier *cls)
{
    return cls->n_rules;
}

/* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
 * must not modify or free it.
 *
 * If 'cls' already contains an identical rule (including wildcards, values of
 * fixed fields, and priority), replaces the old rule by 'rule' and returns the
 * rule that was replaced.  The caller takes ownership of the returned rule and
 * is thus responsible for freeing it, etc., as necessary.
 *
 * Returns NULL if 'cls' does not contain a rule with an identical key, after
 * inserting the new rule.  In this case, no rules are displaced by the new
 * rule, even rules that cannot have any effect because the new rule matches a
 * superset of their flows and has higher priority. */
struct cls_rule *
classifier_replace(struct classifier *cls, struct cls_rule *rule)
{
    struct cls_rule *old_rule;
    struct cls_table *table;

    table = find_table(cls, &rule->wc);
    if (!table) {
        table = insert_table(cls, &rule->wc);
    }

    old_rule = insert_rule(table, rule);
    if (!old_rule) {
        table->n_table_rules++;
        cls->n_rules++;
    }
    return old_rule;
}

/* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
 * must not modify or free it.
 *
 * 'cls' must not contain an identical rule (including wildcards, values of
 * fixed fields, and priority).  Use classifier_find_rule_exactly() to find
 * such a rule. */
void
classifier_insert(struct classifier *cls, struct cls_rule *rule)
{
    struct cls_rule *displaced_rule = classifier_replace(cls, rule);
    assert(!displaced_rule);
}

/* Removes 'rule' from 'cls'.  It is the caller's responsibility to free
 * 'rule', if this is desirable. */
void
classifier_remove(struct classifier *cls, struct cls_rule *rule)
{
    struct cls_rule *head;
    struct cls_table *table;

    table = find_table(cls, &rule->wc);
    head = find_equal(table, &rule->flow, rule->hmap_node.hash);
    if (head != rule) {
        list_remove(&rule->list);
    } else if (list_is_empty(&rule->list)) {
        hmap_remove(&table->rules, &rule->hmap_node);
    } else {
        struct cls_rule *next = CONTAINER_OF(rule->list.next,
                                             struct cls_rule, list);

        list_remove(&rule->list);
        hmap_replace(&table->rules, &rule->hmap_node, &next->hmap_node);
    }

    if (--table->n_table_rules == 0) {
        destroy_table(cls, table);
    }

    cls->n_rules--;
}

/* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
 * Returns a null pointer if no rules in 'cls' match 'flow'.  If multiple rules
 * of equal priority match 'flow', returns one arbitrarily. */
struct cls_rule *
classifier_lookup(const struct classifier *cls, const struct flow *flow)
{
    struct cls_table *table;
    struct cls_rule *best;

    best = NULL;
    HMAP_FOR_EACH (table, hmap_node, &cls->tables) {
        struct cls_rule *rule = find_match(table, flow);
        if (rule && (!best || rule->priority > best->priority)) {
            best = rule;
        }
    }
    return best;
}

/* Finds and returns a rule in 'cls' with exactly the same priority and
 * matching criteria as 'target'.  Returns a null pointer if 'cls' doesn't
 * contain an exact match. */
struct cls_rule *
classifier_find_rule_exactly(const struct classifier *cls,
                             const struct cls_rule *target)
{
    struct cls_rule *head, *rule;
    struct cls_table *table;

    table = find_table(cls, &target->wc);
    if (!table) {
        return NULL;
    }

    head = find_equal(table, &target->flow, flow_hash(&target->flow, 0));
    FOR_EACH_RULE_IN_LIST (rule, head) {
        if (target->priority >= rule->priority) {
            return target->priority == rule->priority ? rule : NULL;
        }
    }
    return NULL;
}

/* Checks if 'target' would overlap any other rule in 'cls'.  Two rules are
 * considered to overlap if both rules have the same priority and a packet
 * could match both. */
bool
classifier_rule_overlaps(const struct classifier *cls,
                         const struct cls_rule *target)
{
    struct cls_table *table;

    HMAP_FOR_EACH (table, hmap_node, &cls->tables) {
        struct flow_wildcards wc;
        struct cls_rule *head;

        flow_wildcards_combine(&wc, &target->wc, &table->wc);
        HMAP_FOR_EACH (head, hmap_node, &table->rules) {
            struct cls_rule *rule;

            FOR_EACH_RULE_IN_LIST (rule, head) {
                if (rule->priority == target->priority
                    && flow_equal_except(&target->flow, &rule->flow, &wc)) {
                    return true;
                }
            }
        }
    }

    return false;
}

/* Iteration. */

static bool
rule_matches(const struct cls_rule *rule, const struct cls_rule *target)
{
    return (!target
            || flow_equal_except(&rule->flow, &target->flow, &target->wc));
}

static struct cls_rule *
search_table(const struct cls_table *table, const struct cls_rule *target)
{
    if (!target || !flow_wildcards_has_extra(&table->wc, &target->wc)) {
        struct cls_rule *rule;

        HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
            if (rule_matches(rule, target)) {
                return rule;
            }
        }
    }
    return NULL;
}

/* Initializes 'cursor' for iterating through 'cls' rules that exactly match
 * 'target' or are more specific than 'target'.  That is, a given 'rule'
 * matches 'target' if, for every field:
 *
 *   - 'target' and 'rule' specify the same (non-wildcarded) value for the
 *     field, or
 *
 *   - 'target' wildcards the field,
 *
 * but not if:
 *
 *   - 'target' and 'rule' specify different values for the field, or
 *
 *   - 'target' specifies a value for the field but 'rule' wildcards it.
 *
 * Equivalently, the truth table for whether a field matches is:
 *
 *                                     rule
 *
 *                             wildcard    exact
 *                            +---------+---------+
 *                   t   wild |   yes   |   yes   |
 *                   a   card |         |         |
 *                   r        +---------+---------+
 *                   g  exact |    no   |if values|
 *                   e        |         |are equal|
 *                   t        +---------+---------+
 *
 * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
 * commands and by OpenFlow 1.0 aggregate and flow stats.
 *
 * Ignores target->priority.
 *
 * 'target' may be NULL to iterate over every rule in 'cls'. */
void
cls_cursor_init(struct cls_cursor *cursor, const struct classifier *cls,
                const struct cls_rule *target)
{
    cursor->cls = cls;
    cursor->target = target;
}

/* Returns the first matching cls_rule in 'cursor''s iteration, or a null
 * pointer if there are no matches. */
struct cls_rule *
cls_cursor_first(struct cls_cursor *cursor)
{
    struct cls_table *table;

    HMAP_FOR_EACH (table, hmap_node, &cursor->cls->tables) {
        struct cls_rule *rule = search_table(table, cursor->target);
        if (rule) {
            cursor->table = table;
            return rule;
        }
    }

    return NULL;
}

/* Returns the next matching cls_rule in 'cursor''s iteration, or a null
 * pointer if there are no more matches. */
struct cls_rule *
cls_cursor_next(struct cls_cursor *cursor, struct cls_rule *rule)
{
    const struct cls_table *table;
    struct cls_rule *next;

    next = next_rule_in_list__(rule);
    if (next->priority < rule->priority) {
        return next;
    }

    /* 'next' is the head of the list, that is, the rule that is included in
     * the table's hmap.  (This is important when the classifier contains rules
     * that differ only in priority.) */
    rule = next;
    HMAP_FOR_EACH_CONTINUE (rule, hmap_node, &cursor->table->rules) {
        if (rule_matches(rule, cursor->target)) {
            return rule;
        }
    }

    table = cursor->table;
    HMAP_FOR_EACH_CONTINUE (table, hmap_node, &cursor->cls->tables) {
        rule = search_table(table, cursor->target);
        if (rule) {
            cursor->table = table;
            return rule;
        }
    }

    return NULL;
}

static struct cls_table *
find_table(const struct classifier *cls, const struct flow_wildcards *wc)
{
    struct cls_table *table;

    HMAP_FOR_EACH_IN_BUCKET (table, hmap_node, flow_wildcards_hash(wc, 0),
                             &cls->tables) {
        if (flow_wildcards_equal(wc, &table->wc)) {
            return table;
        }
    }
    return NULL;
}

static struct cls_table *
insert_table(struct classifier *cls, const struct flow_wildcards *wc)
{
    struct cls_table *table;

    table = xzalloc(sizeof *table);
    hmap_init(&table->rules);
    table->wc = *wc;
    hmap_insert(&cls->tables, &table->hmap_node, flow_wildcards_hash(wc, 0));

    return table;
}

static void
destroy_table(struct classifier *cls, struct cls_table *table)
{
    hmap_remove(&cls->tables, &table->hmap_node);
    hmap_destroy(&table->rules);
    free(table);
}

static struct cls_rule *
find_match(const struct cls_table *table, const struct flow *flow)
{
    struct cls_rule *rule;
    struct flow f;

    f = *flow;
    flow_zero_wildcards(&f, &table->wc);
    HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, flow_hash(&f, 0),
                             &table->rules) {
        if (flow_equal(&f, &rule->flow)) {
            return rule;
        }
    }
    return NULL;
}

static struct cls_rule *
find_equal(struct cls_table *table, const struct flow *flow, uint32_t hash)
{
    struct cls_rule *head;

    HMAP_FOR_EACH_WITH_HASH (head, hmap_node, hash, &table->rules) {
        if (flow_equal(&head->flow, flow)) {
            return head;
        }
    }
    return NULL;
}

static struct cls_rule *
insert_rule(struct cls_table *table, struct cls_rule *new)
{
    struct cls_rule *head;

    new->hmap_node.hash = flow_hash(&new->flow, 0);

    head = find_equal(table, &new->flow, new->hmap_node.hash);
    if (!head) {
        hmap_insert(&table->rules, &new->hmap_node, new->hmap_node.hash);
        list_init(&new->list);
        return NULL;
    } else {
        /* Scan the list for the insertion point that will keep the list in
         * order of decreasing priority. */
        struct cls_rule *rule;
        FOR_EACH_RULE_IN_LIST (rule, head) {
            if (new->priority >= rule->priority) {
                if (rule == head) {
                    /* 'new' is the new highest-priority flow in the list. */
                    hmap_replace(&table->rules,
                                 &rule->hmap_node, &new->hmap_node);
                }

                if (new->priority == rule->priority) {
                    list_replace(&new->list, &rule->list);
                    return rule;
                } else {
                    list_insert(&rule->list, &new->list);
                    return NULL;
                }
            }
        }

        /* Insert 'new' at the end of the list. */
        list_push_back(&head->list, &new->list);
        return NULL;
    }
}

static struct cls_rule *
next_rule_in_list__(struct cls_rule *rule)
{
    struct cls_rule *next = OBJECT_CONTAINING(rule->list.next, next, list);
    return next;
}

static struct cls_rule *
next_rule_in_list(struct cls_rule *rule)
{
    struct cls_rule *next = next_rule_in_list__(rule);
    return next->priority < rule->priority ? next : NULL;
}

static bool
ipv6_equal_except(const struct in6_addr *a, const struct in6_addr *b,
                  const struct in6_addr *mask)
{
    int i;

#ifdef s6_addr32
    for (i=0; i<4; i++) {
        if ((a->s6_addr32[i] ^ b->s6_addr32[i]) & mask->s6_addr32[i]) {
            return false;
        }
    }
#else
    for (i=0; i<16; i++) {
        if ((a->s6_addr[i] ^ b->s6_addr[i]) & mask->s6_addr[i]) {
            return false;
        }
    }
#endif

    return true;
}


static bool
flow_equal_except(const struct flow *a, const struct flow *b,
                  const struct flow_wildcards *wildcards)
{
    const flow_wildcards_t wc = wildcards->wildcards;
    int i;

    BUILD_ASSERT_DECL(FLOW_WC_SEQ == 7);

    for (i = 0; i < FLOW_N_REGS; i++) {
        if ((a->regs[i] ^ b->regs[i]) & wildcards->reg_masks[i]) {
            return false;
        }
    }

    return (!((a->tun_id ^ b->tun_id) & wildcards->tun_id_mask)
            && !((a->nw_src ^ b->nw_src) & wildcards->nw_src_mask)
            && !((a->nw_dst ^ b->nw_dst) & wildcards->nw_dst_mask)
            && (wc & FWW_IN_PORT || a->in_port == b->in_port)
            && !((a->vlan_tci ^ b->vlan_tci) & wildcards->vlan_tci_mask)
            && (wc & FWW_DL_TYPE || a->dl_type == b->dl_type)
            && (wc & FWW_TP_SRC || a->tp_src == b->tp_src)
            && (wc & FWW_TP_DST || a->tp_dst == b->tp_dst)
            && (wc & FWW_DL_SRC || eth_addr_equals(a->dl_src, b->dl_src))
            && (wc & FWW_DL_DST
                || (!((a->dl_dst[0] ^ b->dl_dst[0]) & 0xfe)
                    && a->dl_dst[1] == b->dl_dst[1]
                    && a->dl_dst[2] == b->dl_dst[2]
                    && a->dl_dst[3] == b->dl_dst[3]
                    && a->dl_dst[4] == b->dl_dst[4]
                    && a->dl_dst[5] == b->dl_dst[5]))
            && (wc & FWW_ETH_MCAST
                || !((a->dl_dst[0] ^ b->dl_dst[0]) & 0x01))
            && (wc & FWW_NW_PROTO || a->nw_proto == b->nw_proto)
            && (wc & FWW_NW_TTL || a->nw_ttl == b->nw_ttl)
            && (wc & FWW_NW_DSCP || !((a->nw_tos ^ b->nw_tos) & IP_DSCP_MASK))
            && (wc & FWW_NW_ECN || !((a->nw_tos ^ b->nw_tos) & IP_ECN_MASK))
            && !((a->nw_frag ^ b->nw_frag) & wildcards->nw_frag_mask)
            && (wc & FWW_ARP_SHA || eth_addr_equals(a->arp_sha, b->arp_sha))
            && (wc & FWW_ARP_THA || eth_addr_equals(a->arp_tha, b->arp_tha))
            && (wc & FWW_IPV6_LABEL || a->ipv6_label == b->ipv6_label)
            && ipv6_equal_except(&a->ipv6_src, &b->ipv6_src,
                    &wildcards->ipv6_src_mask)
            && ipv6_equal_except(&a->ipv6_dst, &b->ipv6_dst,
                    &wildcards->ipv6_dst_mask)
            && (wc & FWW_ND_TARGET
                || ipv6_addr_equals(&a->nd_target, &b->nd_target)));
}