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