Global replace of Nicira Networks.
[sliver-openvswitch.git] / lib / 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 #include <config.h>
18 #include "classifier.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <netinet/in.h>
22 #include "byte-order.h"
23 #include "dynamic-string.h"
24 #include "flow.h"
25 #include "hash.h"
26 #include "odp-util.h"
27 #include "ofp-util.h"
28 #include "packets.h"
29
30 static struct cls_table *find_table(const struct classifier *,
31                                     const struct flow_wildcards *);
32 static struct cls_table *insert_table(struct classifier *,
33                                       const struct flow_wildcards *);
34
35 static void destroy_table(struct classifier *, struct cls_table *);
36
37 static struct cls_rule *find_match(const struct cls_table *,
38                                    const struct flow *);
39 static struct cls_rule *find_equal(struct cls_table *, const struct flow *,
40                                    uint32_t hash);
41 static struct cls_rule *insert_rule(struct cls_table *, struct cls_rule *);
42
43 static bool flow_equal_except(const struct flow *, const struct flow *,
44                                 const struct flow_wildcards *);
45
46 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list. */
47 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD)                               \
48     for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
49 #define FOR_EACH_RULE_IN_LIST_SAFE(RULE, NEXT, HEAD)                    \
50     for ((RULE) = (HEAD);                                               \
51          (RULE) != NULL && ((NEXT) = next_rule_in_list(RULE), true);    \
52          (RULE) = (NEXT))
53
54 static struct cls_rule *next_rule_in_list__(struct cls_rule *);
55 static struct cls_rule *next_rule_in_list(struct cls_rule *);
56
57 /* Converts the flow in 'flow' into a cls_rule in 'rule', with the given
58  * 'wildcards' and 'priority'. */
59 void
60 cls_rule_init(const struct flow *flow, const struct flow_wildcards *wildcards,
61               unsigned int priority, struct cls_rule *rule)
62 {
63     rule->flow = *flow;
64     rule->wc = *wildcards;
65     rule->priority = priority;
66     cls_rule_zero_wildcarded_fields(rule);
67 }
68
69 /* Converts the flow in 'flow' into an exact-match cls_rule in 'rule', with the
70  * given 'priority'.  (For OpenFlow 1.0, exact-match rule are always highest
71  * priority, so 'priority' should be at least 65535.) */
72 void
73 cls_rule_init_exact(const struct flow *flow,
74                     unsigned int priority, struct cls_rule *rule)
75 {
76     rule->flow = *flow;
77     rule->flow.skb_priority = 0;
78     flow_wildcards_init_exact(&rule->wc);
79     rule->priority = priority;
80 }
81
82 /* Initializes 'rule' as a "catch-all" rule that matches every packet, with
83  * priority 'priority'. */
84 void
85 cls_rule_init_catchall(struct cls_rule *rule, unsigned int priority)
86 {
87     memset(&rule->flow, 0, sizeof rule->flow);
88     flow_wildcards_init_catchall(&rule->wc);
89     rule->priority = priority;
90 }
91
92 /* For each bit or field wildcarded in 'rule', sets the corresponding bit or
93  * field in 'flow' to all-0-bits.  It is important to maintain this invariant
94  * in a clr_rule that might be inserted into a classifier.
95  *
96  * It is never necessary to call this function directly for a cls_rule that is
97  * initialized or modified only by cls_rule_*() functions.  It is useful to
98  * restore the invariant in a cls_rule whose 'wc' member is modified by hand.
99  */
100 void
101 cls_rule_zero_wildcarded_fields(struct cls_rule *rule)
102 {
103     flow_zero_wildcards(&rule->flow, &rule->wc);
104 }
105
106 void
107 cls_rule_set_reg(struct cls_rule *rule, unsigned int reg_idx, uint32_t value)
108 {
109     cls_rule_set_reg_masked(rule, reg_idx, value, UINT32_MAX);
110 }
111
112 void
113 cls_rule_set_reg_masked(struct cls_rule *rule, unsigned int reg_idx,
114                         uint32_t value, uint32_t mask)
115 {
116     assert(reg_idx < FLOW_N_REGS);
117     flow_wildcards_set_reg_mask(&rule->wc, reg_idx, mask);
118     rule->flow.regs[reg_idx] = value & mask;
119 }
120
121 void
122 cls_rule_set_tun_id(struct cls_rule *rule, ovs_be64 tun_id)
123 {
124     cls_rule_set_tun_id_masked(rule, tun_id, htonll(UINT64_MAX));
125 }
126
127 void
128 cls_rule_set_tun_id_masked(struct cls_rule *rule,
129                            ovs_be64 tun_id, ovs_be64 mask)
130 {
131     rule->wc.tun_id_mask = mask;
132     rule->flow.tun_id = tun_id & mask;
133 }
134
135 void
136 cls_rule_set_in_port(struct cls_rule *rule, uint16_t ofp_port)
137 {
138     rule->wc.wildcards &= ~FWW_IN_PORT;
139     rule->flow.in_port = ofp_port;
140 }
141
142 void
143 cls_rule_set_dl_type(struct cls_rule *rule, ovs_be16 dl_type)
144 {
145     rule->wc.wildcards &= ~FWW_DL_TYPE;
146     rule->flow.dl_type = dl_type;
147 }
148
149 void
150 cls_rule_set_dl_src(struct cls_rule *rule, const uint8_t dl_src[ETH_ADDR_LEN])
151 {
152     rule->wc.wildcards &= ~FWW_DL_SRC;
153     memcpy(rule->flow.dl_src, dl_src, ETH_ADDR_LEN);
154 }
155
156 /* Modifies 'rule' so that the Ethernet address must match 'dl_dst' exactly. */
157 void
158 cls_rule_set_dl_dst(struct cls_rule *rule, const uint8_t dl_dst[ETH_ADDR_LEN])
159 {
160     rule->wc.wildcards &= ~(FWW_DL_DST | FWW_ETH_MCAST);
161     memcpy(rule->flow.dl_dst, dl_dst, ETH_ADDR_LEN);
162 }
163
164 /* Modifies 'rule' so that the Ethernet address must match 'dl_dst' after each
165  * byte is ANDed with the appropriate byte in 'mask'.
166  *
167  * This function will assert-fail if 'mask' is invalid.  Only 'mask' values
168  * accepted by flow_wildcards_is_dl_dst_mask_valid() are allowed. */
169 void
170 cls_rule_set_dl_dst_masked(struct cls_rule *rule,
171                            const uint8_t dl_dst[ETH_ADDR_LEN],
172                            const uint8_t mask[ETH_ADDR_LEN])
173 {
174     flow_wildcards_t *wc = &rule->wc.wildcards;
175     size_t i;
176
177     *wc = flow_wildcards_set_dl_dst_mask(*wc, mask);
178     for (i = 0; i < ETH_ADDR_LEN; i++) {
179         rule->flow.dl_dst[i] = dl_dst[i] & mask[i];
180     }
181 }
182
183 void
184 cls_rule_set_dl_tci(struct cls_rule *rule, ovs_be16 tci)
185 {
186     cls_rule_set_dl_tci_masked(rule, tci, htons(0xffff));
187 }
188
189 void
190 cls_rule_set_dl_tci_masked(struct cls_rule *rule, ovs_be16 tci, ovs_be16 mask)
191 {
192     rule->flow.vlan_tci = tci & mask;
193     rule->wc.vlan_tci_mask = mask;
194 }
195
196 /* Modifies 'rule' so that the VLAN VID is wildcarded.  If the PCP is already
197  * wildcarded, then 'rule' will match a packet regardless of whether it has an
198  * 802.1Q header or not. */
199 void
200 cls_rule_set_any_vid(struct cls_rule *rule)
201 {
202     if (rule->wc.vlan_tci_mask & htons(VLAN_PCP_MASK)) {
203         rule->wc.vlan_tci_mask &= ~htons(VLAN_VID_MASK);
204         rule->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
205     } else {
206         cls_rule_set_dl_tci_masked(rule, htons(0), htons(0));
207     }
208 }
209
210 /* Modifies 'rule' depending on 'dl_vlan':
211  *
212  *   - If 'dl_vlan' is htons(OFP_VLAN_NONE), makes 'rule' match only packets
213  *     without an 802.1Q header.
214  *
215  *   - Otherwise, makes 'rule' match only packets with an 802.1Q header whose
216  *     VID equals the low 12 bits of 'dl_vlan'.
217  */
218 void
219 cls_rule_set_dl_vlan(struct cls_rule *rule, ovs_be16 dl_vlan)
220 {
221     flow_set_vlan_vid(&rule->flow, dl_vlan);
222     if (dl_vlan == htons(OFP_VLAN_NONE)) {
223         rule->wc.vlan_tci_mask = htons(UINT16_MAX);
224     } else {
225         rule->wc.vlan_tci_mask |= htons(VLAN_VID_MASK | VLAN_CFI);
226     }
227 }
228
229 /* Modifies 'rule' so that the VLAN PCP is wildcarded.  If the VID is already
230  * wildcarded, then 'rule' will match a packet regardless of whether it has an
231  * 802.1Q header or not. */
232 void
233 cls_rule_set_any_pcp(struct cls_rule *rule)
234 {
235     if (rule->wc.vlan_tci_mask & htons(VLAN_VID_MASK)) {
236         rule->wc.vlan_tci_mask &= ~htons(VLAN_PCP_MASK);
237         rule->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
238     } else {
239         cls_rule_set_dl_tci_masked(rule, htons(0), htons(0));
240     }
241 }
242
243 /* Modifies 'rule' so that it matches only packets with an 802.1Q header whose
244  * PCP equals the low 3 bits of 'dl_vlan_pcp'. */
245 void
246 cls_rule_set_dl_vlan_pcp(struct cls_rule *rule, uint8_t dl_vlan_pcp)
247 {
248     flow_set_vlan_pcp(&rule->flow, dl_vlan_pcp);
249     rule->wc.vlan_tci_mask |= htons(VLAN_CFI | VLAN_PCP_MASK);
250 }
251
252 void
253 cls_rule_set_tp_src(struct cls_rule *rule, ovs_be16 tp_src)
254 {
255     cls_rule_set_tp_src_masked(rule, tp_src, htons(UINT16_MAX));
256 }
257
258 void
259 cls_rule_set_tp_src_masked(struct cls_rule *rule, ovs_be16 port, ovs_be16 mask)
260 {
261     rule->flow.tp_src = port & mask;
262     rule->wc.tp_src_mask = mask;
263 }
264
265 void
266 cls_rule_set_tp_dst(struct cls_rule *rule, ovs_be16 tp_dst)
267 {
268     cls_rule_set_tp_dst_masked(rule, tp_dst, htons(UINT16_MAX));
269 }
270
271 void
272 cls_rule_set_tp_dst_masked(struct cls_rule *rule, ovs_be16 port, ovs_be16 mask)
273 {
274     rule->flow.tp_dst = port & mask;
275     rule->wc.tp_dst_mask = mask;
276 }
277
278 void
279 cls_rule_set_nw_proto(struct cls_rule *rule, uint8_t nw_proto)
280 {
281     rule->wc.wildcards &= ~FWW_NW_PROTO;
282     rule->flow.nw_proto = nw_proto;
283 }
284
285 void
286 cls_rule_set_nw_src(struct cls_rule *rule, ovs_be32 nw_src)
287 {
288     rule->flow.nw_src = nw_src;
289     rule->wc.nw_src_mask = htonl(UINT32_MAX);
290 }
291
292 void
293 cls_rule_set_nw_src_masked(struct cls_rule *rule,
294                            ovs_be32 nw_src, ovs_be32 mask)
295 {
296     rule->flow.nw_src = nw_src & mask;
297     rule->wc.nw_src_mask = mask;
298 }
299
300 void
301 cls_rule_set_nw_dst(struct cls_rule *rule, ovs_be32 nw_dst)
302 {
303     rule->flow.nw_dst = nw_dst;
304     rule->wc.nw_dst_mask = htonl(UINT32_MAX);
305 }
306
307 void
308 cls_rule_set_nw_dst_masked(struct cls_rule *rule, ovs_be32 ip, ovs_be32 mask)
309 {
310     rule->flow.nw_dst = ip & mask;
311     rule->wc.nw_dst_mask = mask;
312 }
313
314 void
315 cls_rule_set_nw_dscp(struct cls_rule *rule, uint8_t nw_dscp)
316 {
317     rule->wc.wildcards &= ~FWW_NW_DSCP;
318     rule->flow.nw_tos &= ~IP_DSCP_MASK;
319     rule->flow.nw_tos |= nw_dscp & IP_DSCP_MASK;
320 }
321
322 void
323 cls_rule_set_nw_ecn(struct cls_rule *rule, uint8_t nw_ecn)
324 {
325     rule->wc.wildcards &= ~FWW_NW_ECN;
326     rule->flow.nw_tos &= ~IP_ECN_MASK;
327     rule->flow.nw_tos |= nw_ecn & IP_ECN_MASK;
328 }
329
330 void
331 cls_rule_set_nw_ttl(struct cls_rule *rule, uint8_t nw_ttl)
332 {
333     rule->wc.wildcards &= ~FWW_NW_TTL;
334     rule->flow.nw_ttl = nw_ttl;
335 }
336
337 void
338 cls_rule_set_nw_frag(struct cls_rule *rule, uint8_t nw_frag)
339 {
340     rule->wc.nw_frag_mask |= FLOW_NW_FRAG_MASK;
341     rule->flow.nw_frag = nw_frag;
342 }
343
344 void
345 cls_rule_set_nw_frag_masked(struct cls_rule *rule,
346                             uint8_t nw_frag, uint8_t mask)
347 {
348     rule->flow.nw_frag = nw_frag & mask;
349     rule->wc.nw_frag_mask = mask;
350 }
351
352 void
353 cls_rule_set_icmp_type(struct cls_rule *rule, uint8_t icmp_type)
354 {
355     cls_rule_set_tp_src(rule, htons(icmp_type));
356 }
357
358 void
359 cls_rule_set_icmp_code(struct cls_rule *rule, uint8_t icmp_code)
360 {
361     cls_rule_set_tp_dst(rule, htons(icmp_code));
362 }
363
364 void
365 cls_rule_set_arp_sha(struct cls_rule *rule, const uint8_t sha[ETH_ADDR_LEN])
366 {
367     rule->wc.wildcards &= ~FWW_ARP_SHA;
368     memcpy(rule->flow.arp_sha, sha, ETH_ADDR_LEN);
369 }
370
371 void
372 cls_rule_set_arp_tha(struct cls_rule *rule, const uint8_t tha[ETH_ADDR_LEN])
373 {
374     rule->wc.wildcards &= ~FWW_ARP_THA;
375     memcpy(rule->flow.arp_tha, tha, ETH_ADDR_LEN);
376 }
377
378 void
379 cls_rule_set_ipv6_src(struct cls_rule *rule, const struct in6_addr *src)
380 {
381     rule->flow.ipv6_src = *src;
382     rule->wc.ipv6_src_mask = in6addr_exact;
383 }
384
385 void
386 cls_rule_set_ipv6_src_masked(struct cls_rule *rule, const struct in6_addr *src,
387                              const struct in6_addr *mask)
388 {
389     rule->flow.ipv6_src = ipv6_addr_bitand(src, mask);
390     rule->wc.ipv6_src_mask = *mask;
391 }
392
393 void
394 cls_rule_set_ipv6_dst(struct cls_rule *rule, const struct in6_addr *dst)
395 {
396     rule->flow.ipv6_dst = *dst;
397     rule->wc.ipv6_dst_mask = in6addr_exact;
398 }
399
400 void
401 cls_rule_set_ipv6_dst_masked(struct cls_rule *rule, const struct in6_addr *dst,
402                              const struct in6_addr *mask)
403 {
404     rule->flow.ipv6_dst = ipv6_addr_bitand(dst, mask);
405     rule->wc.ipv6_dst_mask = *mask;
406 }
407
408 void
409 cls_rule_set_ipv6_label(struct cls_rule *rule, ovs_be32 ipv6_label)
410 {
411     rule->wc.wildcards &= ~FWW_IPV6_LABEL;
412     rule->flow.ipv6_label = ipv6_label;
413 }
414
415 void
416 cls_rule_set_nd_target(struct cls_rule *rule, const struct in6_addr *target)
417 {
418     rule->flow.nd_target = *target;
419     rule->wc.nd_target_mask = in6addr_exact;
420 }
421
422 void
423 cls_rule_set_nd_target_masked(struct cls_rule *rule,
424                               const struct in6_addr *target,
425                               const struct in6_addr *mask)
426 {
427     rule->flow.nd_target = ipv6_addr_bitand(target, mask);
428     rule->wc.nd_target_mask = *mask;
429 }
430
431 /* Returns true if 'a' and 'b' have the same priority, wildcard the same
432  * fields, and have the same values for fixed fields, otherwise false. */
433 bool
434 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
435 {
436     return (a->priority == b->priority
437             && flow_wildcards_equal(&a->wc, &b->wc)
438             && flow_equal(&a->flow, &b->flow));
439 }
440
441 /* Returns a hash value for the flow, wildcards, and priority in 'rule',
442  * starting from 'basis'. */
443 uint32_t
444 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
445 {
446     uint32_t h0 = flow_hash(&rule->flow, basis);
447     uint32_t h1 = flow_wildcards_hash(&rule->wc, h0);
448     return hash_int(rule->priority, h1);
449 }
450
451 static void
452 format_ip_netmask(struct ds *s, const char *name, ovs_be32 ip,
453                   ovs_be32 netmask)
454 {
455     if (netmask) {
456         ds_put_format(s, "%s=", name);
457         ip_format_masked(ip, netmask, s);
458         ds_put_char(s, ',');
459     }
460 }
461
462 static void
463 format_ipv6_netmask(struct ds *s, const char *name,
464                     const struct in6_addr *addr,
465                     const struct in6_addr *netmask)
466 {
467     if (!ipv6_mask_is_any(netmask)) {
468         ds_put_format(s, "%s=", name);
469         print_ipv6_masked(s, addr, netmask);
470         ds_put_char(s, ',');
471     }
472 }
473
474
475 static void
476 format_be16_masked(struct ds *s, const char *name,
477                    ovs_be16 value, ovs_be16 mask)
478 {
479     if (mask != htons(0)) {
480         ds_put_format(s, "%s=", name);
481         if (mask == htons(UINT16_MAX)) {
482             ds_put_format(s, "%"PRIu16, ntohs(value));
483         } else {
484             ds_put_format(s, "0x%"PRIx16"/0x%"PRIx16,
485                           ntohs(value), ntohs(mask));
486         }
487         ds_put_char(s, ',');
488     }
489 }
490
491 void
492 cls_rule_format(const struct cls_rule *rule, struct ds *s)
493 {
494     const struct flow_wildcards *wc = &rule->wc;
495     size_t start_len = s->length;
496     flow_wildcards_t w = wc->wildcards;
497     const struct flow *f = &rule->flow;
498     bool skip_type = false;
499     bool skip_proto = false;
500
501     int i;
502
503     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 10);
504
505     if (rule->priority != OFP_DEFAULT_PRIORITY) {
506         ds_put_format(s, "priority=%d,", rule->priority);
507     }
508
509     if (!(w & FWW_DL_TYPE)) {
510         skip_type = true;
511         if (f->dl_type == htons(ETH_TYPE_IP)) {
512             if (!(w & FWW_NW_PROTO)) {
513                 skip_proto = true;
514                 if (f->nw_proto == IPPROTO_ICMP) {
515                     ds_put_cstr(s, "icmp,");
516                 } else if (f->nw_proto == IPPROTO_TCP) {
517                     ds_put_cstr(s, "tcp,");
518                 } else if (f->nw_proto == IPPROTO_UDP) {
519                     ds_put_cstr(s, "udp,");
520                 } else {
521                     ds_put_cstr(s, "ip,");
522                     skip_proto = false;
523                 }
524             } else {
525                 ds_put_cstr(s, "ip,");
526             }
527         } else if (f->dl_type == htons(ETH_TYPE_IPV6)) {
528             if (!(w & FWW_NW_PROTO)) {
529                 skip_proto = true;
530                 if (f->nw_proto == IPPROTO_ICMPV6) {
531                     ds_put_cstr(s, "icmp6,");
532                 } else if (f->nw_proto == IPPROTO_TCP) {
533                     ds_put_cstr(s, "tcp6,");
534                 } else if (f->nw_proto == IPPROTO_UDP) {
535                     ds_put_cstr(s, "udp6,");
536                 } else {
537                     ds_put_cstr(s, "ipv6,");
538                     skip_proto = false;
539                 }
540             } else {
541                 ds_put_cstr(s, "ipv6,");
542             }
543         } else if (f->dl_type == htons(ETH_TYPE_ARP)) {
544             ds_put_cstr(s, "arp,");
545         } else {
546             skip_type = false;
547         }
548     }
549     for (i = 0; i < FLOW_N_REGS; i++) {
550         switch (wc->reg_masks[i]) {
551         case 0:
552             break;
553         case UINT32_MAX:
554             ds_put_format(s, "reg%d=0x%"PRIx32",", i, f->regs[i]);
555             break;
556         default:
557             ds_put_format(s, "reg%d=0x%"PRIx32"/0x%"PRIx32",",
558                           i, f->regs[i], wc->reg_masks[i]);
559             break;
560         }
561     }
562     switch (wc->tun_id_mask) {
563     case 0:
564         break;
565     case CONSTANT_HTONLL(UINT64_MAX):
566         ds_put_format(s, "tun_id=%#"PRIx64",", ntohll(f->tun_id));
567         break;
568     default:
569         ds_put_format(s, "tun_id=%#"PRIx64"/%#"PRIx64",",
570                       ntohll(f->tun_id), ntohll(wc->tun_id_mask));
571         break;
572     }
573     if (!(w & FWW_IN_PORT)) {
574         ds_put_format(s, "in_port=%"PRIu16",", f->in_port);
575     }
576     if (wc->vlan_tci_mask) {
577         ovs_be16 vid_mask = wc->vlan_tci_mask & htons(VLAN_VID_MASK);
578         ovs_be16 pcp_mask = wc->vlan_tci_mask & htons(VLAN_PCP_MASK);
579         ovs_be16 cfi = wc->vlan_tci_mask & htons(VLAN_CFI);
580
581         if (cfi && f->vlan_tci & htons(VLAN_CFI)
582             && (!vid_mask || vid_mask == htons(VLAN_VID_MASK))
583             && (!pcp_mask || pcp_mask == htons(VLAN_PCP_MASK))
584             && (vid_mask || pcp_mask)) {
585             if (vid_mask) {
586                 ds_put_format(s, "dl_vlan=%"PRIu16",",
587                               vlan_tci_to_vid(f->vlan_tci));
588             }
589             if (pcp_mask) {
590                 ds_put_format(s, "dl_vlan_pcp=%d,",
591                               vlan_tci_to_pcp(f->vlan_tci));
592             }
593         } else if (wc->vlan_tci_mask == htons(0xffff)) {
594             ds_put_format(s, "vlan_tci=0x%04"PRIx16",", ntohs(f->vlan_tci));
595         } else {
596             ds_put_format(s, "vlan_tci=0x%04"PRIx16"/0x%04"PRIx16",",
597                           ntohs(f->vlan_tci), ntohs(wc->vlan_tci_mask));
598         }
599     }
600     if (!(w & FWW_DL_SRC)) {
601         ds_put_format(s, "dl_src="ETH_ADDR_FMT",", ETH_ADDR_ARGS(f->dl_src));
602     }
603     switch (w & (FWW_DL_DST | FWW_ETH_MCAST)) {
604     case 0:
605         ds_put_format(s, "dl_dst="ETH_ADDR_FMT",", ETH_ADDR_ARGS(f->dl_dst));
606         break;
607     case FWW_DL_DST:
608         ds_put_format(s, "dl_dst="ETH_ADDR_FMT"/01:00:00:00:00:00,",
609                       ETH_ADDR_ARGS(f->dl_dst));
610         break;
611     case FWW_ETH_MCAST:
612         ds_put_format(s, "dl_dst="ETH_ADDR_FMT"/fe:ff:ff:ff:ff:ff,",
613                       ETH_ADDR_ARGS(f->dl_dst));
614         break;
615     case FWW_DL_DST | FWW_ETH_MCAST:
616         break;
617     }
618     if (!skip_type && !(w & FWW_DL_TYPE)) {
619         ds_put_format(s, "dl_type=0x%04"PRIx16",", ntohs(f->dl_type));
620     }
621     if (f->dl_type == htons(ETH_TYPE_IPV6)) {
622         format_ipv6_netmask(s, "ipv6_src", &f->ipv6_src, &wc->ipv6_src_mask);
623         format_ipv6_netmask(s, "ipv6_dst", &f->ipv6_dst, &wc->ipv6_dst_mask);
624         if (!(w & FWW_IPV6_LABEL)) {
625             ds_put_format(s, "ipv6_label=0x%05"PRIx32",", ntohl(f->ipv6_label));
626         }
627     } else {
628         format_ip_netmask(s, "nw_src", f->nw_src, wc->nw_src_mask);
629         format_ip_netmask(s, "nw_dst", f->nw_dst, wc->nw_dst_mask);
630     }
631     if (!skip_proto && !(w & FWW_NW_PROTO)) {
632         if (f->dl_type == htons(ETH_TYPE_ARP)) {
633             ds_put_format(s, "arp_op=%"PRIu8",", f->nw_proto);
634         } else {
635             ds_put_format(s, "nw_proto=%"PRIu8",", f->nw_proto);
636         }
637     }
638     if (f->dl_type == htons(ETH_TYPE_ARP)) {
639         if (!(w & FWW_ARP_SHA)) {
640             ds_put_format(s, "arp_sha="ETH_ADDR_FMT",",
641                     ETH_ADDR_ARGS(f->arp_sha));
642         }
643         if (!(w & FWW_ARP_THA)) {
644             ds_put_format(s, "arp_tha="ETH_ADDR_FMT",",
645                     ETH_ADDR_ARGS(f->arp_tha));
646         }
647     }
648     if (!(w & FWW_NW_DSCP)) {
649         ds_put_format(s, "nw_tos=%"PRIu8",", f->nw_tos & IP_DSCP_MASK);
650     }
651     if (!(w & FWW_NW_ECN)) {
652         ds_put_format(s, "nw_ecn=%"PRIu8",", f->nw_tos & IP_ECN_MASK);
653     }
654     if (!(w & FWW_NW_TTL)) {
655         ds_put_format(s, "nw_ttl=%"PRIu8",", f->nw_ttl);
656     }
657     switch (wc->nw_frag_mask) {
658     case FLOW_NW_FRAG_ANY | FLOW_NW_FRAG_LATER:
659         ds_put_format(s, "nw_frag=%s,",
660                       f->nw_frag & FLOW_NW_FRAG_ANY
661                       ? (f->nw_frag & FLOW_NW_FRAG_LATER ? "later" : "first")
662                       : (f->nw_frag & FLOW_NW_FRAG_LATER ? "<error>" : "no"));
663         break;
664
665     case FLOW_NW_FRAG_ANY:
666         ds_put_format(s, "nw_frag=%s,",
667                       f->nw_frag & FLOW_NW_FRAG_ANY ? "yes" : "no");
668         break;
669
670     case FLOW_NW_FRAG_LATER:
671         ds_put_format(s, "nw_frag=%s,",
672                       f->nw_frag & FLOW_NW_FRAG_LATER ? "later" : "not_later");
673         break;
674     }
675     if (f->nw_proto == IPPROTO_ICMP) {
676         format_be16_masked(s, "icmp_type", f->tp_src, wc->tp_src_mask);
677         format_be16_masked(s, "icmp_code", f->tp_dst, wc->tp_dst_mask);
678     } else if (f->nw_proto == IPPROTO_ICMPV6) {
679         format_be16_masked(s, "icmp_type", f->tp_src, wc->tp_src_mask);
680         format_be16_masked(s, "icmp_code", f->tp_dst, wc->tp_dst_mask);
681         format_ipv6_netmask(s, "nd_target", &f->nd_target,
682                             &wc->nd_target_mask);
683         if (!(w & FWW_ARP_SHA)) {
684             ds_put_format(s, "nd_sll="ETH_ADDR_FMT",",
685                     ETH_ADDR_ARGS(f->arp_sha));
686         }
687         if (!(w & FWW_ARP_THA)) {
688             ds_put_format(s, "nd_tll="ETH_ADDR_FMT",",
689                     ETH_ADDR_ARGS(f->arp_tha));
690         }
691    } else {
692         format_be16_masked(s, "tp_src", f->tp_src, wc->tp_src_mask);
693         format_be16_masked(s, "tp_dst", f->tp_dst, wc->tp_dst_mask);
694     }
695
696     if (s->length > start_len && ds_last(s) == ',') {
697         s->length--;
698     }
699 }
700
701 /* Converts 'rule' to a string and returns the string.  The caller must free
702  * the string (with free()). */
703 char *
704 cls_rule_to_string(const struct cls_rule *rule)
705 {
706     struct ds s = DS_EMPTY_INITIALIZER;
707     cls_rule_format(rule, &s);
708     return ds_steal_cstr(&s);
709 }
710
711 void
712 cls_rule_print(const struct cls_rule *rule)
713 {
714     char *s = cls_rule_to_string(rule);
715     puts(s);
716     free(s);
717 }
718 \f
719 /* Initializes 'cls' as a classifier that initially contains no classification
720  * rules. */
721 void
722 classifier_init(struct classifier *cls)
723 {
724     cls->n_rules = 0;
725     hmap_init(&cls->tables);
726 }
727
728 /* Destroys 'cls'.  Rules within 'cls', if any, are not freed; this is the
729  * caller's responsibility. */
730 void
731 classifier_destroy(struct classifier *cls)
732 {
733     if (cls) {
734         struct cls_table *table, *next_table;
735
736         HMAP_FOR_EACH_SAFE (table, next_table, hmap_node, &cls->tables) {
737             hmap_destroy(&table->rules);
738             hmap_remove(&cls->tables, &table->hmap_node);
739             free(table);
740         }
741         hmap_destroy(&cls->tables);
742     }
743 }
744
745 /* Returns true if 'cls' contains no classification rules, false otherwise. */
746 bool
747 classifier_is_empty(const struct classifier *cls)
748 {
749     return cls->n_rules == 0;
750 }
751
752 /* Returns the number of rules in 'classifier'. */
753 int
754 classifier_count(const struct classifier *cls)
755 {
756     return cls->n_rules;
757 }
758
759 /* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
760  * must not modify or free it.
761  *
762  * If 'cls' already contains an identical rule (including wildcards, values of
763  * fixed fields, and priority), replaces the old rule by 'rule' and returns the
764  * rule that was replaced.  The caller takes ownership of the returned rule and
765  * is thus responsible for freeing it, etc., as necessary.
766  *
767  * Returns NULL if 'cls' does not contain a rule with an identical key, after
768  * inserting the new rule.  In this case, no rules are displaced by the new
769  * rule, even rules that cannot have any effect because the new rule matches a
770  * superset of their flows and has higher priority. */
771 struct cls_rule *
772 classifier_replace(struct classifier *cls, struct cls_rule *rule)
773 {
774     struct cls_rule *old_rule;
775     struct cls_table *table;
776
777     table = find_table(cls, &rule->wc);
778     if (!table) {
779         table = insert_table(cls, &rule->wc);
780     }
781
782     old_rule = insert_rule(table, rule);
783     if (!old_rule) {
784         table->n_table_rules++;
785         cls->n_rules++;
786     }
787     return old_rule;
788 }
789
790 /* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
791  * must not modify or free it.
792  *
793  * 'cls' must not contain an identical rule (including wildcards, values of
794  * fixed fields, and priority).  Use classifier_find_rule_exactly() to find
795  * such a rule. */
796 void
797 classifier_insert(struct classifier *cls, struct cls_rule *rule)
798 {
799     struct cls_rule *displaced_rule = classifier_replace(cls, rule);
800     assert(!displaced_rule);
801 }
802
803 /* Removes 'rule' from 'cls'.  It is the caller's responsibility to free
804  * 'rule', if this is desirable. */
805 void
806 classifier_remove(struct classifier *cls, struct cls_rule *rule)
807 {
808     struct cls_rule *head;
809     struct cls_table *table;
810
811     table = find_table(cls, &rule->wc);
812     head = find_equal(table, &rule->flow, rule->hmap_node.hash);
813     if (head != rule) {
814         list_remove(&rule->list);
815     } else if (list_is_empty(&rule->list)) {
816         hmap_remove(&table->rules, &rule->hmap_node);
817     } else {
818         struct cls_rule *next = CONTAINER_OF(rule->list.next,
819                                              struct cls_rule, list);
820
821         list_remove(&rule->list);
822         hmap_replace(&table->rules, &rule->hmap_node, &next->hmap_node);
823     }
824
825     if (--table->n_table_rules == 0) {
826         destroy_table(cls, table);
827     }
828
829     cls->n_rules--;
830 }
831
832 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
833  * Returns a null pointer if no rules in 'cls' match 'flow'.  If multiple rules
834  * of equal priority match 'flow', returns one arbitrarily. */
835 struct cls_rule *
836 classifier_lookup(const struct classifier *cls, const struct flow *flow)
837 {
838     struct cls_table *table;
839     struct cls_rule *best;
840
841     best = NULL;
842     HMAP_FOR_EACH (table, hmap_node, &cls->tables) {
843         struct cls_rule *rule = find_match(table, flow);
844         if (rule && (!best || rule->priority > best->priority)) {
845             best = rule;
846         }
847     }
848     return best;
849 }
850
851 /* Finds and returns a rule in 'cls' with exactly the same priority and
852  * matching criteria as 'target'.  Returns a null pointer if 'cls' doesn't
853  * contain an exact match. */
854 struct cls_rule *
855 classifier_find_rule_exactly(const struct classifier *cls,
856                              const struct cls_rule *target)
857 {
858     struct cls_rule *head, *rule;
859     struct cls_table *table;
860
861     table = find_table(cls, &target->wc);
862     if (!table) {
863         return NULL;
864     }
865
866     head = find_equal(table, &target->flow, flow_hash(&target->flow, 0));
867     FOR_EACH_RULE_IN_LIST (rule, head) {
868         if (target->priority >= rule->priority) {
869             return target->priority == rule->priority ? rule : NULL;
870         }
871     }
872     return NULL;
873 }
874
875 /* Checks if 'target' would overlap any other rule in 'cls'.  Two rules are
876  * considered to overlap if both rules have the same priority and a packet
877  * could match both. */
878 bool
879 classifier_rule_overlaps(const struct classifier *cls,
880                          const struct cls_rule *target)
881 {
882     struct cls_table *table;
883
884     HMAP_FOR_EACH (table, hmap_node, &cls->tables) {
885         struct flow_wildcards wc;
886         struct cls_rule *head;
887
888         flow_wildcards_combine(&wc, &target->wc, &table->wc);
889         HMAP_FOR_EACH (head, hmap_node, &table->rules) {
890             struct cls_rule *rule;
891
892             FOR_EACH_RULE_IN_LIST (rule, head) {
893                 if (rule->priority == target->priority
894                     && flow_equal_except(&target->flow, &rule->flow, &wc)) {
895                     return true;
896                 }
897             }
898         }
899     }
900
901     return false;
902 }
903 \f
904 /* Iteration. */
905
906 static bool
907 rule_matches(const struct cls_rule *rule, const struct cls_rule *target)
908 {
909     return (!target
910             || flow_equal_except(&rule->flow, &target->flow, &target->wc));
911 }
912
913 static struct cls_rule *
914 search_table(const struct cls_table *table, const struct cls_rule *target)
915 {
916     if (!target || !flow_wildcards_has_extra(&table->wc, &target->wc)) {
917         struct cls_rule *rule;
918
919         HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
920             if (rule_matches(rule, target)) {
921                 return rule;
922             }
923         }
924     }
925     return NULL;
926 }
927
928 /* Initializes 'cursor' for iterating through 'cls' rules that exactly match
929  * 'target' or are more specific than 'target'.  That is, a given 'rule'
930  * matches 'target' if, for every field:
931  *
932  *   - 'target' and 'rule' specify the same (non-wildcarded) value for the
933  *     field, or
934  *
935  *   - 'target' wildcards the field,
936  *
937  * but not if:
938  *
939  *   - 'target' and 'rule' specify different values for the field, or
940  *
941  *   - 'target' specifies a value for the field but 'rule' wildcards it.
942  *
943  * Equivalently, the truth table for whether a field matches is:
944  *
945  *                                     rule
946  *
947  *                             wildcard    exact
948  *                            +---------+---------+
949  *                   t   wild |   yes   |   yes   |
950  *                   a   card |         |         |
951  *                   r        +---------+---------+
952  *                   g  exact |    no   |if values|
953  *                   e        |         |are equal|
954  *                   t        +---------+---------+
955  *
956  * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
957  * commands and by OpenFlow 1.0 aggregate and flow stats.
958  *
959  * Ignores target->priority.
960  *
961  * 'target' may be NULL to iterate over every rule in 'cls'. */
962 void
963 cls_cursor_init(struct cls_cursor *cursor, const struct classifier *cls,
964                 const struct cls_rule *target)
965 {
966     cursor->cls = cls;
967     cursor->target = target;
968 }
969
970 /* Returns the first matching cls_rule in 'cursor''s iteration, or a null
971  * pointer if there are no matches. */
972 struct cls_rule *
973 cls_cursor_first(struct cls_cursor *cursor)
974 {
975     struct cls_table *table;
976
977     HMAP_FOR_EACH (table, hmap_node, &cursor->cls->tables) {
978         struct cls_rule *rule = search_table(table, cursor->target);
979         if (rule) {
980             cursor->table = table;
981             return rule;
982         }
983     }
984
985     return NULL;
986 }
987
988 /* Returns the next matching cls_rule in 'cursor''s iteration, or a null
989  * pointer if there are no more matches. */
990 struct cls_rule *
991 cls_cursor_next(struct cls_cursor *cursor, struct cls_rule *rule)
992 {
993     const struct cls_table *table;
994     struct cls_rule *next;
995
996     next = next_rule_in_list__(rule);
997     if (next->priority < rule->priority) {
998         return next;
999     }
1000
1001     /* 'next' is the head of the list, that is, the rule that is included in
1002      * the table's hmap.  (This is important when the classifier contains rules
1003      * that differ only in priority.) */
1004     rule = next;
1005     HMAP_FOR_EACH_CONTINUE (rule, hmap_node, &cursor->table->rules) {
1006         if (rule_matches(rule, cursor->target)) {
1007             return rule;
1008         }
1009     }
1010
1011     table = cursor->table;
1012     HMAP_FOR_EACH_CONTINUE (table, hmap_node, &cursor->cls->tables) {
1013         rule = search_table(table, cursor->target);
1014         if (rule) {
1015             cursor->table = table;
1016             return rule;
1017         }
1018     }
1019
1020     return NULL;
1021 }
1022 \f
1023 static struct cls_table *
1024 find_table(const struct classifier *cls, const struct flow_wildcards *wc)
1025 {
1026     struct cls_table *table;
1027
1028     HMAP_FOR_EACH_IN_BUCKET (table, hmap_node, flow_wildcards_hash(wc, 0),
1029                              &cls->tables) {
1030         if (flow_wildcards_equal(wc, &table->wc)) {
1031             return table;
1032         }
1033     }
1034     return NULL;
1035 }
1036
1037 static struct cls_table *
1038 insert_table(struct classifier *cls, const struct flow_wildcards *wc)
1039 {
1040     struct cls_table *table;
1041
1042     table = xzalloc(sizeof *table);
1043     hmap_init(&table->rules);
1044     table->wc = *wc;
1045     table->is_catchall = flow_wildcards_is_catchall(&table->wc);
1046     hmap_insert(&cls->tables, &table->hmap_node, flow_wildcards_hash(wc, 0));
1047
1048     return table;
1049 }
1050
1051 static void
1052 destroy_table(struct classifier *cls, struct cls_table *table)
1053 {
1054     hmap_remove(&cls->tables, &table->hmap_node);
1055     hmap_destroy(&table->rules);
1056     free(table);
1057 }
1058
1059 static struct cls_rule *
1060 find_match(const struct cls_table *table, const struct flow *flow)
1061 {
1062     struct cls_rule *rule;
1063
1064     if (table->is_catchall) {
1065         HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
1066             return rule;
1067         }
1068     } else {
1069         struct flow f;
1070
1071         f = *flow;
1072         flow_zero_wildcards(&f, &table->wc);
1073         HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, flow_hash(&f, 0),
1074                                  &table->rules) {
1075             if (flow_equal(&f, &rule->flow)) {
1076                 return rule;
1077             }
1078         }
1079     }
1080
1081     return NULL;
1082 }
1083
1084 static struct cls_rule *
1085 find_equal(struct cls_table *table, const struct flow *flow, uint32_t hash)
1086 {
1087     struct cls_rule *head;
1088
1089     HMAP_FOR_EACH_WITH_HASH (head, hmap_node, hash, &table->rules) {
1090         if (flow_equal(&head->flow, flow)) {
1091             return head;
1092         }
1093     }
1094     return NULL;
1095 }
1096
1097 static struct cls_rule *
1098 insert_rule(struct cls_table *table, struct cls_rule *new)
1099 {
1100     struct cls_rule *head;
1101
1102     new->hmap_node.hash = flow_hash(&new->flow, 0);
1103
1104     head = find_equal(table, &new->flow, new->hmap_node.hash);
1105     if (!head) {
1106         hmap_insert(&table->rules, &new->hmap_node, new->hmap_node.hash);
1107         list_init(&new->list);
1108         return NULL;
1109     } else {
1110         /* Scan the list for the insertion point that will keep the list in
1111          * order of decreasing priority. */
1112         struct cls_rule *rule;
1113         FOR_EACH_RULE_IN_LIST (rule, head) {
1114             if (new->priority >= rule->priority) {
1115                 if (rule == head) {
1116                     /* 'new' is the new highest-priority flow in the list. */
1117                     hmap_replace(&table->rules,
1118                                  &rule->hmap_node, &new->hmap_node);
1119                 }
1120
1121                 if (new->priority == rule->priority) {
1122                     list_replace(&new->list, &rule->list);
1123                     return rule;
1124                 } else {
1125                     list_insert(&rule->list, &new->list);
1126                     return NULL;
1127                 }
1128             }
1129         }
1130
1131         /* Insert 'new' at the end of the list. */
1132         list_push_back(&head->list, &new->list);
1133         return NULL;
1134     }
1135 }
1136
1137 static struct cls_rule *
1138 next_rule_in_list__(struct cls_rule *rule)
1139 {
1140     struct cls_rule *next = OBJECT_CONTAINING(rule->list.next, next, list);
1141     return next;
1142 }
1143
1144 static struct cls_rule *
1145 next_rule_in_list(struct cls_rule *rule)
1146 {
1147     struct cls_rule *next = next_rule_in_list__(rule);
1148     return next->priority < rule->priority ? next : NULL;
1149 }
1150
1151 static bool
1152 ipv6_equal_except(const struct in6_addr *a, const struct in6_addr *b,
1153                   const struct in6_addr *mask)
1154 {
1155     int i;
1156
1157 #ifdef s6_addr32
1158     for (i=0; i<4; i++) {
1159         if ((a->s6_addr32[i] ^ b->s6_addr32[i]) & mask->s6_addr32[i]) {
1160             return false;
1161         }
1162     }
1163 #else
1164     for (i=0; i<16; i++) {
1165         if ((a->s6_addr[i] ^ b->s6_addr[i]) & mask->s6_addr[i]) {
1166             return false;
1167         }
1168     }
1169 #endif
1170
1171     return true;
1172 }
1173
1174
1175 static bool
1176 flow_equal_except(const struct flow *a, const struct flow *b,
1177                   const struct flow_wildcards *wildcards)
1178 {
1179     const flow_wildcards_t wc = wildcards->wildcards;
1180     int i;
1181
1182     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 10);
1183
1184     for (i = 0; i < FLOW_N_REGS; i++) {
1185         if ((a->regs[i] ^ b->regs[i]) & wildcards->reg_masks[i]) {
1186             return false;
1187         }
1188     }
1189
1190     return (!((a->tun_id ^ b->tun_id) & wildcards->tun_id_mask)
1191             && !((a->nw_src ^ b->nw_src) & wildcards->nw_src_mask)
1192             && !((a->nw_dst ^ b->nw_dst) & wildcards->nw_dst_mask)
1193             && (wc & FWW_IN_PORT || a->in_port == b->in_port)
1194             && !((a->vlan_tci ^ b->vlan_tci) & wildcards->vlan_tci_mask)
1195             && (wc & FWW_DL_TYPE || a->dl_type == b->dl_type)
1196             && !((a->tp_src ^ b->tp_src) & wildcards->tp_src_mask)
1197             && !((a->tp_dst ^ b->tp_dst) & wildcards->tp_dst_mask)
1198             && (wc & FWW_DL_SRC || eth_addr_equals(a->dl_src, b->dl_src))
1199             && (wc & FWW_DL_DST
1200                 || (!((a->dl_dst[0] ^ b->dl_dst[0]) & 0xfe)
1201                     && a->dl_dst[1] == b->dl_dst[1]
1202                     && a->dl_dst[2] == b->dl_dst[2]
1203                     && a->dl_dst[3] == b->dl_dst[3]
1204                     && a->dl_dst[4] == b->dl_dst[4]
1205                     && a->dl_dst[5] == b->dl_dst[5]))
1206             && (wc & FWW_ETH_MCAST
1207                 || !((a->dl_dst[0] ^ b->dl_dst[0]) & 0x01))
1208             && (wc & FWW_NW_PROTO || a->nw_proto == b->nw_proto)
1209             && (wc & FWW_NW_TTL || a->nw_ttl == b->nw_ttl)
1210             && (wc & FWW_NW_DSCP || !((a->nw_tos ^ b->nw_tos) & IP_DSCP_MASK))
1211             && (wc & FWW_NW_ECN || !((a->nw_tos ^ b->nw_tos) & IP_ECN_MASK))
1212             && !((a->nw_frag ^ b->nw_frag) & wildcards->nw_frag_mask)
1213             && (wc & FWW_ARP_SHA || eth_addr_equals(a->arp_sha, b->arp_sha))
1214             && (wc & FWW_ARP_THA || eth_addr_equals(a->arp_tha, b->arp_tha))
1215             && (wc & FWW_IPV6_LABEL || a->ipv6_label == b->ipv6_label)
1216             && ipv6_equal_except(&a->ipv6_src, &b->ipv6_src,
1217                     &wildcards->ipv6_src_mask)
1218             && ipv6_equal_except(&a->ipv6_dst, &b->ipv6_dst,
1219                     &wildcards->ipv6_dst_mask)
1220             && ipv6_equal_except(&a->nd_target, &b->nd_target,
1221                                  &wildcards->nd_target_mask));
1222 }