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