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