packets: Do not assume that IPv4, TCP, or ARP headers are 32-bit aligned.
[cascardo/ovs.git] / lib / flow.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc.
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 #include <config.h>
17 #include <sys/types.h>
18 #include "flow.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <limits.h>
23 #include <netinet/in.h>
24 #include <netinet/icmp6.h>
25 #include <netinet/ip6.h>
26 #include <stdint.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include "byte-order.h"
30 #include "coverage.h"
31 #include "csum.h"
32 #include "dynamic-string.h"
33 #include "hash.h"
34 #include "match.h"
35 #include "ofpbuf.h"
36 #include "openflow/openflow.h"
37 #include "packets.h"
38 #include "unaligned.h"
39 #include "vlog.h"
40
41 VLOG_DEFINE_THIS_MODULE(flow);
42
43 COVERAGE_DEFINE(flow_extract);
44 COVERAGE_DEFINE(miniflow_malloc);
45
46 static struct arp_eth_header *
47 pull_arp(struct ofpbuf *packet)
48 {
49     return ofpbuf_try_pull(packet, ARP_ETH_HEADER_LEN);
50 }
51
52 static struct ip_header *
53 pull_ip(struct ofpbuf *packet)
54 {
55     if (packet->size >= IP_HEADER_LEN) {
56         struct ip_header *ip = packet->data;
57         int ip_len = IP_IHL(ip->ip_ihl_ver) * 4;
58         if (ip_len >= IP_HEADER_LEN && packet->size >= ip_len) {
59             return ofpbuf_pull(packet, ip_len);
60         }
61     }
62     return NULL;
63 }
64
65 static struct tcp_header *
66 pull_tcp(struct ofpbuf *packet)
67 {
68     if (packet->size >= TCP_HEADER_LEN) {
69         struct tcp_header *tcp = packet->data;
70         int tcp_len = TCP_OFFSET(tcp->tcp_ctl) * 4;
71         if (tcp_len >= TCP_HEADER_LEN && packet->size >= tcp_len) {
72             return ofpbuf_pull(packet, tcp_len);
73         }
74     }
75     return NULL;
76 }
77
78 static struct udp_header *
79 pull_udp(struct ofpbuf *packet)
80 {
81     return ofpbuf_try_pull(packet, UDP_HEADER_LEN);
82 }
83
84 static struct icmp_header *
85 pull_icmp(struct ofpbuf *packet)
86 {
87     return ofpbuf_try_pull(packet, ICMP_HEADER_LEN);
88 }
89
90 static struct icmp6_hdr *
91 pull_icmpv6(struct ofpbuf *packet)
92 {
93     return ofpbuf_try_pull(packet, sizeof(struct icmp6_hdr));
94 }
95
96 static void
97 parse_vlan(struct ofpbuf *b, struct flow *flow)
98 {
99     struct qtag_prefix {
100         ovs_be16 eth_type;      /* ETH_TYPE_VLAN */
101         ovs_be16 tci;
102     };
103
104     if (b->size >= sizeof(struct qtag_prefix) + sizeof(ovs_be16)) {
105         struct qtag_prefix *qp = ofpbuf_pull(b, sizeof *qp);
106         flow->vlan_tci = qp->tci | htons(VLAN_CFI);
107     }
108 }
109
110 static ovs_be16
111 parse_ethertype(struct ofpbuf *b)
112 {
113     struct llc_snap_header *llc;
114     ovs_be16 proto;
115
116     proto = *(ovs_be16 *) ofpbuf_pull(b, sizeof proto);
117     if (ntohs(proto) >= ETH_TYPE_MIN) {
118         return proto;
119     }
120
121     if (b->size < sizeof *llc) {
122         return htons(FLOW_DL_TYPE_NONE);
123     }
124
125     llc = b->data;
126     if (llc->llc.llc_dsap != LLC_DSAP_SNAP
127         || llc->llc.llc_ssap != LLC_SSAP_SNAP
128         || llc->llc.llc_cntl != LLC_CNTL_SNAP
129         || memcmp(llc->snap.snap_org, SNAP_ORG_ETHERNET,
130                   sizeof llc->snap.snap_org)) {
131         return htons(FLOW_DL_TYPE_NONE);
132     }
133
134     ofpbuf_pull(b, sizeof *llc);
135     return llc->snap.snap_type;
136 }
137
138 static int
139 parse_ipv6(struct ofpbuf *packet, struct flow *flow)
140 {
141     const struct ip6_hdr *nh;
142     ovs_be32 tc_flow;
143     int nexthdr;
144
145     nh = ofpbuf_try_pull(packet, sizeof *nh);
146     if (!nh) {
147         return EINVAL;
148     }
149
150     nexthdr = nh->ip6_nxt;
151
152     flow->ipv6_src = nh->ip6_src;
153     flow->ipv6_dst = nh->ip6_dst;
154
155     tc_flow = get_unaligned_be32(&nh->ip6_flow);
156     flow->nw_tos = ntohl(tc_flow) >> 20;
157     flow->ipv6_label = tc_flow & htonl(IPV6_LABEL_MASK);
158     flow->nw_ttl = nh->ip6_hlim;
159     flow->nw_proto = IPPROTO_NONE;
160
161     while (1) {
162         if ((nexthdr != IPPROTO_HOPOPTS)
163                 && (nexthdr != IPPROTO_ROUTING)
164                 && (nexthdr != IPPROTO_DSTOPTS)
165                 && (nexthdr != IPPROTO_AH)
166                 && (nexthdr != IPPROTO_FRAGMENT)) {
167             /* It's either a terminal header (e.g., TCP, UDP) or one we
168              * don't understand.  In either case, we're done with the
169              * packet, so use it to fill in 'nw_proto'. */
170             break;
171         }
172
173         /* We only verify that at least 8 bytes of the next header are
174          * available, but many of these headers are longer.  Ensure that
175          * accesses within the extension header are within those first 8
176          * bytes. All extension headers are required to be at least 8
177          * bytes. */
178         if (packet->size < 8) {
179             return EINVAL;
180         }
181
182         if ((nexthdr == IPPROTO_HOPOPTS)
183                 || (nexthdr == IPPROTO_ROUTING)
184                 || (nexthdr == IPPROTO_DSTOPTS)) {
185             /* These headers, while different, have the fields we care about
186              * in the same location and with the same interpretation. */
187             const struct ip6_ext *ext_hdr = packet->data;
188             nexthdr = ext_hdr->ip6e_nxt;
189             if (!ofpbuf_try_pull(packet, (ext_hdr->ip6e_len + 1) * 8)) {
190                 return EINVAL;
191             }
192         } else if (nexthdr == IPPROTO_AH) {
193             /* A standard AH definition isn't available, but the fields
194              * we care about are in the same location as the generic
195              * option header--only the header length is calculated
196              * differently. */
197             const struct ip6_ext *ext_hdr = packet->data;
198             nexthdr = ext_hdr->ip6e_nxt;
199             if (!ofpbuf_try_pull(packet, (ext_hdr->ip6e_len + 2) * 4)) {
200                return EINVAL;
201             }
202         } else if (nexthdr == IPPROTO_FRAGMENT) {
203             const struct ip6_frag *frag_hdr = packet->data;
204
205             nexthdr = frag_hdr->ip6f_nxt;
206             if (!ofpbuf_try_pull(packet, sizeof *frag_hdr)) {
207                 return EINVAL;
208             }
209
210             /* We only process the first fragment. */
211             if (frag_hdr->ip6f_offlg != htons(0)) {
212                 flow->nw_frag = FLOW_NW_FRAG_ANY;
213                 if ((frag_hdr->ip6f_offlg & IP6F_OFF_MASK) != htons(0)) {
214                     flow->nw_frag |= FLOW_NW_FRAG_LATER;
215                     nexthdr = IPPROTO_FRAGMENT;
216                     break;
217                 }
218             }
219         }
220     }
221
222     flow->nw_proto = nexthdr;
223     return 0;
224 }
225
226 static void
227 parse_tcp(struct ofpbuf *packet, struct ofpbuf *b, struct flow *flow)
228 {
229     const struct tcp_header *tcp = pull_tcp(b);
230     if (tcp) {
231         flow->tp_src = tcp->tcp_src;
232         flow->tp_dst = tcp->tcp_dst;
233         packet->l7 = b->data;
234     }
235 }
236
237 static void
238 parse_udp(struct ofpbuf *packet, struct ofpbuf *b, struct flow *flow)
239 {
240     const struct udp_header *udp = pull_udp(b);
241     if (udp) {
242         flow->tp_src = udp->udp_src;
243         flow->tp_dst = udp->udp_dst;
244         packet->l7 = b->data;
245     }
246 }
247
248 static bool
249 parse_icmpv6(struct ofpbuf *b, struct flow *flow)
250 {
251     const struct icmp6_hdr *icmp = pull_icmpv6(b);
252
253     if (!icmp) {
254         return false;
255     }
256
257     /* The ICMPv6 type and code fields use the 16-bit transport port
258      * fields, so we need to store them in 16-bit network byte order. */
259     flow->tp_src = htons(icmp->icmp6_type);
260     flow->tp_dst = htons(icmp->icmp6_code);
261
262     if (icmp->icmp6_code == 0 &&
263         (icmp->icmp6_type == ND_NEIGHBOR_SOLICIT ||
264          icmp->icmp6_type == ND_NEIGHBOR_ADVERT)) {
265         const struct in6_addr *nd_target;
266
267         nd_target = ofpbuf_try_pull(b, sizeof *nd_target);
268         if (!nd_target) {
269             return false;
270         }
271         flow->nd_target = *nd_target;
272
273         while (b->size >= 8) {
274             /* The minimum size of an option is 8 bytes, which also is
275              * the size of Ethernet link-layer options. */
276             const struct nd_opt_hdr *nd_opt = b->data;
277             int opt_len = nd_opt->nd_opt_len * 8;
278
279             if (!opt_len || opt_len > b->size) {
280                 goto invalid;
281             }
282
283             /* Store the link layer address if the appropriate option is
284              * provided.  It is considered an error if the same link
285              * layer option is specified twice. */
286             if (nd_opt->nd_opt_type == ND_OPT_SOURCE_LINKADDR
287                     && opt_len == 8) {
288                 if (eth_addr_is_zero(flow->arp_sha)) {
289                     memcpy(flow->arp_sha, nd_opt + 1, ETH_ADDR_LEN);
290                 } else {
291                     goto invalid;
292                 }
293             } else if (nd_opt->nd_opt_type == ND_OPT_TARGET_LINKADDR
294                     && opt_len == 8) {
295                 if (eth_addr_is_zero(flow->arp_tha)) {
296                     memcpy(flow->arp_tha, nd_opt + 1, ETH_ADDR_LEN);
297                 } else {
298                     goto invalid;
299                 }
300             }
301
302             if (!ofpbuf_try_pull(b, opt_len)) {
303                 goto invalid;
304             }
305         }
306     }
307
308     return true;
309
310 invalid:
311     memset(&flow->nd_target, 0, sizeof(flow->nd_target));
312     memset(flow->arp_sha, 0, sizeof(flow->arp_sha));
313     memset(flow->arp_tha, 0, sizeof(flow->arp_tha));
314
315     return false;
316
317 }
318
319 /* Initializes 'flow' members from 'packet', 'skb_priority', 'tnl', and
320  * 'ofp_in_port'.
321  *
322  * Initializes 'packet' header pointers as follows:
323  *
324  *    - packet->l2 to the start of the Ethernet header.
325  *
326  *    - packet->l3 to just past the Ethernet header, or just past the
327  *      vlan_header if one is present, to the first byte of the payload of the
328  *      Ethernet frame.
329  *
330  *    - packet->l4 to just past the IPv4 header, if one is present and has a
331  *      correct length, and otherwise NULL.
332  *
333  *    - packet->l7 to just past the TCP or UDP or ICMP header, if one is
334  *      present and has a correct length, and otherwise NULL.
335  */
336 void
337 flow_extract(struct ofpbuf *packet, uint32_t skb_priority, uint32_t skb_mark,
338              const struct flow_tnl *tnl, uint16_t ofp_in_port,
339              struct flow *flow)
340 {
341     struct ofpbuf b = *packet;
342     struct eth_header *eth;
343
344     COVERAGE_INC(flow_extract);
345
346     memset(flow, 0, sizeof *flow);
347
348     if (tnl) {
349         assert(tnl != &flow->tunnel);
350         flow->tunnel = *tnl;
351     }
352     flow->in_port = ofp_in_port;
353     flow->skb_priority = skb_priority;
354     flow->skb_mark = skb_mark;
355
356     packet->l2 = b.data;
357     packet->l3 = NULL;
358     packet->l4 = NULL;
359     packet->l7 = NULL;
360
361     if (b.size < sizeof *eth) {
362         return;
363     }
364
365     /* Link layer. */
366     eth = b.data;
367     memcpy(flow->dl_src, eth->eth_src, ETH_ADDR_LEN);
368     memcpy(flow->dl_dst, eth->eth_dst, ETH_ADDR_LEN);
369
370     /* dl_type, vlan_tci. */
371     ofpbuf_pull(&b, ETH_ADDR_LEN * 2);
372     if (eth->eth_type == htons(ETH_TYPE_VLAN)) {
373         parse_vlan(&b, flow);
374     }
375     flow->dl_type = parse_ethertype(&b);
376
377     /* Network layer. */
378     packet->l3 = b.data;
379     if (flow->dl_type == htons(ETH_TYPE_IP)) {
380         const struct ip_header *nh = pull_ip(&b);
381         if (nh) {
382             packet->l4 = b.data;
383
384             flow->nw_src = get_16aligned_be32(&nh->ip_src);
385             flow->nw_dst = get_16aligned_be32(&nh->ip_dst);
386             flow->nw_proto = nh->ip_proto;
387
388             flow->nw_tos = nh->ip_tos;
389             if (IP_IS_FRAGMENT(nh->ip_frag_off)) {
390                 flow->nw_frag = FLOW_NW_FRAG_ANY;
391                 if (nh->ip_frag_off & htons(IP_FRAG_OFF_MASK)) {
392                     flow->nw_frag |= FLOW_NW_FRAG_LATER;
393                 }
394             }
395             flow->nw_ttl = nh->ip_ttl;
396
397             if (!(nh->ip_frag_off & htons(IP_FRAG_OFF_MASK))) {
398                 if (flow->nw_proto == IPPROTO_TCP) {
399                     parse_tcp(packet, &b, flow);
400                 } else if (flow->nw_proto == IPPROTO_UDP) {
401                     parse_udp(packet, &b, flow);
402                 } else if (flow->nw_proto == IPPROTO_ICMP) {
403                     const struct icmp_header *icmp = pull_icmp(&b);
404                     if (icmp) {
405                         flow->tp_src = htons(icmp->icmp_type);
406                         flow->tp_dst = htons(icmp->icmp_code);
407                         packet->l7 = b.data;
408                     }
409                 }
410             }
411         }
412     } else if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
413         if (parse_ipv6(&b, flow)) {
414             return;
415         }
416
417         packet->l4 = b.data;
418         if (flow->nw_proto == IPPROTO_TCP) {
419             parse_tcp(packet, &b, flow);
420         } else if (flow->nw_proto == IPPROTO_UDP) {
421             parse_udp(packet, &b, flow);
422         } else if (flow->nw_proto == IPPROTO_ICMPV6) {
423             if (parse_icmpv6(&b, flow)) {
424                 packet->l7 = b.data;
425             }
426         }
427     } else if (flow->dl_type == htons(ETH_TYPE_ARP) ||
428                flow->dl_type == htons(ETH_TYPE_RARP)) {
429         const struct arp_eth_header *arp = pull_arp(&b);
430         if (arp && arp->ar_hrd == htons(1)
431             && arp->ar_pro == htons(ETH_TYPE_IP)
432             && arp->ar_hln == ETH_ADDR_LEN
433             && arp->ar_pln == 4) {
434             /* We only match on the lower 8 bits of the opcode. */
435             if (ntohs(arp->ar_op) <= 0xff) {
436                 flow->nw_proto = ntohs(arp->ar_op);
437             }
438
439             flow->nw_src = get_16aligned_be32(&arp->ar_spa);
440             flow->nw_dst = get_16aligned_be32(&arp->ar_tpa);
441             memcpy(flow->arp_sha, arp->ar_sha, ETH_ADDR_LEN);
442             memcpy(flow->arp_tha, arp->ar_tha, ETH_ADDR_LEN);
443         }
444     }
445 }
446
447 /* For every bit of a field that is wildcarded in 'wildcards', sets the
448  * corresponding bit in 'flow' to zero. */
449 void
450 flow_zero_wildcards(struct flow *flow, const struct flow_wildcards *wildcards)
451 {
452     uint32_t *flow_u32 = (uint32_t *) flow;
453     const uint32_t *wc_u32 = (const uint32_t *) &wildcards->masks;
454     size_t i;
455
456     for (i = 0; i < FLOW_U32S; i++) {
457         flow_u32[i] &= wc_u32[i];
458     }
459 }
460
461 /* Initializes 'fmd' with the metadata found in 'flow'. */
462 void
463 flow_get_metadata(const struct flow *flow, struct flow_metadata *fmd)
464 {
465     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 18);
466
467     fmd->tun_id = flow->tunnel.tun_id;
468     fmd->metadata = flow->metadata;
469     memcpy(fmd->regs, flow->regs, sizeof fmd->regs);
470     fmd->in_port = flow->in_port;
471 }
472
473 char *
474 flow_to_string(const struct flow *flow)
475 {
476     struct ds ds = DS_EMPTY_INITIALIZER;
477     flow_format(&ds, flow);
478     return ds_cstr(&ds);
479 }
480
481 const char *
482 flow_tun_flag_to_string(uint32_t flags)
483 {
484     switch (flags) {
485     case FLOW_TNL_F_DONT_FRAGMENT:
486         return "df";
487     case FLOW_TNL_F_CSUM:
488         return "csum";
489     case FLOW_TNL_F_KEY:
490         return "key";
491     default:
492         return NULL;
493     }
494 }
495
496 void
497 format_flags(struct ds *ds, const char *(*bit_to_string)(uint32_t),
498              uint32_t flags, char del)
499 {
500     uint32_t bad = 0;
501
502     if (!flags) {
503         return;
504     }
505     while (flags) {
506         uint32_t bit = rightmost_1bit(flags);
507         const char *s;
508
509         s = bit_to_string(bit);
510         if (s) {
511             ds_put_format(ds, "%s%c", s, del);
512         } else {
513             bad |= bit;
514         }
515
516         flags &= ~bit;
517     }
518
519     if (bad) {
520         ds_put_format(ds, "0x%"PRIx32"%c", bad, del);
521     }
522     ds_chomp(ds, del);
523 }
524
525 void
526 flow_format(struct ds *ds, const struct flow *flow)
527 {
528     struct match match;
529
530     match_wc_init(&match, flow);
531     match_format(&match, ds, OFP_DEFAULT_PRIORITY);
532 }
533
534 void
535 flow_print(FILE *stream, const struct flow *flow)
536 {
537     char *s = flow_to_string(flow);
538     fputs(s, stream);
539     free(s);
540 }
541 \f
542 /* flow_wildcards functions. */
543
544 /* Initializes 'wc' as a set of wildcards that matches every packet. */
545 void
546 flow_wildcards_init_catchall(struct flow_wildcards *wc)
547 {
548     memset(&wc->masks, 0, sizeof wc->masks);
549 }
550
551 /* Initializes 'wc' as an exact-match set of wildcards; that is, 'wc' does not
552  * wildcard any bits or fields. */
553 void
554 flow_wildcards_init_exact(struct flow_wildcards *wc)
555 {
556     memset(&wc->masks, 0xff, sizeof wc->masks);
557     memset(wc->masks.zeros, 0, sizeof wc->masks.zeros);
558 }
559
560 /* Returns true if 'wc' matches every packet, false if 'wc' fixes any bits or
561  * fields. */
562 bool
563 flow_wildcards_is_catchall(const struct flow_wildcards *wc)
564 {
565     const uint32_t *wc_u32 = (const uint32_t *) &wc->masks;
566     size_t i;
567
568     for (i = 0; i < FLOW_U32S; i++) {
569         if (wc_u32[i]) {
570             return false;
571         }
572     }
573     return true;
574 }
575
576 /* Initializes 'dst' as the combination of wildcards in 'src1' and 'src2'.
577  * That is, a bit or a field is wildcarded in 'dst' if it is wildcarded in
578  * 'src1' or 'src2' or both.  */
579 void
580 flow_wildcards_combine(struct flow_wildcards *dst,
581                        const struct flow_wildcards *src1,
582                        const struct flow_wildcards *src2)
583 {
584     uint32_t *dst_u32 = (uint32_t *) &dst->masks;
585     const uint32_t *src1_u32 = (const uint32_t *) &src1->masks;
586     const uint32_t *src2_u32 = (const uint32_t *) &src2->masks;
587     size_t i;
588
589     for (i = 0; i < FLOW_U32S; i++) {
590         dst_u32[i] = src1_u32[i] & src2_u32[i];
591     }
592 }
593
594 /* Returns a hash of the wildcards in 'wc'. */
595 uint32_t
596 flow_wildcards_hash(const struct flow_wildcards *wc, uint32_t basis)
597 {
598     return flow_hash(&wc->masks, basis);;
599 }
600
601 /* Returns true if 'a' and 'b' represent the same wildcards, false if they are
602  * different. */
603 bool
604 flow_wildcards_equal(const struct flow_wildcards *a,
605                      const struct flow_wildcards *b)
606 {
607     return flow_equal(&a->masks, &b->masks);
608 }
609
610 /* Returns true if at least one bit or field is wildcarded in 'a' but not in
611  * 'b', false otherwise. */
612 bool
613 flow_wildcards_has_extra(const struct flow_wildcards *a,
614                          const struct flow_wildcards *b)
615 {
616     const uint32_t *a_u32 = (const uint32_t *) &a->masks;
617     const uint32_t *b_u32 = (const uint32_t *) &b->masks;
618     size_t i;
619
620     for (i = 0; i < FLOW_U32S; i++) {
621         if ((a_u32[i] & b_u32[i]) != b_u32[i]) {
622             return true;
623         }
624     }
625     return false;
626 }
627
628 /* Returns true if 'a' and 'b' are equal, except that 0-bits (wildcarded bits)
629  * in 'wc' do not need to be equal in 'a' and 'b'. */
630 bool
631 flow_equal_except(const struct flow *a, const struct flow *b,
632                   const struct flow_wildcards *wc)
633 {
634     const uint32_t *a_u32 = (const uint32_t *) a;
635     const uint32_t *b_u32 = (const uint32_t *) b;
636     const uint32_t *wc_u32 = (const uint32_t *) &wc->masks;
637     size_t i;
638
639     for (i = 0; i < FLOW_U32S; i++) {
640         if ((a_u32[i] ^ b_u32[i]) & wc_u32[i]) {
641             return false;
642         }
643     }
644     return true;
645 }
646
647 /* Sets the wildcard mask for register 'idx' in 'wc' to 'mask'.
648  * (A 0-bit indicates a wildcard bit.) */
649 void
650 flow_wildcards_set_reg_mask(struct flow_wildcards *wc, int idx, uint32_t mask)
651 {
652     wc->masks.regs[idx] = mask;
653 }
654
655 /* Hashes 'flow' based on its L2 through L4 protocol information. */
656 uint32_t
657 flow_hash_symmetric_l4(const struct flow *flow, uint32_t basis)
658 {
659     struct {
660         union {
661             ovs_be32 ipv4_addr;
662             struct in6_addr ipv6_addr;
663         };
664         ovs_be16 eth_type;
665         ovs_be16 vlan_tci;
666         ovs_be16 tp_port;
667         uint8_t eth_addr[ETH_ADDR_LEN];
668         uint8_t ip_proto;
669     } fields;
670
671     int i;
672
673     memset(&fields, 0, sizeof fields);
674     for (i = 0; i < ETH_ADDR_LEN; i++) {
675         fields.eth_addr[i] = flow->dl_src[i] ^ flow->dl_dst[i];
676     }
677     fields.vlan_tci = flow->vlan_tci & htons(VLAN_VID_MASK);
678     fields.eth_type = flow->dl_type;
679
680     /* UDP source and destination port are not taken into account because they
681      * will not necessarily be symmetric in a bidirectional flow. */
682     if (fields.eth_type == htons(ETH_TYPE_IP)) {
683         fields.ipv4_addr = flow->nw_src ^ flow->nw_dst;
684         fields.ip_proto = flow->nw_proto;
685         if (fields.ip_proto == IPPROTO_TCP) {
686             fields.tp_port = flow->tp_src ^ flow->tp_dst;
687         }
688     } else if (fields.eth_type == htons(ETH_TYPE_IPV6)) {
689         const uint8_t *a = &flow->ipv6_src.s6_addr[0];
690         const uint8_t *b = &flow->ipv6_dst.s6_addr[0];
691         uint8_t *ipv6_addr = &fields.ipv6_addr.s6_addr[0];
692
693         for (i=0; i<16; i++) {
694             ipv6_addr[i] = a[i] ^ b[i];
695         }
696         fields.ip_proto = flow->nw_proto;
697         if (fields.ip_proto == IPPROTO_TCP) {
698             fields.tp_port = flow->tp_src ^ flow->tp_dst;
699         }
700     }
701     return hash_bytes(&fields, sizeof fields, basis);
702 }
703
704 /* Hashes the portions of 'flow' designated by 'fields'. */
705 uint32_t
706 flow_hash_fields(const struct flow *flow, enum nx_hash_fields fields,
707                  uint16_t basis)
708 {
709     switch (fields) {
710
711     case NX_HASH_FIELDS_ETH_SRC:
712         return hash_bytes(flow->dl_src, sizeof flow->dl_src, basis);
713
714     case NX_HASH_FIELDS_SYMMETRIC_L4:
715         return flow_hash_symmetric_l4(flow, basis);
716     }
717
718     NOT_REACHED();
719 }
720
721 /* Returns a string representation of 'fields'. */
722 const char *
723 flow_hash_fields_to_str(enum nx_hash_fields fields)
724 {
725     switch (fields) {
726     case NX_HASH_FIELDS_ETH_SRC: return "eth_src";
727     case NX_HASH_FIELDS_SYMMETRIC_L4: return "symmetric_l4";
728     default: return "<unknown>";
729     }
730 }
731
732 /* Returns true if the value of 'fields' is supported. Otherwise false. */
733 bool
734 flow_hash_fields_valid(enum nx_hash_fields fields)
735 {
736     return fields == NX_HASH_FIELDS_ETH_SRC
737         || fields == NX_HASH_FIELDS_SYMMETRIC_L4;
738 }
739
740 /* Sets the VLAN VID that 'flow' matches to 'vid', which is interpreted as an
741  * OpenFlow 1.0 "dl_vlan" value:
742  *
743  *      - If it is in the range 0...4095, 'flow->vlan_tci' is set to match
744  *        that VLAN.  Any existing PCP match is unchanged (it becomes 0 if
745  *        'flow' previously matched packets without a VLAN header).
746  *
747  *      - If it is OFP_VLAN_NONE, 'flow->vlan_tci' is set to match a packet
748  *        without a VLAN tag.
749  *
750  *      - Other values of 'vid' should not be used. */
751 void
752 flow_set_dl_vlan(struct flow *flow, ovs_be16 vid)
753 {
754     if (vid == htons(OFP10_VLAN_NONE)) {
755         flow->vlan_tci = htons(0);
756     } else {
757         vid &= htons(VLAN_VID_MASK);
758         flow->vlan_tci &= ~htons(VLAN_VID_MASK);
759         flow->vlan_tci |= htons(VLAN_CFI) | vid;
760     }
761 }
762
763 /* Sets the VLAN VID that 'flow' matches to 'vid', which is interpreted as an
764  * OpenFlow 1.2 "vlan_vid" value, that is, the low 13 bits of 'vlan_tci' (VID
765  * plus CFI). */
766 void
767 flow_set_vlan_vid(struct flow *flow, ovs_be16 vid)
768 {
769     ovs_be16 mask = htons(VLAN_VID_MASK | VLAN_CFI);
770     flow->vlan_tci &= ~mask;
771     flow->vlan_tci |= vid & mask;
772 }
773
774 /* Sets the VLAN PCP that 'flow' matches to 'pcp', which should be in the
775  * range 0...7.
776  *
777  * This function has no effect on the VLAN ID that 'flow' matches.
778  *
779  * After calling this function, 'flow' will not match packets without a VLAN
780  * header. */
781 void
782 flow_set_vlan_pcp(struct flow *flow, uint8_t pcp)
783 {
784     pcp &= 0x07;
785     flow->vlan_tci &= ~htons(VLAN_PCP_MASK);
786     flow->vlan_tci |= htons((pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
787 }
788
789 /* Puts into 'b' a packet that flow_extract() would parse as having the given
790  * 'flow'.
791  *
792  * (This is useful only for testing, obviously, and the packet isn't really
793  * valid. It hasn't got some checksums filled in, for one, and lots of fields
794  * are just zeroed.) */
795 void
796 flow_compose(struct ofpbuf *b, const struct flow *flow)
797 {
798     eth_compose(b, flow->dl_dst, flow->dl_src, ntohs(flow->dl_type), 0);
799     if (flow->dl_type == htons(FLOW_DL_TYPE_NONE)) {
800         struct eth_header *eth = b->l2;
801         eth->eth_type = htons(b->size);
802         return;
803     }
804
805     if (flow->vlan_tci & htons(VLAN_CFI)) {
806         eth_push_vlan(b, flow->vlan_tci);
807     }
808
809     if (flow->dl_type == htons(ETH_TYPE_IP)) {
810         struct ip_header *ip;
811
812         b->l3 = ip = ofpbuf_put_zeros(b, sizeof *ip);
813         ip->ip_ihl_ver = IP_IHL_VER(5, 4);
814         ip->ip_tos = flow->nw_tos;
815         ip->ip_proto = flow->nw_proto;
816         put_16aligned_be32(&ip->ip_src, flow->nw_src);
817         put_16aligned_be32(&ip->ip_dst, flow->nw_dst);
818
819         if (flow->nw_frag & FLOW_NW_FRAG_ANY) {
820             ip->ip_frag_off |= htons(IP_MORE_FRAGMENTS);
821             if (flow->nw_frag & FLOW_NW_FRAG_LATER) {
822                 ip->ip_frag_off |= htons(100);
823             }
824         }
825         if (!(flow->nw_frag & FLOW_NW_FRAG_ANY)
826             || !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
827             if (flow->nw_proto == IPPROTO_TCP) {
828                 struct tcp_header *tcp;
829
830                 b->l4 = tcp = ofpbuf_put_zeros(b, sizeof *tcp);
831                 tcp->tcp_src = flow->tp_src;
832                 tcp->tcp_dst = flow->tp_dst;
833                 tcp->tcp_ctl = TCP_CTL(0, 5);
834             } else if (flow->nw_proto == IPPROTO_UDP) {
835                 struct udp_header *udp;
836
837                 b->l4 = udp = ofpbuf_put_zeros(b, sizeof *udp);
838                 udp->udp_src = flow->tp_src;
839                 udp->udp_dst = flow->tp_dst;
840             } else if (flow->nw_proto == IPPROTO_ICMP) {
841                 struct icmp_header *icmp;
842
843                 b->l4 = icmp = ofpbuf_put_zeros(b, sizeof *icmp);
844                 icmp->icmp_type = ntohs(flow->tp_src);
845                 icmp->icmp_code = ntohs(flow->tp_dst);
846                 icmp->icmp_csum = csum(icmp, ICMP_HEADER_LEN);
847             }
848         }
849
850         ip = b->l3;
851         ip->ip_tot_len = htons((uint8_t *) b->data + b->size
852                                - (uint8_t *) b->l3);
853         ip->ip_csum = csum(ip, sizeof *ip);
854     } else if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
855         /* XXX */
856     } else if (flow->dl_type == htons(ETH_TYPE_ARP) ||
857                flow->dl_type == htons(ETH_TYPE_RARP)) {
858         struct arp_eth_header *arp;
859
860         b->l3 = arp = ofpbuf_put_zeros(b, sizeof *arp);
861         arp->ar_hrd = htons(1);
862         arp->ar_pro = htons(ETH_TYPE_IP);
863         arp->ar_hln = ETH_ADDR_LEN;
864         arp->ar_pln = 4;
865         arp->ar_op = htons(flow->nw_proto);
866
867         if (flow->nw_proto == ARP_OP_REQUEST ||
868             flow->nw_proto == ARP_OP_REPLY) {
869             put_16aligned_be32(&arp->ar_spa, flow->nw_src);
870             put_16aligned_be32(&arp->ar_tpa, flow->nw_dst);
871             memcpy(arp->ar_sha, flow->arp_sha, ETH_ADDR_LEN);
872             memcpy(arp->ar_tha, flow->arp_tha, ETH_ADDR_LEN);
873         }
874     }
875 }
876 \f
877 /* Compressed flow. */
878
879 static int
880 miniflow_n_values(const struct miniflow *flow)
881 {
882     int n, i;
883
884     n = 0;
885     for (i = 0; i < MINI_N_MAPS; i++) {
886         n += popcount(flow->map[i]);
887     }
888     return n;
889 }
890
891 static uint32_t *
892 miniflow_alloc_values(struct miniflow *flow, int n)
893 {
894     if (n <= MINI_N_INLINE) {
895         return flow->inline_values;
896     } else {
897         COVERAGE_INC(miniflow_malloc);
898         return xmalloc(n * sizeof *flow->values);
899     }
900 }
901
902 /* Initializes 'dst' as a copy of 'src'.  The caller must eventually free 'dst'
903  * with miniflow_destroy(). */
904 void
905 miniflow_init(struct miniflow *dst, const struct flow *src)
906 {
907     const uint32_t *src_u32 = (const uint32_t *) src;
908     unsigned int ofs;
909     unsigned int i;
910     int n;
911
912     /* Initialize dst->map, counting the number of nonzero elements. */
913     n = 0;
914     memset(dst->map, 0, sizeof dst->map);
915     for (i = 0; i < FLOW_U32S; i++) {
916         if (src_u32[i]) {
917             dst->map[i / 32] |= 1u << (i % 32);
918             n++;
919         }
920     }
921
922     /* Initialize dst->values. */
923     dst->values = miniflow_alloc_values(dst, n);
924     ofs = 0;
925     for (i = 0; i < MINI_N_MAPS; i++) {
926         uint32_t map;
927
928         for (map = dst->map[i]; map; map = zero_rightmost_1bit(map)) {
929             dst->values[ofs++] = src_u32[raw_ctz(map) + i * 32];
930         }
931     }
932 }
933
934 /* Initializes 'dst' as a copy of 'src'.  The caller must eventually free 'dst'
935  * with miniflow_destroy(). */
936 void
937 miniflow_clone(struct miniflow *dst, const struct miniflow *src)
938 {
939     int n = miniflow_n_values(src);
940     memcpy(dst->map, src->map, sizeof dst->map);
941     dst->values = miniflow_alloc_values(dst, n);
942     memcpy(dst->values, src->values, n * sizeof *dst->values);
943 }
944
945 /* Frees any memory owned by 'flow'.  Does not free the storage in which 'flow'
946  * itself resides; the caller is responsible for that. */
947 void
948 miniflow_destroy(struct miniflow *flow)
949 {
950     if (flow->values != flow->inline_values) {
951         free(flow->values);
952     }
953 }
954
955 /* Initializes 'dst' as a copy of 'src'. */
956 void
957 miniflow_expand(const struct miniflow *src, struct flow *dst)
958 {
959     uint32_t *dst_u32 = (uint32_t *) dst;
960     int ofs;
961     int i;
962
963     memset(dst_u32, 0, sizeof *dst);
964
965     ofs = 0;
966     for (i = 0; i < MINI_N_MAPS; i++) {
967         uint32_t map;
968
969         for (map = src->map[i]; map; map = zero_rightmost_1bit(map)) {
970             dst_u32[raw_ctz(map) + i * 32] = src->values[ofs++];
971         }
972     }
973 }
974
975 static const uint32_t *
976 miniflow_get__(const struct miniflow *flow, unsigned int u32_ofs)
977 {
978     if (!(flow->map[u32_ofs / 32] & (1u << (u32_ofs % 32)))) {
979         static const uint32_t zero = 0;
980         return &zero;
981     } else {
982         const uint32_t *p = flow->values;
983
984         BUILD_ASSERT(MINI_N_MAPS == 2);
985         if (u32_ofs < 32) {
986             p += popcount(flow->map[0] & ((1u << u32_ofs) - 1));
987         } else {
988             p += popcount(flow->map[0]);
989             p += popcount(flow->map[1] & ((1u << (u32_ofs - 32)) - 1));
990         }
991         return p;
992     }
993 }
994
995 /* Returns the uint32_t that would be at byte offset '4 * u32_ofs' if 'flow'
996  * were expanded into a "struct flow". */
997 uint32_t
998 miniflow_get(const struct miniflow *flow, unsigned int u32_ofs)
999 {
1000     return *miniflow_get__(flow, u32_ofs);
1001 }
1002
1003 /* Returns the ovs_be16 that would be at byte offset 'u8_ofs' if 'flow' were
1004  * expanded into a "struct flow". */
1005 static ovs_be16
1006 miniflow_get_be16(const struct miniflow *flow, unsigned int u8_ofs)
1007 {
1008     const uint32_t *u32p = miniflow_get__(flow, u8_ofs / 4);
1009     const ovs_be16 *be16p = (const ovs_be16 *) u32p;
1010     return be16p[u8_ofs % 4 != 0];
1011 }
1012
1013 /* Returns the VID within the vlan_tci member of the "struct flow" represented
1014  * by 'flow'. */
1015 uint16_t
1016 miniflow_get_vid(const struct miniflow *flow)
1017 {
1018     ovs_be16 tci = miniflow_get_be16(flow, offsetof(struct flow, vlan_tci));
1019     return vlan_tci_to_vid(tci);
1020 }
1021
1022 /* Returns true if 'a' and 'b' are the same flow, false otherwise.  */
1023 bool
1024 miniflow_equal(const struct miniflow *a, const struct miniflow *b)
1025 {
1026     int i;
1027
1028     for (i = 0; i < MINI_N_MAPS; i++) {
1029         if (a->map[i] != b->map[i]) {
1030             return false;
1031         }
1032     }
1033
1034     return !memcmp(a->values, b->values,
1035                    miniflow_n_values(a) * sizeof *a->values);
1036 }
1037
1038 /* Returns true if 'a' and 'b' are equal at the places where there are 1-bits
1039  * in 'mask', false if they differ. */
1040 bool
1041 miniflow_equal_in_minimask(const struct miniflow *a, const struct miniflow *b,
1042                            const struct minimask *mask)
1043 {
1044     const uint32_t *p;
1045     int i;
1046
1047     p = mask->masks.values;
1048     for (i = 0; i < MINI_N_MAPS; i++) {
1049         uint32_t map;
1050
1051         for (map = mask->masks.map[i]; map; map = zero_rightmost_1bit(map)) {
1052             int ofs = raw_ctz(map) + i * 32;
1053
1054             if ((miniflow_get(a, ofs) ^ miniflow_get(b, ofs)) & *p) {
1055                 return false;
1056             }
1057             p++;
1058         }
1059     }
1060
1061     return true;
1062 }
1063
1064 /* Returns true if 'a' and 'b' are equal at the places where there are 1-bits
1065  * in 'mask', false if they differ. */
1066 bool
1067 miniflow_equal_flow_in_minimask(const struct miniflow *a, const struct flow *b,
1068                                 const struct minimask *mask)
1069 {
1070     const uint32_t *b_u32 = (const uint32_t *) b;
1071     const uint32_t *p;
1072     int i;
1073
1074     p = mask->masks.values;
1075     for (i = 0; i < MINI_N_MAPS; i++) {
1076         uint32_t map;
1077
1078         for (map = mask->masks.map[i]; map; map = zero_rightmost_1bit(map)) {
1079             int ofs = raw_ctz(map) + i * 32;
1080
1081             if ((miniflow_get(a, ofs) ^ b_u32[ofs]) & *p) {
1082                 return false;
1083             }
1084             p++;
1085         }
1086     }
1087
1088     return true;
1089 }
1090
1091 /* Returns a hash value for 'flow', given 'basis'. */
1092 uint32_t
1093 miniflow_hash(const struct miniflow *flow, uint32_t basis)
1094 {
1095     BUILD_ASSERT_DECL(MINI_N_MAPS == 2);
1096     return hash_3words(flow->map[0], flow->map[1],
1097                        hash_words(flow->values, miniflow_n_values(flow),
1098                                   basis));
1099 }
1100
1101 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
1102  * 'mask', given 'basis'.
1103  *
1104  * The hash values returned by this function are the same as those returned by
1105  * flow_hash_in_minimask(), only the form of the arguments differ. */
1106 uint32_t
1107 miniflow_hash_in_minimask(const struct miniflow *flow,
1108                           const struct minimask *mask, uint32_t basis)
1109 {
1110     const uint32_t *p = mask->masks.values;
1111     uint32_t hash;
1112     int i;
1113
1114     hash = basis;
1115     for (i = 0; i < MINI_N_MAPS; i++) {
1116         uint32_t map;
1117
1118         for (map = mask->masks.map[i]; map; map = zero_rightmost_1bit(map)) {
1119             int ofs = raw_ctz(map) + i * 32;
1120
1121             hash = mhash_add(hash, miniflow_get(flow, ofs) & *p);
1122             p++;
1123         }
1124     }
1125
1126     return mhash_finish(hash, p - mask->masks.values);
1127 }
1128
1129 /* Returns a hash value for the bits of 'flow' where there are 1-bits in
1130  * 'mask', given 'basis'.
1131  *
1132  * The hash values returned by this function are the same as those returned by
1133  * miniflow_hash_in_minimask(), only the form of the arguments differ. */
1134 uint32_t
1135 flow_hash_in_minimask(const struct flow *flow, const struct minimask *mask,
1136                       uint32_t basis)
1137 {
1138     const uint32_t *flow_u32 = (const uint32_t *) flow;
1139     const uint32_t *p = mask->masks.values;
1140     uint32_t hash;
1141     int i;
1142
1143     hash = basis;
1144     for (i = 0; i < MINI_N_MAPS; i++) {
1145         uint32_t map;
1146
1147         for (map = mask->masks.map[i]; map; map = zero_rightmost_1bit(map)) {
1148             int ofs = raw_ctz(map) + i * 32;
1149
1150             hash = mhash_add(hash, flow_u32[ofs] & *p);
1151             p++;
1152         }
1153     }
1154
1155     return mhash_finish(hash, p - mask->masks.values);
1156 }
1157 \f
1158 /* Initializes 'dst' as a copy of 'src'.  The caller must eventually free 'dst'
1159  * with minimask_destroy(). */
1160 void
1161 minimask_init(struct minimask *mask, const struct flow_wildcards *wc)
1162 {
1163     miniflow_init(&mask->masks, &wc->masks);
1164 }
1165
1166 /* Initializes 'dst' as a copy of 'src'.  The caller must eventually free 'dst'
1167  * with minimask_destroy(). */
1168 void
1169 minimask_clone(struct minimask *dst, const struct minimask *src)
1170 {
1171     miniflow_clone(&dst->masks, &src->masks);
1172 }
1173
1174 /* Initializes 'dst_' as the bit-wise "and" of 'a_' and 'b_'.
1175  *
1176  * The caller must provide room for FLOW_U32S "uint32_t"s in 'storage', for use
1177  * by 'dst_'.  The caller must *not* free 'dst_' with minimask_destroy(). */
1178 void
1179 minimask_combine(struct minimask *dst_,
1180                  const struct minimask *a_, const struct minimask *b_,
1181                  uint32_t storage[FLOW_U32S])
1182 {
1183     struct miniflow *dst = &dst_->masks;
1184     const struct miniflow *a = &a_->masks;
1185     const struct miniflow *b = &b_->masks;
1186     int i, n;
1187
1188     n = 0;
1189     dst->values = storage;
1190     for (i = 0; i < MINI_N_MAPS; i++) {
1191         uint32_t map;
1192
1193         dst->map[i] = 0;
1194         for (map = a->map[i] & b->map[i]; map;
1195              map = zero_rightmost_1bit(map)) {
1196             int ofs = raw_ctz(map) + i * 32;
1197             uint32_t mask = miniflow_get(a, ofs) & miniflow_get(b, ofs);
1198
1199             if (mask) {
1200                 dst->map[i] |= rightmost_1bit(map);
1201                 dst->values[n++] = mask;
1202             }
1203         }
1204     }
1205 }
1206
1207 /* Frees any memory owned by 'mask'.  Does not free the storage in which 'mask'
1208  * itself resides; the caller is responsible for that. */
1209 void
1210 minimask_destroy(struct minimask *mask)
1211 {
1212     miniflow_destroy(&mask->masks);
1213 }
1214
1215 /* Initializes 'dst' as a copy of 'src'. */
1216 void
1217 minimask_expand(const struct minimask *mask, struct flow_wildcards *wc)
1218 {
1219     miniflow_expand(&mask->masks, &wc->masks);
1220 }
1221
1222 /* Returns the uint32_t that would be at byte offset '4 * u32_ofs' if 'mask'
1223  * were expanded into a "struct flow_wildcards". */
1224 uint32_t
1225 minimask_get(const struct minimask *mask, unsigned int u32_ofs)
1226 {
1227     return miniflow_get(&mask->masks, u32_ofs);
1228 }
1229
1230 /* Returns the VID mask within the vlan_tci member of the "struct
1231  * flow_wildcards" represented by 'mask'. */
1232 uint16_t
1233 minimask_get_vid_mask(const struct minimask *mask)
1234 {
1235     return miniflow_get_vid(&mask->masks);
1236 }
1237
1238 /* Returns true if 'a' and 'b' are the same flow mask, false otherwise.  */
1239 bool
1240 minimask_equal(const struct minimask *a, const struct minimask *b)
1241 {
1242     return miniflow_equal(&a->masks, &b->masks);
1243 }
1244
1245 /* Returns a hash value for 'mask', given 'basis'. */
1246 uint32_t
1247 minimask_hash(const struct minimask *mask, uint32_t basis)
1248 {
1249     return miniflow_hash(&mask->masks, basis);
1250 }
1251
1252 /* Returns true if at least one bit is wildcarded in 'a_' but not in 'b_',
1253  * false otherwise. */
1254 bool
1255 minimask_has_extra(const struct minimask *a_, const struct minimask *b_)
1256 {
1257     const struct miniflow *a = &a_->masks;
1258     const struct miniflow *b = &b_->masks;
1259     int i;
1260
1261     for (i = 0; i < MINI_N_MAPS; i++) {
1262         uint32_t map;
1263
1264         for (map = a->map[i] | b->map[i]; map;
1265              map = zero_rightmost_1bit(map)) {
1266             int ofs = raw_ctz(map) + i * 32;
1267             uint32_t a_u32 = miniflow_get(a, ofs);
1268             uint32_t b_u32 = miniflow_get(b, ofs);
1269
1270             if ((a_u32 & b_u32) != b_u32) {
1271                 return true;
1272             }
1273         }
1274     }
1275
1276     return false;
1277 }
1278
1279 /* Returns true if 'mask' matches every packet, false if 'mask' fixes any bits
1280  * or fields. */
1281 bool
1282 minimask_is_catchall(const struct minimask *mask_)
1283 {
1284     const struct miniflow *mask = &mask_->masks;
1285
1286     BUILD_ASSERT(MINI_N_MAPS == 2);
1287     return !(mask->map[0] | mask->map[1]);
1288 }