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