nicira-ext: Support matching ARP source and target hardware addresses.
[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 odp_port)
146 {
147     rule->wc.wildcards &= ~FWW_IN_PORT;
148     rule->flow.in_port = odp_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 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 void
173 cls_rule_set_dl_tci(struct cls_rule *rule, ovs_be16 tci)
174 {
175     cls_rule_set_dl_tci_masked(rule, tci, htons(0xffff));
176 }
177
178 void
179 cls_rule_set_dl_tci_masked(struct cls_rule *rule, ovs_be16 tci, ovs_be16 mask)
180 {
181     rule->flow.vlan_tci = tci & mask;
182     rule->wc.vlan_tci_mask = mask;
183 }
184
185 /* Modifies 'rule' so that the VLAN VID is wildcarded.  If the PCP is already
186  * wildcarded, then 'rule' will match a packet regardless of whether it has an
187  * 802.1Q header or not. */
188 void
189 cls_rule_set_any_vid(struct cls_rule *rule)
190 {
191     if (rule->wc.vlan_tci_mask & htons(VLAN_PCP_MASK)) {
192         rule->wc.vlan_tci_mask &= ~htons(VLAN_VID_MASK);
193         rule->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
194     } else {
195         cls_rule_set_dl_tci_masked(rule, htons(0), htons(0));
196     }
197 }
198
199 /* Modifies 'rule' depending on 'dl_vlan':
200  *
201  *   - If 'dl_vlan' is htons(OFP_VLAN_NONE), makes 'rule' match only packets
202  *     without an 802.1Q header.
203  *
204  *   - Otherwise, makes 'rule' match only packets with an 802.1Q header whose
205  *     VID equals the low 12 bits of 'dl_vlan'.
206  */
207 void
208 cls_rule_set_dl_vlan(struct cls_rule *rule, ovs_be16 dl_vlan)
209 {
210     if (dl_vlan == htons(OFP_VLAN_NONE)) {
211         cls_rule_set_dl_tci(rule, htons(0));
212     } else {
213         dl_vlan &= htons(VLAN_VID_MASK);
214         rule->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
215         rule->flow.vlan_tci |= htons(VLAN_CFI) | dl_vlan;
216         rule->wc.vlan_tci_mask |= htons(VLAN_VID_MASK | VLAN_CFI);
217     }
218 }
219
220 /* Modifies 'rule' so that the VLAN PCP is wildcarded.  If the VID is already
221  * wildcarded, then 'rule' will match a packet regardless of whether it has an
222  * 802.1Q header or not. */
223 void
224 cls_rule_set_any_pcp(struct cls_rule *rule)
225 {
226     if (rule->wc.vlan_tci_mask & htons(VLAN_VID_MASK)) {
227         rule->wc.vlan_tci_mask &= ~htons(VLAN_PCP_MASK);
228         rule->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
229     } else {
230         cls_rule_set_dl_tci_masked(rule, htons(0), htons(0));
231     }
232 }
233
234 /* Modifies 'rule' so that it matches only packets with an 802.1Q header whose
235  * PCP equals the low 3 bits of 'dl_vlan_pcp'. */
236 void
237 cls_rule_set_dl_vlan_pcp(struct cls_rule *rule, uint8_t dl_vlan_pcp)
238 {
239     dl_vlan_pcp &= 0x07;
240     rule->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
241     rule->flow.vlan_tci |= htons((dl_vlan_pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
242     rule->wc.vlan_tci_mask |= htons(VLAN_CFI | VLAN_PCP_MASK);
243 }
244
245 void
246 cls_rule_set_tp_src(struct cls_rule *rule, ovs_be16 tp_src)
247 {
248     rule->wc.wildcards &= ~FWW_TP_SRC;
249     rule->flow.tp_src = tp_src;
250 }
251
252 void
253 cls_rule_set_tp_dst(struct cls_rule *rule, ovs_be16 tp_dst)
254 {
255     rule->wc.wildcards &= ~FWW_TP_DST;
256     rule->flow.tp_dst = tp_dst;
257 }
258
259 void
260 cls_rule_set_nw_proto(struct cls_rule *rule, uint8_t nw_proto)
261 {
262     rule->wc.wildcards &= ~FWW_NW_PROTO;
263     rule->flow.nw_proto = nw_proto;
264 }
265
266 void
267 cls_rule_set_nw_src(struct cls_rule *rule, ovs_be32 nw_src)
268 {
269     cls_rule_set_nw_src_masked(rule, nw_src, htonl(UINT32_MAX));
270 }
271
272 bool
273 cls_rule_set_nw_src_masked(struct cls_rule *rule, ovs_be32 ip, ovs_be32 mask)
274 {
275     if (flow_wildcards_set_nw_src_mask(&rule->wc, mask)) {
276         rule->flow.nw_src = ip & mask;
277         return true;
278     } else {
279         return false;
280     }
281 }
282
283 void
284 cls_rule_set_nw_dst(struct cls_rule *rule, ovs_be32 nw_dst)
285 {
286     cls_rule_set_nw_dst_masked(rule, nw_dst, htonl(UINT32_MAX));
287 }
288
289 bool
290 cls_rule_set_nw_dst_masked(struct cls_rule *rule, ovs_be32 ip, ovs_be32 mask)
291 {
292     if (flow_wildcards_set_nw_dst_mask(&rule->wc, mask)) {
293         rule->flow.nw_dst = ip & mask;
294         return true;
295     } else {
296         return false;
297     }
298 }
299
300 void
301 cls_rule_set_nw_tos(struct cls_rule *rule, uint8_t nw_tos)
302 {
303     rule->wc.wildcards &= ~FWW_NW_TOS;
304     rule->flow.nw_tos = nw_tos & IP_DSCP_MASK;
305 }
306
307 void
308 cls_rule_set_icmp_type(struct cls_rule *rule, uint8_t icmp_type)
309 {
310     rule->wc.wildcards &= ~FWW_TP_SRC;
311     rule->flow.icmp_type = htons(icmp_type);
312
313 }
314
315 void
316 cls_rule_set_icmp_code(struct cls_rule *rule, uint8_t icmp_code)
317 {
318     rule->wc.wildcards &= ~FWW_TP_DST;
319     rule->flow.icmp_code = htons(icmp_code);
320 }
321
322 void
323 cls_rule_set_arp_sha(struct cls_rule *rule, const uint8_t sha[ETH_ADDR_LEN])
324 {
325     rule->wc.wildcards &= ~FWW_ARP_SHA;
326     memcpy(rule->flow.arp_sha, sha, ETH_ADDR_LEN);
327 }
328
329 void
330 cls_rule_set_arp_tha(struct cls_rule *rule, const uint8_t tha[ETH_ADDR_LEN])
331 {
332     rule->wc.wildcards &= ~FWW_ARP_THA;
333     memcpy(rule->flow.arp_tha, tha, ETH_ADDR_LEN);
334 }
335
336 /* Returns true if 'a' and 'b' have the same priority, wildcard the same
337  * fields, and have the same values for fixed fields, otherwise false. */
338 bool
339 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
340 {
341     return (a->priority == b->priority
342             && flow_wildcards_equal(&a->wc, &b->wc)
343             && flow_equal(&a->flow, &b->flow));
344 }
345
346 static void
347 format_ip_netmask(struct ds *s, const char *name, ovs_be32 ip,
348                   ovs_be32 netmask)
349 {
350     if (netmask) {
351         ds_put_format(s, "%s="IP_FMT, name, IP_ARGS(&ip));
352         if (netmask != htonl(UINT32_MAX)) {
353             if (ip_is_cidr(netmask)) {
354                 int wcbits = ofputil_netmask_to_wcbits(netmask);
355                 ds_put_format(s, "/%d", 32 - wcbits);
356             } else {
357                 ds_put_format(s, "/"IP_FMT, IP_ARGS(&netmask));
358             }
359         }
360         ds_put_char(s, ',');
361     }
362 }
363
364 void
365 cls_rule_format(const struct cls_rule *rule, struct ds *s)
366 {
367     const struct flow_wildcards *wc = &rule->wc;
368     size_t start_len = s->length;
369     flow_wildcards_t w = wc->wildcards;
370     const struct flow *f = &rule->flow;
371     bool skip_type = false;
372     bool skip_proto = false;
373
374     int i;
375
376     if (rule->priority != OFP_DEFAULT_PRIORITY) {
377         ds_put_format(s, "priority=%d,", rule->priority);
378     }
379
380     if (!(w & FWW_DL_TYPE)) {
381         skip_type = true;
382         if (f->dl_type == htons(ETH_TYPE_IP)) {
383             if (!(w & FWW_NW_PROTO)) {
384                 skip_proto = true;
385                 if (f->nw_proto == IPPROTO_ICMP) {
386                     ds_put_cstr(s, "icmp,");
387                 } else if (f->nw_proto == IPPROTO_TCP) {
388                     ds_put_cstr(s, "tcp,");
389                 } else if (f->nw_proto == IPPROTO_UDP) {
390                     ds_put_cstr(s, "udp,");
391                 } else {
392                     ds_put_cstr(s, "ip,");
393                     skip_proto = false;
394                 }
395             } else {
396                 ds_put_cstr(s, "ip,");
397             }
398         } else if (f->dl_type == htons(ETH_TYPE_ARP)) {
399             ds_put_cstr(s, "arp,");
400         } else {
401             skip_type = false;
402         }
403     }
404     for (i = 0; i < FLOW_N_REGS; i++) {
405         switch (wc->reg_masks[i]) {
406         case 0:
407             break;
408         case UINT32_MAX:
409             ds_put_format(s, "reg%d=0x%"PRIx32",", i, f->regs[i]);
410             break;
411         default:
412             ds_put_format(s, "reg%d=0x%"PRIx32"/0x%"PRIx32",",
413                           i, f->regs[i], wc->reg_masks[i]);
414             break;
415         }
416     }
417     switch (wc->tun_id_mask) {
418     case 0:
419         break;
420     case CONSTANT_HTONLL(UINT64_MAX):
421         ds_put_format(s, "tun_id=%#"PRIx64",", ntohll(f->tun_id));
422         break;
423     default:
424         ds_put_format(s, "tun_id=%#"PRIx64"/%#"PRIx64",",
425                       ntohll(f->tun_id), ntohll(wc->tun_id_mask));
426         break;
427     }
428     if (!(w & FWW_IN_PORT)) {
429         ds_put_format(s, "in_port=%"PRIu16",",
430                       odp_port_to_ofp_port(f->in_port));
431     }
432     if (wc->vlan_tci_mask) {
433         ovs_be16 vid_mask = wc->vlan_tci_mask & htons(VLAN_VID_MASK);
434         ovs_be16 pcp_mask = wc->vlan_tci_mask & htons(VLAN_PCP_MASK);
435         ovs_be16 cfi = wc->vlan_tci_mask & htons(VLAN_CFI);
436
437         if (cfi && f->vlan_tci & htons(VLAN_CFI)
438             && (!vid_mask || vid_mask == htons(VLAN_VID_MASK))
439             && (!pcp_mask || pcp_mask == htons(VLAN_PCP_MASK))
440             && (vid_mask || pcp_mask)) {
441             if (vid_mask) {
442                 ds_put_format(s, "dl_vlan=%"PRIu16",",
443                               vlan_tci_to_vid(f->vlan_tci));
444             }
445             if (pcp_mask) {
446                 ds_put_format(s, "dl_vlan_pcp=%d,",
447                               vlan_tci_to_pcp(f->vlan_tci));
448             }
449         } else {
450             ds_put_format(s, "vlan_tci=0x%04"PRIx16"/0x%04"PRIx16",",
451                           ntohs(f->vlan_tci), ntohs(wc->vlan_tci_mask));
452         }
453     }
454     if (!(w & FWW_DL_SRC)) {
455         ds_put_format(s, "dl_src="ETH_ADDR_FMT",", ETH_ADDR_ARGS(f->dl_src));
456     }
457     switch (w & (FWW_DL_DST | FWW_ETH_MCAST)) {
458     case 0:
459         ds_put_format(s, "dl_dst="ETH_ADDR_FMT",", ETH_ADDR_ARGS(f->dl_dst));
460         break;
461     case FWW_DL_DST:
462         ds_put_format(s, "dl_dst="ETH_ADDR_FMT"/01:00:00:00:00:00,",
463                       ETH_ADDR_ARGS(f->dl_dst));
464         break;
465     case FWW_ETH_MCAST:
466         ds_put_format(s, "dl_dst="ETH_ADDR_FMT"/fe:ff:ff:ff:ff:ff,",
467                       ETH_ADDR_ARGS(f->dl_dst));
468         break;
469     case FWW_DL_DST | FWW_ETH_MCAST:
470         break;
471     }
472     if (!skip_type && !(w & FWW_DL_TYPE)) {
473         ds_put_format(s, "dl_type=0x%04"PRIx16",", ntohs(f->dl_type));
474     }
475     format_ip_netmask(s, "nw_src", f->nw_src, wc->nw_src_mask);
476     format_ip_netmask(s, "nw_dst", f->nw_dst, wc->nw_dst_mask);
477     if (!skip_proto && !(w & FWW_NW_PROTO)) {
478         if (f->dl_type == htons(ETH_TYPE_ARP)) {
479             ds_put_format(s, "opcode=%"PRIu8",", f->nw_proto);
480         } else {
481             ds_put_format(s, "nw_proto=%"PRIu8",", f->nw_proto);
482         }
483     }
484     if (f->dl_type == htons(ETH_TYPE_ARP)) {
485         if (!(w & FWW_ARP_SHA)) {
486             ds_put_format(s, "arp_sha="ETH_ADDR_FMT",",
487                     ETH_ADDR_ARGS(f->arp_sha));
488         }
489         if (!(w & FWW_ARP_THA)) {
490             ds_put_format(s, "arp_tha="ETH_ADDR_FMT",",
491                     ETH_ADDR_ARGS(f->arp_tha));
492         }
493     }
494     if (!(w & FWW_NW_TOS)) {
495         ds_put_format(s, "nw_tos=%"PRIu8",", f->nw_tos);
496     }
497     if (f->nw_proto == IPPROTO_ICMP) {
498         if (!(w & FWW_TP_SRC)) {
499             ds_put_format(s, "icmp_type=%"PRIu16",", ntohs(f->tp_src));
500         }
501         if (!(w & FWW_TP_DST)) {
502             ds_put_format(s, "icmp_code=%"PRIu16",", ntohs(f->tp_dst));
503         }
504     } else {
505         if (!(w & FWW_TP_SRC)) {
506             ds_put_format(s, "tp_src=%"PRIu16",", ntohs(f->tp_src));
507         }
508         if (!(w & FWW_TP_DST)) {
509             ds_put_format(s, "tp_dst=%"PRIu16",", ntohs(f->tp_dst));
510         }
511     }
512
513     if (s->length > start_len && ds_last(s) == ',') {
514         s->length--;
515     }
516 }
517
518 /* Converts 'rule' to a string and returns the string.  The caller must free
519  * the string (with free()). */
520 char *
521 cls_rule_to_string(const struct cls_rule *rule)
522 {
523     struct ds s = DS_EMPTY_INITIALIZER;
524     cls_rule_format(rule, &s);
525     return ds_steal_cstr(&s);
526 }
527
528 void
529 cls_rule_print(const struct cls_rule *rule)
530 {
531     char *s = cls_rule_to_string(rule);
532     puts(s);
533     free(s);
534 }
535 \f
536 /* Initializes 'cls' as a classifier that initially contains no classification
537  * rules. */
538 void
539 classifier_init(struct classifier *cls)
540 {
541     cls->n_rules = 0;
542     hmap_init(&cls->tables);
543 }
544
545 /* Destroys 'cls'.  Rules within 'cls', if any, are not freed; this is the
546  * caller's responsibility. */
547 void
548 classifier_destroy(struct classifier *cls)
549 {
550     if (cls) {
551         struct cls_table *table, *next_table;
552
553         HMAP_FOR_EACH_SAFE (table, next_table, hmap_node, &cls->tables) {
554             hmap_destroy(&table->rules);
555             hmap_remove(&cls->tables, &table->hmap_node);
556             free(table);
557         }
558         hmap_destroy(&cls->tables);
559     }
560 }
561
562 /* Returns true if 'cls' contains no classification rules, false otherwise. */
563 bool
564 classifier_is_empty(const struct classifier *cls)
565 {
566     return cls->n_rules == 0;
567 }
568
569 /* Returns the number of rules in 'classifier'. */
570 int
571 classifier_count(const struct classifier *cls)
572 {
573     return cls->n_rules;
574 }
575
576 /* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
577  * must not modify or free it.
578  *
579  * If 'cls' already contains an identical rule (including wildcards, values of
580  * fixed fields, and priority), replaces the old rule by 'rule' and returns the
581  * rule that was replaced.  The caller takes ownership of the returned rule and
582  * is thus responsible for freeing it, etc., as necessary.
583  *
584  * Returns NULL if 'cls' does not contain a rule with an identical key, after
585  * inserting the new rule.  In this case, no rules are displaced by the new
586  * rule, even rules that cannot have any effect because the new rule matches a
587  * superset of their flows and has higher priority. */
588 struct cls_rule *
589 classifier_insert(struct classifier *cls, struct cls_rule *rule)
590 {
591     struct cls_rule *old_rule;
592     struct cls_table *table;
593
594     table = find_table(cls, &rule->wc);
595     if (!table) {
596         table = insert_table(cls, &rule->wc);
597     }
598
599     old_rule = insert_rule(table, rule);
600     if (!old_rule) {
601         table->n_table_rules++;
602         cls->n_rules++;
603     }
604     return old_rule;
605 }
606
607 /* Removes 'rule' from 'cls'.  It is the caller's responsibility to free
608  * 'rule', if this is desirable. */
609 void
610 classifier_remove(struct classifier *cls, struct cls_rule *rule)
611 {
612     struct cls_rule *head;
613     struct cls_table *table;
614
615     table = find_table(cls, &rule->wc);
616     head = find_equal(table, &rule->flow, rule->hmap_node.hash);
617     if (head != rule) {
618         list_remove(&rule->list);
619     } else if (list_is_empty(&rule->list)) {
620         hmap_remove(&table->rules, &rule->hmap_node);
621     } else {
622         struct cls_rule *next = CONTAINER_OF(rule->list.next,
623                                              struct cls_rule, list);
624
625         list_remove(&rule->list);
626         hmap_replace(&table->rules, &rule->hmap_node, &next->hmap_node);
627     }
628
629     if (--table->n_table_rules == 0) {
630         destroy_table(cls, table);
631     }
632
633     cls->n_rules--;
634 }
635
636 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
637  * Returns a null pointer if no rules in 'cls' match 'flow'.  If multiple rules
638  * of equal priority match 'flow', returns one arbitrarily. */
639 struct cls_rule *
640 classifier_lookup(const struct classifier *cls, const struct flow *flow)
641 {
642     struct cls_table *table;
643     struct cls_rule *best;
644
645     best = NULL;
646     HMAP_FOR_EACH (table, hmap_node, &cls->tables) {
647         struct cls_rule *rule = find_match(table, flow);
648         if (rule && (!best || rule->priority > best->priority)) {
649             best = rule;
650         }
651     }
652     return best;
653 }
654
655 /* Finds and returns a rule in 'cls' with exactly the same priority and
656  * matching criteria as 'target'.  Returns a null pointer if 'cls' doesn't
657  * contain an exact match.
658  *
659  * Priority is ignored for exact-match rules (because OpenFlow 1.0 always
660  * treats exact-match rules as highest priority). */
661 struct cls_rule *
662 classifier_find_rule_exactly(const struct classifier *cls,
663                              const struct cls_rule *target)
664 {
665     struct cls_rule *head, *rule;
666     struct cls_table *table;
667
668     table = find_table(cls, &target->wc);
669     if (!table) {
670         return NULL;
671     }
672
673     head = find_equal(table, &target->flow, flow_hash(&target->flow, 0));
674     if (flow_wildcards_is_exact(&target->wc)) {
675         return head;
676     }
677     FOR_EACH_RULE_IN_LIST (rule, head) {
678         if (target->priority >= rule->priority) {
679             return target->priority == rule->priority ? rule : NULL;
680         }
681     }
682     return NULL;
683 }
684
685 /* Checks if 'target' would overlap any other rule in 'cls'.  Two rules are
686  * considered to overlap if both rules have the same priority and a packet
687  * could match both. */
688 bool
689 classifier_rule_overlaps(const struct classifier *cls,
690                          const struct cls_rule *target)
691 {
692     struct cls_table *table;
693
694     HMAP_FOR_EACH (table, hmap_node, &cls->tables) {
695         struct flow_wildcards wc;
696         struct cls_rule *head;
697
698         flow_wildcards_combine(&wc, &target->wc, &table->wc);
699         HMAP_FOR_EACH (head, hmap_node, &table->rules) {
700             struct cls_rule *rule;
701
702             FOR_EACH_RULE_IN_LIST (rule, head) {
703                 if (rule->priority == target->priority
704                     && flow_equal_except(&target->flow, &rule->flow, &wc)) {
705                     return true;
706                 }
707             }
708         }
709     }
710
711     return false;
712 }
713 \f
714 /* Iteration. */
715
716 static bool
717 rule_matches(const struct cls_rule *rule, const struct cls_rule *target)
718 {
719     return (!target
720             || flow_equal_except(&rule->flow, &target->flow, &target->wc));
721 }
722
723 static struct cls_rule *
724 search_table(const struct cls_table *table, const struct cls_rule *target)
725 {
726     if (!target || !flow_wildcards_has_extra(&table->wc, &target->wc)) {
727         struct cls_rule *rule;
728
729         HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
730             if (rule_matches(rule, target)) {
731                 return rule;
732             }
733         }
734     }
735     return NULL;
736 }
737
738 /* Initializes 'cursor' for iterating through 'cls' rules that exactly match
739  * 'target' or are more specific than 'target'.  That is, a given 'rule'
740  * matches 'target' if, for every field:
741  *
742  *   - 'target' and 'rule' specify the same (non-wildcarded) value for the
743  *     field, or
744  *
745  *   - 'target' wildcards the field,
746  *
747  * but not if:
748  *
749  *   - 'target' and 'rule' specify different values for the field, or
750  *
751  *   - 'target' specifies a value for the field but 'rule' wildcards it.
752  *
753  * Equivalently, the truth table for whether a field matches is:
754  *
755  *                                     rule
756  *
757  *                             wildcard    exact
758  *                            +---------+---------+
759  *                   t   wild |   yes   |   yes   |
760  *                   a   card |         |         |
761  *                   r        +---------+---------+
762  *                   g  exact |    no   |if values|
763  *                   e        |         |are equal|
764  *                   t        +---------+---------+
765  *
766  * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
767  * commands and by OpenFlow 1.0 aggregate and flow stats.
768  *
769  * Ignores target->priority.
770  *
771  * 'target' may be NULL to iterate over every rule in 'cls'. */
772 void
773 cls_cursor_init(struct cls_cursor *cursor, const struct classifier *cls,
774                 const struct cls_rule *target)
775 {
776     cursor->cls = cls;
777     cursor->target = target;
778 }
779
780 /* Returns the first matching cls_rule in 'cursor''s iteration, or a null
781  * pointer if there are no matches. */
782 struct cls_rule *
783 cls_cursor_first(struct cls_cursor *cursor)
784 {
785     struct cls_table *table;
786
787     for (table = classifier_first_table(cursor->cls); table;
788          table = classifier_next_table(cursor->cls, table)) {
789         struct cls_rule *rule = search_table(table, cursor->target);
790         if (rule) {
791             cursor->table = table;
792             return rule;
793         }
794     }
795
796     return NULL;
797 }
798
799 /* Returns the next matching cls_rule in 'cursor''s iteration, or a null
800  * pointer if there are no more matches. */
801 struct cls_rule *
802 cls_cursor_next(struct cls_cursor *cursor, struct cls_rule *rule)
803 {
804     const struct cls_table *table;
805     struct cls_rule *next;
806
807     next = next_rule_in_list__(rule);
808     if (next->priority < rule->priority) {
809         return next;
810     }
811
812     /* 'next' is the head of the list, that is, the rule that is included in
813      * the table's hmap.  (This is important when the classifier contains rules
814      * that differ only in priority.) */
815     rule = next;
816     HMAP_FOR_EACH_CONTINUE (rule, hmap_node, &cursor->table->rules) {
817         if (rule_matches(rule, cursor->target)) {
818             return rule;
819         }
820     }
821
822     for (table = classifier_next_table(cursor->cls, cursor->table); table;
823          table = classifier_next_table(cursor->cls, table)) {
824         rule = search_table(table, cursor->target);
825         if (rule) {
826             cursor->table = table;
827             return rule;
828         }
829     }
830
831     return NULL;
832 }
833 \f
834 static struct cls_table *
835 find_table(const struct classifier *cls, const struct flow_wildcards *wc)
836 {
837     struct cls_table *table;
838
839     HMAP_FOR_EACH_IN_BUCKET (table, hmap_node, flow_wildcards_hash(wc),
840                              &cls->tables) {
841         if (flow_wildcards_equal(wc, &table->wc)) {
842             return table;
843         }
844     }
845     return NULL;
846 }
847
848 static struct cls_table *
849 insert_table(struct classifier *cls, const struct flow_wildcards *wc)
850 {
851     struct cls_table *table;
852
853     table = xzalloc(sizeof *table);
854     hmap_init(&table->rules);
855     table->wc = *wc;
856     hmap_insert(&cls->tables, &table->hmap_node, flow_wildcards_hash(wc));
857
858     return table;
859 }
860
861 static struct cls_table *
862 classifier_first_table(const struct classifier *cls)
863 {
864     return cls_table_from_hmap_node(hmap_first(&cls->tables));
865 }
866
867 static struct cls_table *
868 classifier_next_table(const struct classifier *cls,
869                       const struct cls_table *table)
870 {
871     return cls_table_from_hmap_node(hmap_next(&cls->tables,
872                                               &table->hmap_node));
873 }
874
875 static void
876 destroy_table(struct classifier *cls, struct cls_table *table)
877 {
878     hmap_remove(&cls->tables, &table->hmap_node);
879     hmap_destroy(&table->rules);
880     free(table);
881 }
882
883 static struct cls_rule *
884 find_match(const struct cls_table *table, const struct flow *flow)
885 {
886     struct cls_rule *rule;
887     struct flow f;
888
889     f = *flow;
890     zero_wildcards(&f, &table->wc);
891     HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, flow_hash(&f, 0),
892                              &table->rules) {
893         if (flow_equal(&f, &rule->flow)) {
894             return rule;
895         }
896     }
897     return NULL;
898 }
899
900 static struct cls_rule *
901 find_equal(struct cls_table *table, const struct flow *flow, uint32_t hash)
902 {
903     struct cls_rule *head;
904
905     HMAP_FOR_EACH_WITH_HASH (head, hmap_node, hash, &table->rules) {
906         if (flow_equal(&head->flow, flow)) {
907             return head;
908         }
909     }
910     return NULL;
911 }
912
913 static struct cls_rule *
914 insert_rule(struct cls_table *table, struct cls_rule *new)
915 {
916     struct cls_rule *head;
917
918     new->hmap_node.hash = flow_hash(&new->flow, 0);
919
920     head = find_equal(table, &new->flow, new->hmap_node.hash);
921     if (!head) {
922         hmap_insert(&table->rules, &new->hmap_node, new->hmap_node.hash);
923         list_init(&new->list);
924         return NULL;
925     } else {
926         /* Scan the list for the insertion point that will keep the list in
927          * order of decreasing priority. */
928         struct cls_rule *rule;
929         FOR_EACH_RULE_IN_LIST (rule, head) {
930             if (new->priority >= rule->priority) {
931                 if (rule == head) {
932                     /* 'new' is the new highest-priority flow in the list. */
933                     hmap_replace(&table->rules,
934                                  &rule->hmap_node, &new->hmap_node);
935                 }
936
937                 if (new->priority == rule->priority) {
938                     list_replace(&new->list, &rule->list);
939                     return rule;
940                 } else {
941                     list_insert(&rule->list, &new->list);
942                     return NULL;
943                 }
944             }
945         }
946
947         /* Insert 'new' at the end of the list. */
948         list_push_back(&head->list, &new->list);
949         return NULL;
950     }
951 }
952
953 static struct cls_rule *
954 next_rule_in_list__(struct cls_rule *rule)
955 {
956     struct cls_rule *next = OBJECT_CONTAINING(rule->list.next, next, list);
957     return next;
958 }
959
960 static struct cls_rule *
961 next_rule_in_list(struct cls_rule *rule)
962 {
963     struct cls_rule *next = next_rule_in_list__(rule);
964     return next->priority < rule->priority ? next : NULL;
965 }
966
967 static bool
968 flow_equal_except(const struct flow *a, const struct flow *b,
969                   const struct flow_wildcards *wildcards)
970 {
971     const flow_wildcards_t wc = wildcards->wildcards;
972     int i;
973
974     BUILD_ASSERT_DECL(FLOW_SIG_SIZE == 52 + FLOW_N_REGS * 4);
975
976     for (i = 0; i < FLOW_N_REGS; i++) {
977         if ((a->regs[i] ^ b->regs[i]) & wildcards->reg_masks[i]) {
978             return false;
979         }
980     }
981
982     return (!((a->tun_id ^ b->tun_id) & wildcards->tun_id_mask)
983             && !((a->nw_src ^ b->nw_src) & wildcards->nw_src_mask)
984             && !((a->nw_dst ^ b->nw_dst) & wildcards->nw_dst_mask)
985             && (wc & FWW_IN_PORT || a->in_port == b->in_port)
986             && !((a->vlan_tci ^ b->vlan_tci) & wildcards->vlan_tci_mask)
987             && (wc & FWW_DL_TYPE || a->dl_type == b->dl_type)
988             && (wc & FWW_TP_SRC || a->tp_src == b->tp_src)
989             && (wc & FWW_TP_DST || a->tp_dst == b->tp_dst)
990             && (wc & FWW_DL_SRC || eth_addr_equals(a->dl_src, b->dl_src))
991             && (wc & FWW_DL_DST
992                 || (!((a->dl_dst[0] ^ b->dl_dst[0]) & 0xfe)
993                     && a->dl_dst[1] == b->dl_dst[1]
994                     && a->dl_dst[2] == b->dl_dst[2]
995                     && a->dl_dst[3] == b->dl_dst[3]
996                     && a->dl_dst[4] == b->dl_dst[4]
997                     && a->dl_dst[5] == b->dl_dst[5]))
998             && (wc & FWW_ETH_MCAST
999                 || !((a->dl_dst[0] ^ b->dl_dst[0]) & 0x01))
1000             && (wc & FWW_NW_PROTO || a->nw_proto == b->nw_proto)
1001             && (wc & FWW_NW_TOS || a->nw_tos == b->nw_tos)
1002             && (wc & FWW_ARP_SHA || eth_addr_equals(a->arp_sha, b->arp_sha))
1003             && (wc & FWW_ARP_THA || eth_addr_equals(a->arp_tha, b->arp_tha)));
1004 }
1005
1006 static void
1007 zero_wildcards(struct flow *flow, const struct flow_wildcards *wildcards)
1008 {
1009     const flow_wildcards_t wc = wildcards->wildcards;
1010     int i;
1011
1012     BUILD_ASSERT_DECL(FLOW_SIG_SIZE == 52 + 4 * FLOW_N_REGS);
1013
1014     for (i = 0; i < FLOW_N_REGS; i++) {
1015         flow->regs[i] &= wildcards->reg_masks[i];
1016     }
1017     flow->tun_id &= wildcards->tun_id_mask;
1018     flow->nw_src &= wildcards->nw_src_mask;
1019     flow->nw_dst &= wildcards->nw_dst_mask;
1020     if (wc & FWW_IN_PORT) {
1021         flow->in_port = 0;
1022     }
1023     flow->vlan_tci &= wildcards->vlan_tci_mask;
1024     if (wc & FWW_DL_TYPE) {
1025         flow->dl_type = 0;
1026     }
1027     if (wc & FWW_TP_SRC) {
1028         flow->tp_src = 0;
1029     }
1030     if (wc & FWW_TP_DST) {
1031         flow->tp_dst = 0;
1032     }
1033     if (wc & FWW_DL_SRC) {
1034         memset(flow->dl_src, 0, sizeof flow->dl_src);
1035     }
1036     if (wc & FWW_DL_DST) {
1037         flow->dl_dst[0] &= 0x01;
1038         memset(&flow->dl_dst[1], 0, 5);
1039     }
1040     if (wc & FWW_ETH_MCAST) {
1041         flow->dl_dst[0] &= 0xfe;
1042     }
1043     if (wc & FWW_NW_PROTO) {
1044         flow->nw_proto = 0;
1045     }
1046     if (wc & FWW_NW_TOS) {
1047         flow->nw_tos = 0;
1048     }
1049     if (wc & FWW_ARP_SHA) {
1050         memset(flow->arp_sha, 0, sizeof flow->arp_sha);
1051     }
1052     if (wc & FWW_ARP_THA) {
1053         memset(flow->arp_tha, 0, sizeof flow->arp_tha);
1054     }
1055 }