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