classifier: Print ARP opcode as "arp_op" instead of "opcode".
[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 static void zero_wildcards(struct flow *, const struct flow_wildcards *);
49
50 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list. */
51 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD)                               \
52     for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
53 #define FOR_EACH_RULE_IN_LIST_SAFE(RULE, NEXT, HEAD)                    \
54     for ((RULE) = (HEAD);                                               \
55          (RULE) != NULL && ((NEXT) = next_rule_in_list(RULE), true);    \
56          (RULE) = (NEXT))
57
58 static struct cls_rule *next_rule_in_list__(struct cls_rule *);
59 static struct cls_rule *next_rule_in_list(struct cls_rule *);
60
61 static struct cls_table *
62 cls_table_from_hmap_node(const struct hmap_node *node)
63 {
64     return node ? CONTAINER_OF(node, struct cls_table, hmap_node) : NULL;
65 }
66
67 /* Converts the flow in 'flow' into a cls_rule in 'rule', with the given
68  * 'wildcards' and 'priority'. */
69 void
70 cls_rule_init(const struct flow *flow, const struct flow_wildcards *wildcards,
71               unsigned int priority, struct cls_rule *rule)
72 {
73     rule->flow = *flow;
74     rule->wc = *wildcards;
75     rule->priority = priority;
76     cls_rule_zero_wildcarded_fields(rule);
77 }
78
79 /* Converts the flow in 'flow' into an exact-match cls_rule in 'rule', with the
80  * given 'priority'.  (For OpenFlow 1.0, exact-match rule are always highest
81  * priority, so 'priority' should be at least 65535.) */
82 void
83 cls_rule_init_exact(const struct flow *flow,
84                     unsigned int priority, struct cls_rule *rule)
85 {
86     rule->flow = *flow;
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     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_tos(struct cls_rule *rule, uint8_t nw_tos)
322 {
323     rule->wc.wildcards &= ~FWW_NW_TOS;
324     rule->flow.nw_tos = nw_tos & IP_DSCP_MASK;
325 }
326
327 void
328 cls_rule_set_icmp_type(struct cls_rule *rule, uint8_t icmp_type)
329 {
330     rule->wc.wildcards &= ~FWW_TP_SRC;
331     rule->flow.icmp_type = htons(icmp_type);
332
333 }
334
335 void
336 cls_rule_set_icmp_code(struct cls_rule *rule, uint8_t icmp_code)
337 {
338     rule->wc.wildcards &= ~FWW_TP_DST;
339     rule->flow.icmp_code = htons(icmp_code);
340 }
341
342 void
343 cls_rule_set_arp_sha(struct cls_rule *rule, const uint8_t sha[ETH_ADDR_LEN])
344 {
345     rule->wc.wildcards &= ~FWW_ARP_SHA;
346     memcpy(rule->flow.arp_sha, sha, ETH_ADDR_LEN);
347 }
348
349 void
350 cls_rule_set_arp_tha(struct cls_rule *rule, const uint8_t tha[ETH_ADDR_LEN])
351 {
352     rule->wc.wildcards &= ~FWW_ARP_THA;
353     memcpy(rule->flow.arp_tha, tha, ETH_ADDR_LEN);
354 }
355
356 void
357 cls_rule_set_ipv6_src(struct cls_rule *rule, const struct in6_addr *src)
358 {
359     cls_rule_set_ipv6_src_masked(rule, src, &in6addr_exact);
360 }
361
362 bool
363 cls_rule_set_ipv6_src_masked(struct cls_rule *rule, const struct in6_addr *src,
364                              const struct in6_addr *mask)
365 {
366     if (flow_wildcards_set_ipv6_src_mask(&rule->wc, mask)) {
367         rule->flow.ipv6_src = ipv6_addr_bitand(src, mask);
368         return true;
369     } else {
370         return false;
371     }
372 }
373
374 void
375 cls_rule_set_ipv6_dst(struct cls_rule *rule, const struct in6_addr *dst)
376 {
377     cls_rule_set_ipv6_dst_masked(rule, dst, &in6addr_exact);
378 }
379
380 bool
381 cls_rule_set_ipv6_dst_masked(struct cls_rule *rule, const struct in6_addr *dst,
382                              const struct in6_addr *mask)
383 {
384     if (flow_wildcards_set_ipv6_dst_mask(&rule->wc, mask)) {
385         rule->flow.ipv6_dst = ipv6_addr_bitand(dst, mask);
386         return true;
387     } else {
388         return false;
389     }
390 }
391
392 void
393 cls_rule_set_nd_target(struct cls_rule *rule, const struct in6_addr target)
394 {
395     rule->wc.wildcards &= ~FWW_ND_TARGET;
396     rule->flow.nd_target = target;
397 }
398
399 /* Returns true if 'a' and 'b' have the same priority, wildcard the same
400  * fields, and have the same values for fixed fields, otherwise false. */
401 bool
402 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
403 {
404     return (a->priority == b->priority
405             && flow_wildcards_equal(&a->wc, &b->wc)
406             && flow_equal(&a->flow, &b->flow));
407 }
408
409 /* Returns a hash value for the flow, wildcards, and priority in 'rule',
410  * starting from 'basis'. */
411 uint32_t
412 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
413 {
414     uint32_t h0 = flow_hash(&rule->flow, basis);
415     uint32_t h1 = flow_wildcards_hash(&rule->wc, h0);
416     return hash_int(rule->priority, h1);
417 }
418
419 static void
420 format_ip_netmask(struct ds *s, const char *name, ovs_be32 ip,
421                   ovs_be32 netmask)
422 {
423     if (netmask) {
424         ds_put_format(s, "%s="IP_FMT, name, IP_ARGS(&ip));
425         if (netmask != htonl(UINT32_MAX)) {
426             if (ip_is_cidr(netmask)) {
427                 int wcbits = ofputil_netmask_to_wcbits(netmask);
428                 ds_put_format(s, "/%d", 32 - wcbits);
429             } else {
430                 ds_put_format(s, "/"IP_FMT, IP_ARGS(&netmask));
431             }
432         }
433         ds_put_char(s, ',');
434     }
435 }
436
437 static void
438 format_ipv6_netmask(struct ds *s, const char *name,
439                     const struct in6_addr *addr,
440                     const struct in6_addr *netmask)
441 {
442     if (!ipv6_mask_is_any(netmask)) {
443         ds_put_format(s, "%s=", name);
444         print_ipv6_addr(s, addr);
445         if (!ipv6_mask_is_exact(netmask)) {
446             if (ipv6_is_cidr(netmask)) {
447                 int cidr_bits = ipv6_count_cidr_bits(netmask);
448                 ds_put_format(s, "/%d", cidr_bits);
449             } else {
450                 ds_put_char(s, '/');
451                 print_ipv6_addr(s, netmask);
452             }
453         }
454         ds_put_char(s, ',');
455     }
456 }
457
458 void
459 cls_rule_format(const struct cls_rule *rule, struct ds *s)
460 {
461     const struct flow_wildcards *wc = &rule->wc;
462     size_t start_len = s->length;
463     flow_wildcards_t w = wc->wildcards;
464     const struct flow *f = &rule->flow;
465     bool skip_type = false;
466     bool skip_proto = false;
467
468     int i;
469
470     if (rule->priority != OFP_DEFAULT_PRIORITY) {
471         ds_put_format(s, "priority=%d,", rule->priority);
472     }
473
474     if (!(w & FWW_DL_TYPE)) {
475         skip_type = true;
476         if (f->dl_type == htons(ETH_TYPE_IP)) {
477             if (!(w & FWW_NW_PROTO)) {
478                 skip_proto = true;
479                 if (f->nw_proto == IPPROTO_ICMP) {
480                     ds_put_cstr(s, "icmp,");
481                 } else if (f->nw_proto == IPPROTO_TCP) {
482                     ds_put_cstr(s, "tcp,");
483                 } else if (f->nw_proto == IPPROTO_UDP) {
484                     ds_put_cstr(s, "udp,");
485                 } else {
486                     ds_put_cstr(s, "ip,");
487                     skip_proto = false;
488                 }
489             } else {
490                 ds_put_cstr(s, "ip,");
491             }
492         } else if (f->dl_type == htons(ETH_TYPE_IPV6)) {
493             if (!(w & FWW_NW_PROTO)) {
494                 skip_proto = true;
495                 if (f->nw_proto == IPPROTO_ICMPV6) {
496                     ds_put_cstr(s, "icmp6,");
497                 } else if (f->nw_proto == IPPROTO_TCP) {
498                     ds_put_cstr(s, "tcp6,");
499                 } else if (f->nw_proto == IPPROTO_UDP) {
500                     ds_put_cstr(s, "udp6,");
501                 } else {
502                     ds_put_cstr(s, "ipv6,");
503                     skip_proto = false;
504                 }
505             } else {
506                 ds_put_cstr(s, "ipv6,");
507             }
508         } else if (f->dl_type == htons(ETH_TYPE_ARP)) {
509             ds_put_cstr(s, "arp,");
510         } else {
511             skip_type = false;
512         }
513     }
514     for (i = 0; i < FLOW_N_REGS; i++) {
515         switch (wc->reg_masks[i]) {
516         case 0:
517             break;
518         case UINT32_MAX:
519             ds_put_format(s, "reg%d=0x%"PRIx32",", i, f->regs[i]);
520             break;
521         default:
522             ds_put_format(s, "reg%d=0x%"PRIx32"/0x%"PRIx32",",
523                           i, f->regs[i], wc->reg_masks[i]);
524             break;
525         }
526     }
527     switch (wc->tun_id_mask) {
528     case 0:
529         break;
530     case CONSTANT_HTONLL(UINT64_MAX):
531         ds_put_format(s, "tun_id=%#"PRIx64",", ntohll(f->tun_id));
532         break;
533     default:
534         ds_put_format(s, "tun_id=%#"PRIx64"/%#"PRIx64",",
535                       ntohll(f->tun_id), ntohll(wc->tun_id_mask));
536         break;
537     }
538     if (!(w & FWW_IN_PORT)) {
539         ds_put_format(s, "in_port=%"PRIu16",", f->in_port);
540     }
541     if (wc->vlan_tci_mask) {
542         ovs_be16 vid_mask = wc->vlan_tci_mask & htons(VLAN_VID_MASK);
543         ovs_be16 pcp_mask = wc->vlan_tci_mask & htons(VLAN_PCP_MASK);
544         ovs_be16 cfi = wc->vlan_tci_mask & htons(VLAN_CFI);
545
546         if (cfi && f->vlan_tci & htons(VLAN_CFI)
547             && (!vid_mask || vid_mask == htons(VLAN_VID_MASK))
548             && (!pcp_mask || pcp_mask == htons(VLAN_PCP_MASK))
549             && (vid_mask || pcp_mask)) {
550             if (vid_mask) {
551                 ds_put_format(s, "dl_vlan=%"PRIu16",",
552                               vlan_tci_to_vid(f->vlan_tci));
553             }
554             if (pcp_mask) {
555                 ds_put_format(s, "dl_vlan_pcp=%d,",
556                               vlan_tci_to_pcp(f->vlan_tci));
557             }
558         } else if (wc->vlan_tci_mask == htons(0xffff)) {
559             ds_put_format(s, "vlan_tci=0x%04"PRIx16",", ntohs(f->vlan_tci));
560         } else {
561             ds_put_format(s, "vlan_tci=0x%04"PRIx16"/0x%04"PRIx16",",
562                           ntohs(f->vlan_tci), ntohs(wc->vlan_tci_mask));
563         }
564     }
565     if (!(w & FWW_DL_SRC)) {
566         ds_put_format(s, "dl_src="ETH_ADDR_FMT",", ETH_ADDR_ARGS(f->dl_src));
567     }
568     switch (w & (FWW_DL_DST | FWW_ETH_MCAST)) {
569     case 0:
570         ds_put_format(s, "dl_dst="ETH_ADDR_FMT",", ETH_ADDR_ARGS(f->dl_dst));
571         break;
572     case FWW_DL_DST:
573         ds_put_format(s, "dl_dst="ETH_ADDR_FMT"/01:00:00:00:00:00,",
574                       ETH_ADDR_ARGS(f->dl_dst));
575         break;
576     case FWW_ETH_MCAST:
577         ds_put_format(s, "dl_dst="ETH_ADDR_FMT"/fe:ff:ff:ff:ff:ff,",
578                       ETH_ADDR_ARGS(f->dl_dst));
579         break;
580     case FWW_DL_DST | FWW_ETH_MCAST:
581         break;
582     }
583     if (!skip_type && !(w & FWW_DL_TYPE)) {
584         ds_put_format(s, "dl_type=0x%04"PRIx16",", ntohs(f->dl_type));
585     }
586     if (f->dl_type == htons(ETH_TYPE_IPV6)) {
587         format_ipv6_netmask(s, "ipv6_src", &f->ipv6_src, &wc->ipv6_src_mask);
588         format_ipv6_netmask(s, "ipv6_dst", &f->ipv6_dst, &wc->ipv6_dst_mask);
589     } else {
590         format_ip_netmask(s, "nw_src", f->nw_src, wc->nw_src_mask);
591         format_ip_netmask(s, "nw_dst", f->nw_dst, wc->nw_dst_mask);
592     }
593     if (!skip_proto && !(w & FWW_NW_PROTO)) {
594         if (f->dl_type == htons(ETH_TYPE_ARP)) {
595             ds_put_format(s, "arp_op=%"PRIu8",", f->nw_proto);
596         } else {
597             ds_put_format(s, "nw_proto=%"PRIu8",", f->nw_proto);
598         }
599     }
600     if (f->dl_type == htons(ETH_TYPE_ARP)) {
601         if (!(w & FWW_ARP_SHA)) {
602             ds_put_format(s, "arp_sha="ETH_ADDR_FMT",",
603                     ETH_ADDR_ARGS(f->arp_sha));
604         }
605         if (!(w & FWW_ARP_THA)) {
606             ds_put_format(s, "arp_tha="ETH_ADDR_FMT",",
607                     ETH_ADDR_ARGS(f->arp_tha));
608         }
609     }
610     if (!(w & FWW_NW_TOS)) {
611         ds_put_format(s, "nw_tos=%"PRIu8",", f->nw_tos);
612     }
613     if (f->nw_proto == IPPROTO_ICMP) {
614         if (!(w & FWW_TP_SRC)) {
615             ds_put_format(s, "icmp_type=%"PRIu16",", ntohs(f->tp_src));
616         }
617         if (!(w & FWW_TP_DST)) {
618             ds_put_format(s, "icmp_code=%"PRIu16",", ntohs(f->tp_dst));
619         }
620     } else if (f->nw_proto == IPPROTO_ICMPV6) {
621         if (!(w & FWW_TP_SRC)) {
622             ds_put_format(s, "icmp_type=%"PRIu16",", ntohs(f->tp_src));
623         }
624         if (!(w & FWW_TP_DST)) {
625             ds_put_format(s, "icmp_code=%"PRIu16",", ntohs(f->tp_dst));
626         }
627         if (!(w & FWW_ND_TARGET)) {
628             ds_put_cstr(s, "nd_target=");
629             print_ipv6_addr(s, &f->nd_target);
630             ds_put_char(s, ',');
631         }
632         if (!(w & FWW_ARP_SHA)) {
633             ds_put_format(s, "nd_sll="ETH_ADDR_FMT",", 
634                     ETH_ADDR_ARGS(f->arp_sha));
635         }
636         if (!(w & FWW_ARP_THA)) {
637             ds_put_format(s, "nd_tll="ETH_ADDR_FMT",", 
638                     ETH_ADDR_ARGS(f->arp_tha));
639         }
640    } else {
641         if (!(w & FWW_TP_SRC)) {
642             ds_put_format(s, "tp_src=%"PRIu16",", ntohs(f->tp_src));
643         }
644         if (!(w & FWW_TP_DST)) {
645             ds_put_format(s, "tp_dst=%"PRIu16",", ntohs(f->tp_dst));
646         }
647     }
648
649     if (s->length > start_len && ds_last(s) == ',') {
650         s->length--;
651     }
652 }
653
654 /* Converts 'rule' to a string and returns the string.  The caller must free
655  * the string (with free()). */
656 char *
657 cls_rule_to_string(const struct cls_rule *rule)
658 {
659     struct ds s = DS_EMPTY_INITIALIZER;
660     cls_rule_format(rule, &s);
661     return ds_steal_cstr(&s);
662 }
663
664 void
665 cls_rule_print(const struct cls_rule *rule)
666 {
667     char *s = cls_rule_to_string(rule);
668     puts(s);
669     free(s);
670 }
671 \f
672 /* Initializes 'cls' as a classifier that initially contains no classification
673  * rules. */
674 void
675 classifier_init(struct classifier *cls)
676 {
677     cls->n_rules = 0;
678     hmap_init(&cls->tables);
679 }
680
681 /* Destroys 'cls'.  Rules within 'cls', if any, are not freed; this is the
682  * caller's responsibility. */
683 void
684 classifier_destroy(struct classifier *cls)
685 {
686     if (cls) {
687         struct cls_table *table, *next_table;
688
689         HMAP_FOR_EACH_SAFE (table, next_table, hmap_node, &cls->tables) {
690             hmap_destroy(&table->rules);
691             hmap_remove(&cls->tables, &table->hmap_node);
692             free(table);
693         }
694         hmap_destroy(&cls->tables);
695     }
696 }
697
698 /* Returns true if 'cls' contains no classification rules, false otherwise. */
699 bool
700 classifier_is_empty(const struct classifier *cls)
701 {
702     return cls->n_rules == 0;
703 }
704
705 /* Returns the number of rules in 'classifier'. */
706 int
707 classifier_count(const struct classifier *cls)
708 {
709     return cls->n_rules;
710 }
711
712 /* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
713  * must not modify or free it.
714  *
715  * If 'cls' already contains an identical rule (including wildcards, values of
716  * fixed fields, and priority), replaces the old rule by 'rule' and returns the
717  * rule that was replaced.  The caller takes ownership of the returned rule and
718  * is thus responsible for freeing it, etc., as necessary.
719  *
720  * Returns NULL if 'cls' does not contain a rule with an identical key, after
721  * inserting the new rule.  In this case, no rules are displaced by the new
722  * rule, even rules that cannot have any effect because the new rule matches a
723  * superset of their flows and has higher priority. */
724 struct cls_rule *
725 classifier_replace(struct classifier *cls, struct cls_rule *rule)
726 {
727     struct cls_rule *old_rule;
728     struct cls_table *table;
729
730     table = find_table(cls, &rule->wc);
731     if (!table) {
732         table = insert_table(cls, &rule->wc);
733     }
734
735     old_rule = insert_rule(table, rule);
736     if (!old_rule) {
737         table->n_table_rules++;
738         cls->n_rules++;
739     }
740     return old_rule;
741 }
742
743 /* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
744  * must not modify or free it.
745  *
746  * 'cls' must not contain an identical rule (including wildcards, values of
747  * fixed fields, and priority).  Use classifier_find_rule_exactly() to find
748  * such a rule. */
749 void
750 classifier_insert(struct classifier *cls, struct cls_rule *rule)
751 {
752     struct cls_rule *displaced_rule = classifier_replace(cls, rule);
753     assert(!displaced_rule);
754 }
755
756 /* Removes 'rule' from 'cls'.  It is the caller's responsibility to free
757  * 'rule', if this is desirable. */
758 void
759 classifier_remove(struct classifier *cls, struct cls_rule *rule)
760 {
761     struct cls_rule *head;
762     struct cls_table *table;
763
764     table = find_table(cls, &rule->wc);
765     head = find_equal(table, &rule->flow, rule->hmap_node.hash);
766     if (head != rule) {
767         list_remove(&rule->list);
768     } else if (list_is_empty(&rule->list)) {
769         hmap_remove(&table->rules, &rule->hmap_node);
770     } else {
771         struct cls_rule *next = CONTAINER_OF(rule->list.next,
772                                              struct cls_rule, list);
773
774         list_remove(&rule->list);
775         hmap_replace(&table->rules, &rule->hmap_node, &next->hmap_node);
776     }
777
778     if (--table->n_table_rules == 0) {
779         destroy_table(cls, table);
780     }
781
782     cls->n_rules--;
783 }
784
785 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
786  * Returns a null pointer if no rules in 'cls' match 'flow'.  If multiple rules
787  * of equal priority match 'flow', returns one arbitrarily. */
788 struct cls_rule *
789 classifier_lookup(const struct classifier *cls, const struct flow *flow)
790 {
791     struct cls_table *table;
792     struct cls_rule *best;
793
794     best = NULL;
795     HMAP_FOR_EACH (table, hmap_node, &cls->tables) {
796         struct cls_rule *rule = find_match(table, flow);
797         if (rule && (!best || rule->priority > best->priority)) {
798             best = rule;
799         }
800     }
801     return best;
802 }
803
804 /* Finds and returns a rule in 'cls' with exactly the same priority and
805  * matching criteria as 'target'.  Returns a null pointer if 'cls' doesn't
806  * contain an exact match. */
807 struct cls_rule *
808 classifier_find_rule_exactly(const struct classifier *cls,
809                              const struct cls_rule *target)
810 {
811     struct cls_rule *head, *rule;
812     struct cls_table *table;
813
814     table = find_table(cls, &target->wc);
815     if (!table) {
816         return NULL;
817     }
818
819     head = find_equal(table, &target->flow, flow_hash(&target->flow, 0));
820     FOR_EACH_RULE_IN_LIST (rule, head) {
821         if (target->priority >= rule->priority) {
822             return target->priority == rule->priority ? rule : NULL;
823         }
824     }
825     return NULL;
826 }
827
828 /* Checks if 'target' would overlap any other rule in 'cls'.  Two rules are
829  * considered to overlap if both rules have the same priority and a packet
830  * could match both. */
831 bool
832 classifier_rule_overlaps(const struct classifier *cls,
833                          const struct cls_rule *target)
834 {
835     struct cls_table *table;
836
837     HMAP_FOR_EACH (table, hmap_node, &cls->tables) {
838         struct flow_wildcards wc;
839         struct cls_rule *head;
840
841         flow_wildcards_combine(&wc, &target->wc, &table->wc);
842         HMAP_FOR_EACH (head, hmap_node, &table->rules) {
843             struct cls_rule *rule;
844
845             FOR_EACH_RULE_IN_LIST (rule, head) {
846                 if (rule->priority == target->priority
847                     && flow_equal_except(&target->flow, &rule->flow, &wc)) {
848                     return true;
849                 }
850             }
851         }
852     }
853
854     return false;
855 }
856 \f
857 /* Iteration. */
858
859 static bool
860 rule_matches(const struct cls_rule *rule, const struct cls_rule *target)
861 {
862     return (!target
863             || flow_equal_except(&rule->flow, &target->flow, &target->wc));
864 }
865
866 static struct cls_rule *
867 search_table(const struct cls_table *table, const struct cls_rule *target)
868 {
869     if (!target || !flow_wildcards_has_extra(&table->wc, &target->wc)) {
870         struct cls_rule *rule;
871
872         HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
873             if (rule_matches(rule, target)) {
874                 return rule;
875             }
876         }
877     }
878     return NULL;
879 }
880
881 /* Initializes 'cursor' for iterating through 'cls' rules that exactly match
882  * 'target' or are more specific than 'target'.  That is, a given 'rule'
883  * matches 'target' if, for every field:
884  *
885  *   - 'target' and 'rule' specify the same (non-wildcarded) value for the
886  *     field, or
887  *
888  *   - 'target' wildcards the field,
889  *
890  * but not if:
891  *
892  *   - 'target' and 'rule' specify different values for the field, or
893  *
894  *   - 'target' specifies a value for the field but 'rule' wildcards it.
895  *
896  * Equivalently, the truth table for whether a field matches is:
897  *
898  *                                     rule
899  *
900  *                             wildcard    exact
901  *                            +---------+---------+
902  *                   t   wild |   yes   |   yes   |
903  *                   a   card |         |         |
904  *                   r        +---------+---------+
905  *                   g  exact |    no   |if values|
906  *                   e        |         |are equal|
907  *                   t        +---------+---------+
908  *
909  * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
910  * commands and by OpenFlow 1.0 aggregate and flow stats.
911  *
912  * Ignores target->priority.
913  *
914  * 'target' may be NULL to iterate over every rule in 'cls'. */
915 void
916 cls_cursor_init(struct cls_cursor *cursor, const struct classifier *cls,
917                 const struct cls_rule *target)
918 {
919     cursor->cls = cls;
920     cursor->target = target;
921 }
922
923 /* Returns the first matching cls_rule in 'cursor''s iteration, or a null
924  * pointer if there are no matches. */
925 struct cls_rule *
926 cls_cursor_first(struct cls_cursor *cursor)
927 {
928     struct cls_table *table;
929
930     for (table = classifier_first_table(cursor->cls); table;
931          table = classifier_next_table(cursor->cls, table)) {
932         struct cls_rule *rule = search_table(table, cursor->target);
933         if (rule) {
934             cursor->table = table;
935             return rule;
936         }
937     }
938
939     return NULL;
940 }
941
942 /* Returns the next matching cls_rule in 'cursor''s iteration, or a null
943  * pointer if there are no more matches. */
944 struct cls_rule *
945 cls_cursor_next(struct cls_cursor *cursor, struct cls_rule *rule)
946 {
947     const struct cls_table *table;
948     struct cls_rule *next;
949
950     next = next_rule_in_list__(rule);
951     if (next->priority < rule->priority) {
952         return next;
953     }
954
955     /* 'next' is the head of the list, that is, the rule that is included in
956      * the table's hmap.  (This is important when the classifier contains rules
957      * that differ only in priority.) */
958     rule = next;
959     HMAP_FOR_EACH_CONTINUE (rule, hmap_node, &cursor->table->rules) {
960         if (rule_matches(rule, cursor->target)) {
961             return rule;
962         }
963     }
964
965     for (table = classifier_next_table(cursor->cls, cursor->table); table;
966          table = classifier_next_table(cursor->cls, table)) {
967         rule = search_table(table, cursor->target);
968         if (rule) {
969             cursor->table = table;
970             return rule;
971         }
972     }
973
974     return NULL;
975 }
976 \f
977 static struct cls_table *
978 find_table(const struct classifier *cls, const struct flow_wildcards *wc)
979 {
980     struct cls_table *table;
981
982     HMAP_FOR_EACH_IN_BUCKET (table, hmap_node, flow_wildcards_hash(wc, 0),
983                              &cls->tables) {
984         if (flow_wildcards_equal(wc, &table->wc)) {
985             return table;
986         }
987     }
988     return NULL;
989 }
990
991 static struct cls_table *
992 insert_table(struct classifier *cls, const struct flow_wildcards *wc)
993 {
994     struct cls_table *table;
995
996     table = xzalloc(sizeof *table);
997     hmap_init(&table->rules);
998     table->wc = *wc;
999     hmap_insert(&cls->tables, &table->hmap_node, flow_wildcards_hash(wc, 0));
1000
1001     return table;
1002 }
1003
1004 static struct cls_table *
1005 classifier_first_table(const struct classifier *cls)
1006 {
1007     return cls_table_from_hmap_node(hmap_first(&cls->tables));
1008 }
1009
1010 static struct cls_table *
1011 classifier_next_table(const struct classifier *cls,
1012                       const struct cls_table *table)
1013 {
1014     return cls_table_from_hmap_node(hmap_next(&cls->tables,
1015                                               &table->hmap_node));
1016 }
1017
1018 static void
1019 destroy_table(struct classifier *cls, struct cls_table *table)
1020 {
1021     hmap_remove(&cls->tables, &table->hmap_node);
1022     hmap_destroy(&table->rules);
1023     free(table);
1024 }
1025
1026 static struct cls_rule *
1027 find_match(const struct cls_table *table, const struct flow *flow)
1028 {
1029     struct cls_rule *rule;
1030     struct flow f;
1031
1032     f = *flow;
1033     zero_wildcards(&f, &table->wc);
1034     HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, flow_hash(&f, 0),
1035                              &table->rules) {
1036         if (flow_equal(&f, &rule->flow)) {
1037             return rule;
1038         }
1039     }
1040     return NULL;
1041 }
1042
1043 static struct cls_rule *
1044 find_equal(struct cls_table *table, const struct flow *flow, uint32_t hash)
1045 {
1046     struct cls_rule *head;
1047
1048     HMAP_FOR_EACH_WITH_HASH (head, hmap_node, hash, &table->rules) {
1049         if (flow_equal(&head->flow, flow)) {
1050             return head;
1051         }
1052     }
1053     return NULL;
1054 }
1055
1056 static struct cls_rule *
1057 insert_rule(struct cls_table *table, struct cls_rule *new)
1058 {
1059     struct cls_rule *head;
1060
1061     new->hmap_node.hash = flow_hash(&new->flow, 0);
1062
1063     head = find_equal(table, &new->flow, new->hmap_node.hash);
1064     if (!head) {
1065         hmap_insert(&table->rules, &new->hmap_node, new->hmap_node.hash);
1066         list_init(&new->list);
1067         return NULL;
1068     } else {
1069         /* Scan the list for the insertion point that will keep the list in
1070          * order of decreasing priority. */
1071         struct cls_rule *rule;
1072         FOR_EACH_RULE_IN_LIST (rule, head) {
1073             if (new->priority >= rule->priority) {
1074                 if (rule == head) {
1075                     /* 'new' is the new highest-priority flow in the list. */
1076                     hmap_replace(&table->rules,
1077                                  &rule->hmap_node, &new->hmap_node);
1078                 }
1079
1080                 if (new->priority == rule->priority) {
1081                     list_replace(&new->list, &rule->list);
1082                     return rule;
1083                 } else {
1084                     list_insert(&rule->list, &new->list);
1085                     return NULL;
1086                 }
1087             }
1088         }
1089
1090         /* Insert 'new' at the end of the list. */
1091         list_push_back(&head->list, &new->list);
1092         return NULL;
1093     }
1094 }
1095
1096 static struct cls_rule *
1097 next_rule_in_list__(struct cls_rule *rule)
1098 {
1099     struct cls_rule *next = OBJECT_CONTAINING(rule->list.next, next, list);
1100     return next;
1101 }
1102
1103 static struct cls_rule *
1104 next_rule_in_list(struct cls_rule *rule)
1105 {
1106     struct cls_rule *next = next_rule_in_list__(rule);
1107     return next->priority < rule->priority ? next : NULL;
1108 }
1109
1110 static bool
1111 ipv6_equal_except(const struct in6_addr *a, const struct in6_addr *b,
1112                   const struct in6_addr *mask)
1113 {
1114     int i;
1115
1116 #ifdef s6_addr32
1117     for (i=0; i<4; i++) {
1118         if ((a->s6_addr32[i] ^ b->s6_addr32[i]) & mask->s6_addr32[i]) {
1119             return false;
1120         }
1121     }
1122 #else
1123     for (i=0; i<16; i++) {
1124         if ((a->s6_addr[i] ^ b->s6_addr[i]) & mask->s6_addr[i]) {
1125             return false;
1126         }
1127     }
1128 #endif
1129
1130     return true;
1131 }
1132
1133
1134 static bool
1135 flow_equal_except(const struct flow *a, const struct flow *b,
1136                   const struct flow_wildcards *wildcards)
1137 {
1138     const flow_wildcards_t wc = wildcards->wildcards;
1139     int i;
1140
1141     BUILD_ASSERT_DECL(FLOW_SIG_SIZE == 100 + FLOW_N_REGS * 4);
1142
1143     for (i = 0; i < FLOW_N_REGS; i++) {
1144         if ((a->regs[i] ^ b->regs[i]) & wildcards->reg_masks[i]) {
1145             return false;
1146         }
1147     }
1148
1149     return (!((a->tun_id ^ b->tun_id) & wildcards->tun_id_mask)
1150             && !((a->nw_src ^ b->nw_src) & wildcards->nw_src_mask)
1151             && !((a->nw_dst ^ b->nw_dst) & wildcards->nw_dst_mask)
1152             && (wc & FWW_IN_PORT || a->in_port == b->in_port)
1153             && !((a->vlan_tci ^ b->vlan_tci) & wildcards->vlan_tci_mask)
1154             && (wc & FWW_DL_TYPE || a->dl_type == b->dl_type)
1155             && (wc & FWW_TP_SRC || a->tp_src == b->tp_src)
1156             && (wc & FWW_TP_DST || a->tp_dst == b->tp_dst)
1157             && (wc & FWW_DL_SRC || eth_addr_equals(a->dl_src, b->dl_src))
1158             && (wc & FWW_DL_DST
1159                 || (!((a->dl_dst[0] ^ b->dl_dst[0]) & 0xfe)
1160                     && a->dl_dst[1] == b->dl_dst[1]
1161                     && a->dl_dst[2] == b->dl_dst[2]
1162                     && a->dl_dst[3] == b->dl_dst[3]
1163                     && a->dl_dst[4] == b->dl_dst[4]
1164                     && a->dl_dst[5] == b->dl_dst[5]))
1165             && (wc & FWW_ETH_MCAST
1166                 || !((a->dl_dst[0] ^ b->dl_dst[0]) & 0x01))
1167             && (wc & FWW_NW_PROTO || a->nw_proto == b->nw_proto)
1168             && (wc & FWW_NW_TOS || a->nw_tos == b->nw_tos)
1169             && (wc & FWW_ARP_SHA || eth_addr_equals(a->arp_sha, b->arp_sha))
1170             && (wc & FWW_ARP_THA || eth_addr_equals(a->arp_tha, b->arp_tha))
1171             && ipv6_equal_except(&a->ipv6_src, &b->ipv6_src,
1172                     &wildcards->ipv6_src_mask)
1173             && ipv6_equal_except(&a->ipv6_dst, &b->ipv6_dst,
1174                     &wildcards->ipv6_dst_mask)
1175             && (wc & FWW_ND_TARGET 
1176                 || ipv6_addr_equals(&a->nd_target, &b->nd_target)));
1177 }
1178
1179 static void
1180 zero_wildcards(struct flow *flow, const struct flow_wildcards *wildcards)
1181 {
1182     const flow_wildcards_t wc = wildcards->wildcards;
1183     int i;
1184
1185     BUILD_ASSERT_DECL(FLOW_SIG_SIZE == 100 + 4 * FLOW_N_REGS);
1186
1187     for (i = 0; i < FLOW_N_REGS; i++) {
1188         flow->regs[i] &= wildcards->reg_masks[i];
1189     }
1190     flow->tun_id &= wildcards->tun_id_mask;
1191     flow->nw_src &= wildcards->nw_src_mask;
1192     flow->nw_dst &= wildcards->nw_dst_mask;
1193     if (wc & FWW_IN_PORT) {
1194         flow->in_port = 0;
1195     }
1196     flow->vlan_tci &= wildcards->vlan_tci_mask;
1197     if (wc & FWW_DL_TYPE) {
1198         flow->dl_type = 0;
1199     }
1200     if (wc & FWW_TP_SRC) {
1201         flow->tp_src = 0;
1202     }
1203     if (wc & FWW_TP_DST) {
1204         flow->tp_dst = 0;
1205     }
1206     if (wc & FWW_DL_SRC) {
1207         memset(flow->dl_src, 0, sizeof flow->dl_src);
1208     }
1209     if (wc & FWW_DL_DST) {
1210         flow->dl_dst[0] &= 0x01;
1211         memset(&flow->dl_dst[1], 0, 5);
1212     }
1213     if (wc & FWW_ETH_MCAST) {
1214         flow->dl_dst[0] &= 0xfe;
1215     }
1216     if (wc & FWW_NW_PROTO) {
1217         flow->nw_proto = 0;
1218     }
1219     if (wc & FWW_NW_TOS) {
1220         flow->nw_tos = 0;
1221     }
1222     if (wc & FWW_ARP_SHA) {
1223         memset(flow->arp_sha, 0, sizeof flow->arp_sha);
1224     }
1225     if (wc & FWW_ARP_THA) {
1226         memset(flow->arp_tha, 0, sizeof flow->arp_tha);
1227     }
1228     flow->ipv6_src = ipv6_addr_bitand(&flow->ipv6_src,
1229             &wildcards->ipv6_src_mask);
1230     flow->ipv6_dst = ipv6_addr_bitand(&flow->ipv6_dst,
1231             &wildcards->ipv6_dst_mask);
1232     if (wc & FWW_ND_TARGET) {
1233         memset(&flow->nd_target, 0, sizeof flow->nd_target);
1234     }
1235 }