flow: Define miniflow_get__() to simplify code.
[cascardo/ovs.git] / lib / flow.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 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 <errno.h>
20 #include <inttypes.h>
21 #include <limits.h>
22 #include <netinet/in.h>
23 #include <netinet/icmp6.h>
24 #include <netinet/ip6.h>
25 #include <stdint.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include "byte-order.h"
29 #include "coverage.h"
30 #include "csum.h"
31 #include "dynamic-string.h"
32 #include "hash.h"
33 #include "jhash.h"
34 #include "match.h"
35 #include "ofpbuf.h"
36 #include "openflow/openflow.h"
37 #include "packets.h"
38 #include "odp-util.h"
39 #include "random.h"
40 #include "unaligned.h"
41
42 COVERAGE_DEFINE(flow_extract);
43 COVERAGE_DEFINE(miniflow_malloc);
44
45 /* U32 indices for segmented flow classification. */
46 const uint8_t flow_segment_u32s[4] = {
47     FLOW_SEGMENT_1_ENDS_AT / 4,
48     FLOW_SEGMENT_2_ENDS_AT / 4,
49     FLOW_SEGMENT_3_ENDS_AT / 4,
50     FLOW_U32S
51 };
52
53 /* miniflow_extract() assumes the following to be true to optimize the
54  * extraction process. */
55 BUILD_ASSERT_DECL(offsetof(struct flow, dl_type) + 2
56                   == offsetof(struct flow, vlan_tci) &&
57                   offsetof(struct flow, dl_type) / 4
58                   == offsetof(struct flow, vlan_tci) / 4 );
59
60 BUILD_ASSERT_DECL(offsetof(struct flow, nw_frag) + 3
61                   == offsetof(struct flow, nw_proto) &&
62                   offsetof(struct flow, nw_tos) + 2
63                   == offsetof(struct flow, nw_proto) &&
64                   offsetof(struct flow, nw_ttl) + 1
65                   == offsetof(struct flow, nw_proto) &&
66                   offsetof(struct flow, nw_frag) / 4
67                   == offsetof(struct flow, nw_tos) / 4 &&
68                   offsetof(struct flow, nw_ttl) / 4
69                   == offsetof(struct flow, nw_tos) / 4 &&
70                   offsetof(struct flow, nw_proto) / 4
71                   == offsetof(struct flow, nw_tos) / 4);
72
73 /* TCP flags in the first half of a BE32, zeroes in the other half. */
74 BUILD_ASSERT_DECL(offsetof(struct flow, tcp_flags) + 2
75                   == offsetof(struct flow, pad2) &&
76                   offsetof(struct flow, tcp_flags) / 4
77                   == offsetof(struct flow, pad2) / 4);
78 #if WORDS_BIGENDIAN
79 #define TCP_FLAGS_BE32(tcp_ctl) ((OVS_FORCE ovs_be32)TCP_FLAGS_BE16(tcp_ctl) \
80                                  << 16)
81 #else
82 #define TCP_FLAGS_BE32(tcp_ctl) ((OVS_FORCE ovs_be32)TCP_FLAGS_BE16(tcp_ctl))
83 #endif
84
85 BUILD_ASSERT_DECL(offsetof(struct flow, tp_src) + 2
86                   == offsetof(struct flow, tp_dst) &&
87                   offsetof(struct flow, tp_src) / 4
88                   == offsetof(struct flow, tp_dst) / 4);
89
90 /* Removes 'size' bytes from the head end of '*datap', of size '*sizep', which
91  * must contain at least 'size' bytes of data.  Returns the first byte of data
92  * removed. */
93 static inline const void *
94 data_pull(void **datap, size_t *sizep, size_t size)
95 {
96     char *data = (char *)*datap;
97     *datap = data + size;
98     *sizep -= size;
99     return data;
100 }
101
102 /* If '*datap' has at least 'size' bytes of data, removes that many bytes from
103  * the head end of '*datap' and returns the first byte removed.  Otherwise,
104  * returns a null pointer without modifying '*datap'. */
105 static inline const void *
106 data_try_pull(void **datap, size_t *sizep, size_t size)
107 {
108     return OVS_LIKELY(*sizep >= size) ? data_pull(datap, sizep, size) : NULL;
109 }
110
111 /* Context for pushing data to a miniflow. */
112 struct mf_ctx {
113     uint64_t map;
114     uint32_t *data;
115     uint32_t * const end;
116 };
117
118 /* miniflow_push_* macros allow filling in a miniflow data values in order.
119  * Assertions are needed only when the layout of the struct flow is modified.
120  * 'ofs' is a compile-time constant, which allows most of the code be optimized
121  * away.  Some GCC versions gave warnings on ALWAYS_INLINE, so these are
122  * defined as macros. */
123
124 #if (FLOW_WC_SEQ != 28)
125 #define MINIFLOW_ASSERT(X) ovs_assert(X)
126 BUILD_MESSAGE("FLOW_WC_SEQ changed: miniflow_extract() will have runtime "
127                "assertions enabled. Consider updating FLOW_WC_SEQ after "
128                "testing")
129 #else
130 #define MINIFLOW_ASSERT(X)
131 #endif
132
133 #define miniflow_push_uint32_(MF, OFS, VALUE)                   \
134 {                                                               \
135     MINIFLOW_ASSERT(MF.data < MF.end && (OFS) % 4 == 0          \
136                     && !(MF.map & (UINT64_MAX << (OFS) / 4)));  \
137     *MF.data++ = VALUE;                                         \
138     MF.map |= UINT64_C(1) << (OFS) / 4;                         \
139 }
140
141 #define miniflow_push_be32_(MF, OFS, VALUE) \
142     miniflow_push_uint32_(MF, OFS, (OVS_FORCE uint32_t)(VALUE))
143
144 #define miniflow_push_uint16_(MF, OFS, VALUE)                   \
145 {                                                               \
146     MINIFLOW_ASSERT(MF.data < MF.end &&                                 \
147                     (((OFS) % 4 == 0 && !(MF.map & (UINT64_MAX << (OFS) / 4))) \
148                      || ((OFS) % 4 == 2 && MF.map & (UINT64_C(1) << (OFS) / 4) \
149                          && !(MF.map & (UINT64_MAX << ((OFS) / 4 + 1)))))); \
150                                                                         \
151     if ((OFS) % 4 == 0) {                                               \
152         *(uint16_t *)MF.data = VALUE;                                   \
153         MF.map |= UINT64_C(1) << (OFS) / 4;                             \
154     } else if ((OFS) % 4 == 2) {                                        \
155         *((uint16_t *)MF.data + 1) = VALUE;                             \
156         MF.data++;                                                      \
157     }                                                                   \
158 }
159
160 #define miniflow_push_be16_(MF, OFS, VALUE)             \
161     miniflow_push_uint16_(MF, OFS, (OVS_FORCE uint16_t)VALUE);
162
163 /* Data at 'valuep' may be unaligned. */
164 #define miniflow_push_words_(MF, OFS, VALUEP, N_WORDS)          \
165 {                                                               \
166     int ofs32 = (OFS) / 4;                                      \
167                                                                         \
168     MINIFLOW_ASSERT(MF.data + (N_WORDS) <= MF.end && (OFS) % 4 == 0     \
169                     && !(MF.map & (UINT64_MAX << ofs32)));              \
170                                                                         \
171     memcpy(MF.data, (VALUEP), (N_WORDS) * sizeof *MF.data);             \
172     MF.data += (N_WORDS);                                               \
173     MF.map |= ((UINT64_MAX >> (64 - (N_WORDS))) << ofs32);              \
174 }
175
176 #define miniflow_push_uint32(MF, FIELD, VALUE)                          \
177     miniflow_push_uint32_(MF, offsetof(struct flow, FIELD), VALUE)
178
179 #define miniflow_push_be32(MF, FIELD, VALUE)                            \
180     miniflow_push_be32_(MF, offsetof(struct flow, FIELD), VALUE)
181
182 #define miniflow_push_uint32_check(MF, FIELD, VALUE)                    \
183     { if (OVS_LIKELY(VALUE)) {                                          \
184             miniflow_push_uint32_(MF, offsetof(struct flow, FIELD), VALUE); \
185         }                                                               \
186     }
187
188 #define miniflow_push_be32_check(MF, FIELD, VALUE)                      \
189     { if (OVS_LIKELY(VALUE)) {                                          \
190             miniflow_push_be32_(MF, offsetof(struct flow, FIELD), VALUE); \
191         }                                                               \
192     }
193
194 #define miniflow_push_uint16(MF, FIELD, VALUE)                          \
195     miniflow_push_uint16_(MF, offsetof(struct flow, FIELD), VALUE)
196
197 #define miniflow_push_be16(MF, FIELD, VALUE)                            \
198     miniflow_push_be16_(MF, offsetof(struct flow, FIELD), VALUE)
199
200 #define miniflow_push_words(MF, FIELD, VALUEP, N_WORDS)                 \
201     miniflow_push_words_(MF, offsetof(struct flow, FIELD), VALUEP, N_WORDS)
202
203 /* Pulls the MPLS headers at '*datap' and returns the count of them. */
204 static inline int
205 parse_mpls(void **datap, size_t *sizep)
206 {
207     const struct mpls_hdr *mh;
208     int count = 0;
209
210     while ((mh = data_try_pull(datap, sizep, sizeof *mh))) {
211         count++;
212         if (mh->mpls_lse.lo & htons(1 << MPLS_BOS_SHIFT)) {
213             break;
214         }
215     }
216     return MIN(count, FLOW_MAX_MPLS_LABELS);
217 }
218
219 static inline ovs_be16
220 parse_vlan(void **datap, size_t *sizep)
221 {
222     const struct eth_header *eth = *datap;
223
224     struct qtag_prefix {
225         ovs_be16 eth_type;      /* ETH_TYPE_VLAN */
226         ovs_be16 tci;
227     };
228
229     data_pull(datap, sizep, ETH_ADDR_LEN * 2);
230
231     if (eth->eth_type == htons(ETH_TYPE_VLAN)) {
232         if (OVS_LIKELY(*sizep
233                        >= sizeof(struct qtag_prefix) + sizeof(ovs_be16))) {
234             const struct qtag_prefix *qp = data_pull(datap, sizep, sizeof *qp);
235             return qp->tci | htons(VLAN_CFI);
236         }
237     }
238     return 0;
239 }
240
241 static inline ovs_be16
242 parse_ethertype(void **datap, size_t *sizep)
243 {
244     const struct llc_snap_header *llc;
245     ovs_be16 proto;
246
247     proto = *(ovs_be16 *) data_pull(datap, sizep, sizeof proto);
248     if (OVS_LIKELY(ntohs(proto) >= ETH_TYPE_MIN)) {
249         return proto;
250     }
251
252     if (OVS_UNLIKELY(*sizep < sizeof *llc)) {
253         return htons(FLOW_DL_TYPE_NONE);
254     }
255
256     llc = *datap;
257     if (OVS_UNLIKELY(llc->llc.llc_dsap != LLC_DSAP_SNAP
258                      || llc->llc.llc_ssap != LLC_SSAP_SNAP
259                      || llc->llc.llc_cntl != LLC_CNTL_SNAP
260                      || memcmp(llc->snap.snap_org, SNAP_ORG_ETHERNET,
261                                sizeof llc->snap.snap_org))) {
262         return htons(FLOW_DL_TYPE_NONE);
263     }
264
265     data_pull(datap, sizep, sizeof *llc);
266
267     if (OVS_LIKELY(ntohs(llc->snap.snap_type) >= ETH_TYPE_MIN)) {
268         return llc->snap.snap_type;
269     }
270
271     return htons(FLOW_DL_TYPE_NONE);
272 }
273
274 static inline bool
275 parse_icmpv6(void **datap, size_t *sizep, const struct icmp6_hdr *icmp,
276              const struct in6_addr **nd_target,
277              uint8_t arp_buf[2][ETH_ADDR_LEN])
278 {
279     if (icmp->icmp6_code == 0 &&
280         (icmp->icmp6_type == ND_NEIGHBOR_SOLICIT ||
281          icmp->icmp6_type == ND_NEIGHBOR_ADVERT)) {
282
283         *nd_target = data_try_pull(datap, sizep, sizeof **nd_target);
284         if (OVS_UNLIKELY(!*nd_target)) {
285             return false;
286         }
287
288         while (*sizep >= 8) {
289             /* The minimum size of an option is 8 bytes, which also is
290              * the size of Ethernet link-layer options. */
291             const struct nd_opt_hdr *nd_opt = *datap;
292             int opt_len = nd_opt->nd_opt_len * 8;
293
294             if (!opt_len || opt_len > *sizep) {
295                 goto invalid;
296             }
297
298             /* Store the link layer address if the appropriate option is
299              * provided.  It is considered an error if the same link
300              * layer option is specified twice. */
301             if (nd_opt->nd_opt_type == ND_OPT_SOURCE_LINKADDR
302                     && opt_len == 8) {
303                 if (OVS_LIKELY(eth_addr_is_zero(arp_buf[0]))) {
304                     memcpy(arp_buf[0], nd_opt + 1, ETH_ADDR_LEN);
305                 } else {
306                     goto invalid;
307                 }
308             } else if (nd_opt->nd_opt_type == ND_OPT_TARGET_LINKADDR
309                     && opt_len == 8) {
310                 if (OVS_LIKELY(eth_addr_is_zero(arp_buf[1]))) {
311                     memcpy(arp_buf[1], nd_opt + 1, ETH_ADDR_LEN);
312                 } else {
313                     goto invalid;
314                 }
315             }
316
317             if (OVS_UNLIKELY(!data_try_pull(datap, sizep, opt_len))) {
318                 goto invalid;
319             }
320         }
321     }
322
323     return true;
324
325 invalid:
326     return false;
327 }
328
329 /* Initializes 'flow' members from 'packet' and 'md'
330  *
331  * Initializes 'packet' header l2 pointer to the start of the Ethernet
332  * header, and the layer offsets as follows:
333  *
334  *    - packet->l2_5_ofs to the start of the MPLS shim header, or UINT16_MAX
335  *      when there is no MPLS shim header.
336  *
337  *    - packet->l3_ofs to just past the Ethernet header, or just past the
338  *      vlan_header if one is present, to the first byte of the payload of the
339  *      Ethernet frame.  UINT16_MAX if the frame is too short to contain an
340  *      Ethernet header.
341  *
342  *    - packet->l4_ofs to just past the IPv4 header, if one is present and
343  *      has at least the content used for the fields of interest for the flow,
344  *      otherwise UINT16_MAX.
345  */
346 void
347 flow_extract(struct ofpbuf *packet, const struct pkt_metadata *md,
348              struct flow *flow)
349 {
350     struct {
351         struct miniflow mf;
352         uint32_t buf[FLOW_U32S];
353     } m;
354
355     COVERAGE_INC(flow_extract);
356
357     miniflow_initialize(&m.mf, m.buf);
358     miniflow_extract(packet, md, &m.mf);
359     miniflow_expand(&m.mf, flow);
360 }
361
362 /* Caller is responsible for initializing 'dst' with enough storage for
363  * FLOW_U32S * 4 bytes. */
364 void
365 miniflow_extract(struct ofpbuf *packet, const struct pkt_metadata *md,
366                  struct miniflow *dst)
367 {
368     void *data = ofpbuf_data(packet);
369     size_t size = ofpbuf_size(packet);
370     uint32_t *values = miniflow_values(dst);
371     struct mf_ctx mf = { 0, values, values + FLOW_U32S };
372     char *l2;
373     ovs_be16 dl_type;
374     uint8_t nw_frag, nw_tos, nw_ttl, nw_proto;
375
376     /* Metadata. */
377     if (md) {
378         if (md->tunnel.ip_dst) {
379             miniflow_push_words(mf, tunnel, &md->tunnel,
380                                 sizeof md->tunnel / 4);
381         }
382         miniflow_push_uint32_check(mf, skb_priority, md->skb_priority);
383         miniflow_push_uint32_check(mf, pkt_mark, md->pkt_mark);
384         miniflow_push_uint32_check(mf, recirc_id, md->recirc_id);
385         miniflow_push_uint32(mf, in_port, odp_to_u32(md->in_port.odp_port));
386     }
387
388     /* Initialize packet's layer pointer and offsets. */
389     l2 = data;
390     ofpbuf_set_frame(packet, data);
391
392     /* Must have full Ethernet header to proceed. */
393     if (OVS_UNLIKELY(size < sizeof(struct eth_header))) {
394         goto out;
395     } else {
396         ovs_be16 vlan_tci;
397
398         /* Link layer. */
399         BUILD_ASSERT(offsetof(struct flow, dl_dst) + 6
400                      == offsetof(struct flow, dl_src));
401         miniflow_push_words(mf, dl_dst, data, ETH_ADDR_LEN * 2 / 4);
402         /* dl_type, vlan_tci. */
403         vlan_tci = parse_vlan(&data, &size);
404         dl_type = parse_ethertype(&data, &size);
405         miniflow_push_be16(mf, dl_type, dl_type);
406         miniflow_push_be16(mf, vlan_tci, vlan_tci);
407     }
408
409     /* Parse mpls. */
410     if (OVS_UNLIKELY(eth_type_mpls(dl_type))) {
411         int count;
412         const void *mpls = data;
413
414         packet->l2_5_ofs = (char *)data - l2;
415         count = parse_mpls(&data, &size);
416         miniflow_push_words(mf, mpls_lse, mpls, count);
417     }
418
419     /* Network layer. */
420     packet->l3_ofs = (char *)data - l2;
421
422     nw_frag = 0;
423     if (OVS_LIKELY(dl_type == htons(ETH_TYPE_IP))) {
424         const struct ip_header *nh = data;
425         int ip_len;
426         uint16_t tot_len;
427
428         if (OVS_UNLIKELY(size < IP_HEADER_LEN)) {
429             goto out;
430         }
431         ip_len = IP_IHL(nh->ip_ihl_ver) * 4;
432
433         if (OVS_UNLIKELY(ip_len < IP_HEADER_LEN)) {
434             goto out;
435         }
436         if (OVS_UNLIKELY(size < ip_len)) {
437             goto out;
438         }
439         tot_len = ntohs(nh->ip_tot_len);
440         if (OVS_UNLIKELY(tot_len > size)) {
441             goto out;
442         }
443         if (OVS_UNLIKELY(size - tot_len > UINT8_MAX)) {
444             goto out;
445         }
446         ofpbuf_set_l2_pad_size(packet, size - tot_len);
447         size = tot_len;   /* Never pull padding. */
448
449         /* Push both source and destination address at once. */
450         miniflow_push_words(mf, nw_src, &nh->ip_src, 2);
451
452         nw_tos = nh->ip_tos;
453         nw_ttl = nh->ip_ttl;
454         nw_proto = nh->ip_proto;
455         if (OVS_UNLIKELY(IP_IS_FRAGMENT(nh->ip_frag_off))) {
456             nw_frag = FLOW_NW_FRAG_ANY;
457             if (nh->ip_frag_off & htons(IP_FRAG_OFF_MASK)) {
458                 nw_frag |= FLOW_NW_FRAG_LATER;
459             }
460         }
461         data_pull(&data, &size, ip_len);
462     } else if (dl_type == htons(ETH_TYPE_IPV6)) {
463         const struct ovs_16aligned_ip6_hdr *nh;
464         ovs_be32 tc_flow;
465         uint16_t plen;
466
467         if (OVS_UNLIKELY(size < sizeof *nh)) {
468             goto out;
469         }
470         nh = data_pull(&data, &size, sizeof *nh);
471
472         plen = ntohs(nh->ip6_plen);
473         if (OVS_UNLIKELY(plen > size)) {
474             goto out;
475         }
476         /* Jumbo Payload option not supported yet. */
477         if (OVS_UNLIKELY(size - plen > UINT8_MAX)) {
478             goto out;
479         }
480         ofpbuf_set_l2_pad_size(packet, size - plen);
481         size = plen;   /* Never pull padding. */
482
483         miniflow_push_words(mf, ipv6_src, &nh->ip6_src,
484                             sizeof nh->ip6_src / 4);
485         miniflow_push_words(mf, ipv6_dst, &nh->ip6_dst,
486                             sizeof nh->ip6_dst / 4);
487
488         tc_flow = get_16aligned_be32(&nh->ip6_flow);
489         {
490             ovs_be32 label = tc_flow & htonl(IPV6_LABEL_MASK);
491             miniflow_push_be32_check(mf, ipv6_label, label);
492         }
493
494         nw_tos = ntohl(tc_flow) >> 20;
495         nw_ttl = nh->ip6_hlim;
496         nw_proto = nh->ip6_nxt;
497
498         while (1) {
499             if (OVS_LIKELY((nw_proto != IPPROTO_HOPOPTS)
500                            && (nw_proto != IPPROTO_ROUTING)
501                            && (nw_proto != IPPROTO_DSTOPTS)
502                            && (nw_proto != IPPROTO_AH)
503                            && (nw_proto != IPPROTO_FRAGMENT))) {
504                 /* It's either a terminal header (e.g., TCP, UDP) or one we
505                  * don't understand.  In either case, we're done with the
506                  * packet, so use it to fill in 'nw_proto'. */
507                 break;
508             }
509
510             /* We only verify that at least 8 bytes of the next header are
511              * available, but many of these headers are longer.  Ensure that
512              * accesses within the extension header are within those first 8
513              * bytes. All extension headers are required to be at least 8
514              * bytes. */
515             if (OVS_UNLIKELY(size < 8)) {
516                 goto out;
517             }
518
519             if ((nw_proto == IPPROTO_HOPOPTS)
520                 || (nw_proto == IPPROTO_ROUTING)
521                 || (nw_proto == IPPROTO_DSTOPTS)) {
522                 /* These headers, while different, have the fields we care
523                  * about in the same location and with the same
524                  * interpretation. */
525                 const struct ip6_ext *ext_hdr = data;
526                 nw_proto = ext_hdr->ip6e_nxt;
527                 if (OVS_UNLIKELY(!data_try_pull(&data, &size,
528                                                 (ext_hdr->ip6e_len + 1) * 8))) {
529                     goto out;
530                 }
531             } else if (nw_proto == IPPROTO_AH) {
532                 /* A standard AH definition isn't available, but the fields
533                  * we care about are in the same location as the generic
534                  * option header--only the header length is calculated
535                  * differently. */
536                 const struct ip6_ext *ext_hdr = data;
537                 nw_proto = ext_hdr->ip6e_nxt;
538                 if (OVS_UNLIKELY(!data_try_pull(&data, &size,
539                                                 (ext_hdr->ip6e_len + 2) * 4))) {
540                     goto out;
541                 }
542             } else if (nw_proto == IPPROTO_FRAGMENT) {
543                 const struct ovs_16aligned_ip6_frag *frag_hdr = data;
544
545                 nw_proto = frag_hdr->ip6f_nxt;
546                 if (!data_try_pull(&data, &size, sizeof *frag_hdr)) {
547                     goto out;
548                 }
549
550                 /* We only process the first fragment. */
551                 if (frag_hdr->ip6f_offlg != htons(0)) {
552                     nw_frag = FLOW_NW_FRAG_ANY;
553                     if ((frag_hdr->ip6f_offlg & IP6F_OFF_MASK) != htons(0)) {
554                         nw_frag |= FLOW_NW_FRAG_LATER;
555                         nw_proto = IPPROTO_FRAGMENT;
556                         break;
557                     }
558                 }
559             }
560         }
561     } else {
562         if (dl_type == htons(ETH_TYPE_ARP) ||
563             dl_type == htons(ETH_TYPE_RARP)) {
564             uint8_t arp_buf[2][ETH_ADDR_LEN];
565             const struct arp_eth_header *arp = (const struct arp_eth_header *)
566                 data_try_pull(&data, &size, ARP_ETH_HEADER_LEN);
567
568             if (OVS_LIKELY(arp) && OVS_LIKELY(arp->ar_hrd == htons(1))
569                 && OVS_LIKELY(arp->ar_pro == htons(ETH_TYPE_IP))
570                 && OVS_LIKELY(arp->ar_hln == ETH_ADDR_LEN)
571                 && OVS_LIKELY(arp->ar_pln == 4)) {
572                 miniflow_push_words(mf, nw_src, &arp->ar_spa, 1);
573                 miniflow_push_words(mf, nw_dst, &arp->ar_tpa, 1);
574
575                 /* We only match on the lower 8 bits of the opcode. */
576                 if (OVS_LIKELY(ntohs(arp->ar_op) <= 0xff)) {
577                     miniflow_push_be32(mf, nw_frag, htonl(ntohs(arp->ar_op)));
578                 }
579
580                 /* Must be adjacent. */
581                 BUILD_ASSERT(offsetof(struct flow, arp_sha) + 6
582                              == offsetof(struct flow, arp_tha));
583
584                 memcpy(arp_buf[0], arp->ar_sha, ETH_ADDR_LEN);
585                 memcpy(arp_buf[1], arp->ar_tha, ETH_ADDR_LEN);
586                 miniflow_push_words(mf, arp_sha, arp_buf,
587                                     ETH_ADDR_LEN * 2 / 4);
588             }
589         }
590         goto out;
591     }
592
593     packet->l4_ofs = (char *)data - l2;
594     miniflow_push_be32(mf, nw_frag,
595                        BYTES_TO_BE32(nw_frag, nw_tos, nw_ttl, nw_proto));
596
597     if (OVS_LIKELY(!(nw_frag & FLOW_NW_FRAG_LATER))) {
598         if (OVS_LIKELY(nw_proto == IPPROTO_TCP)) {
599             if (OVS_LIKELY(size >= TCP_HEADER_LEN)) {
600                 const struct tcp_header *tcp = data;
601
602                 miniflow_push_be32(mf, tcp_flags,
603                                    TCP_FLAGS_BE32(tcp->tcp_ctl));
604                 miniflow_push_words(mf, tp_src, &tcp->tcp_src, 1);
605             }
606         } else if (OVS_LIKELY(nw_proto == IPPROTO_UDP)) {
607             if (OVS_LIKELY(size >= UDP_HEADER_LEN)) {
608                 const struct udp_header *udp = data;
609
610                 miniflow_push_words(mf, tp_src, &udp->udp_src, 1);
611             }
612         } else if (OVS_LIKELY(nw_proto == IPPROTO_SCTP)) {
613             if (OVS_LIKELY(size >= SCTP_HEADER_LEN)) {
614                 const struct sctp_header *sctp = data;
615
616                 miniflow_push_words(mf, tp_src, &sctp->sctp_src, 1);
617             }
618         } else if (OVS_LIKELY(nw_proto == IPPROTO_ICMP)) {
619             if (OVS_LIKELY(size >= ICMP_HEADER_LEN)) {
620                 const struct icmp_header *icmp = data;
621
622                 miniflow_push_be16(mf, tp_src, htons(icmp->icmp_type));
623                 miniflow_push_be16(mf, tp_dst, htons(icmp->icmp_code));
624             }
625         } else if (OVS_LIKELY(nw_proto == IPPROTO_IGMP)) {
626             if (OVS_LIKELY(size >= IGMP_HEADER_LEN)) {
627                 const struct igmp_header *igmp = data;
628
629                 miniflow_push_be16(mf, tp_src, htons(igmp->igmp_type));
630                 miniflow_push_be16(mf, tp_dst, htons(igmp->igmp_code));
631                 miniflow_push_be32(mf, igmp_group_ip4,
632                                    get_16aligned_be32(&igmp->group));
633             }
634         } else if (OVS_LIKELY(nw_proto == IPPROTO_ICMPV6)) {
635             if (OVS_LIKELY(size >= sizeof(struct icmp6_hdr))) {
636                 const struct in6_addr *nd_target = NULL;
637                 uint8_t arp_buf[2][ETH_ADDR_LEN];
638                 const struct icmp6_hdr *icmp = data_pull(&data, &size,
639                                                          sizeof *icmp);
640                 memset(arp_buf, 0, sizeof arp_buf);
641                 if (OVS_LIKELY(parse_icmpv6(&data, &size, icmp, &nd_target,
642                                             arp_buf))) {
643                     miniflow_push_words(mf, arp_sha, arp_buf,
644                                              ETH_ADDR_LEN * 2 / 4);
645                     if (nd_target) {
646                         miniflow_push_words(mf, nd_target, nd_target,
647                                             sizeof *nd_target / 4);
648                     }
649                     miniflow_push_be16(mf, tp_src, htons(icmp->icmp6_type));
650                     miniflow_push_be16(mf, tp_dst, htons(icmp->icmp6_code));
651                 }
652             }
653         }
654     }
655     if (md) {
656         miniflow_push_uint32_check(mf, dp_hash, md->dp_hash);
657     }
658  out:
659     dst->map = mf.map;
660 }
661
662 /* For every bit of a field that is wildcarded in 'wildcards', sets the
663  * corresponding bit in 'flow' to zero. */
664 void
665 flow_zero_wildcards(struct flow *flow, const struct flow_wildcards *wildcards)
666 {
667     uint32_t *flow_u32 = (uint32_t *) flow;
668     const uint32_t *wc_u32 = (const uint32_t *) &wildcards->masks;
669     size_t i;
670
671     for (i = 0; i < FLOW_U32S; i++) {
672         flow_u32[i] &= wc_u32[i];
673     }
674 }
675
676 void
677 flow_unwildcard_tp_ports(const struct flow *flow, struct flow_wildcards *wc)
678 {
679     if (flow->nw_proto != IPPROTO_ICMP) {
680         memset(&wc->masks.tp_src, 0xff, sizeof wc->masks.tp_src);
681         memset(&wc->masks.tp_dst, 0xff, sizeof wc->masks.tp_dst);
682     } else {
683         wc->masks.tp_src = htons(0xff);
684         wc->masks.tp_dst = htons(0xff);
685     }
686 }
687
688 /* Initializes 'fmd' with the metadata found in 'flow'. */
689 void
690 flow_get_metadata(const struct flow *flow, struct flow_metadata *fmd)
691 {
692     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 28);
693
694     fmd->dp_hash = flow->dp_hash;
695     fmd->recirc_id = flow->recirc_id;
696     fmd->tun_id = flow->tunnel.tun_id;
697     fmd->tun_src = flow->tunnel.ip_src;
698     fmd->tun_dst = flow->tunnel.ip_dst;
699     fmd->metadata = flow->metadata;
700     memcpy(fmd->regs, flow->regs, sizeof fmd->regs);
701     fmd->pkt_mark = flow->pkt_mark;
702     fmd->in_port = flow->in_port.ofp_port;
703 }
704
705 char *
706 flow_to_string(const struct flow *flow)
707 {
708     struct ds ds = DS_EMPTY_INITIALIZER;
709     flow_format(&ds, flow);
710     return ds_cstr(&ds);
711 }
712
713 const char *
714 flow_tun_flag_to_string(uint32_t flags)
715 {
716     switch (flags) {
717     case FLOW_TNL_F_DONT_FRAGMENT:
718         return "df";
719     case FLOW_TNL_F_CSUM:
720         return "csum";
721     case FLOW_TNL_F_KEY:
722         return "key";
723     case FLOW_TNL_F_OAM:
724         return "oam";
725     default:
726         return NULL;
727     }
728 }
729
730 void
731 format_flags(struct ds *ds, const char *(*bit_to_string)(uint32_t),
732              uint32_t flags, char del)
733 {
734     uint32_t bad = 0;
735
736     if (!flags) {
737         return;
738     }
739     while (flags) {
740         uint32_t bit = rightmost_1bit(flags);
741         const char *s;
742
743         s = bit_to_string(bit);
744         if (s) {
745             ds_put_format(ds, "%s%c", s, del);
746         } else {
747             bad |= bit;
748         }
749
750         flags &= ~bit;
751     }
752
753     if (bad) {
754         ds_put_format(ds, "0x%"PRIx32"%c", bad, del);
755     }
756     ds_chomp(ds, del);
757 }
758
759 void
760 format_flags_masked(struct ds *ds, const char *name,
761                     const char *(*bit_to_string)(uint32_t), uint32_t flags,
762                     uint32_t mask)
763 {
764     if (name) {
765         ds_put_format(ds, "%s=", name);
766     }
767     while (mask) {
768         uint32_t bit = rightmost_1bit(mask);
769         const char *s = bit_to_string(bit);
770
771         ds_put_format(ds, "%s%s", (flags & bit) ? "+" : "-",
772                       s ? s : "[Unknown]");
773         mask &= ~bit;
774     }
775 }
776
777 void
778 flow_format(struct ds *ds, const struct flow *flow)
779 {
780     struct match match;
781     struct flow_wildcards *wc = &match.wc;
782
783     match_wc_init(&match, flow);
784
785     /* As this function is most often used for formatting a packet in a
786      * packet-in message, skip formatting the packet context fields that are
787      * all-zeroes (Openflow spec encourages leaving out all-zeroes context
788      * fields from the packet-in messages).  We make an exception with the
789      * 'in_port' field, which we always format, as packets usually have an
790      * in_port, and 0 is a port just like any other port. */
791     if (!flow->skb_priority) {
792         WC_UNMASK_FIELD(wc, skb_priority);
793     }
794     if (!flow->pkt_mark) {
795         WC_UNMASK_FIELD(wc, pkt_mark);
796     }
797     if (!flow->recirc_id) {
798         WC_UNMASK_FIELD(wc, recirc_id);
799     }
800     for (int i = 0; i < FLOW_N_REGS; i++) {
801         if (!flow->regs[i]) {
802             WC_UNMASK_FIELD(wc, regs[i]);
803         }
804     }
805     if (!flow->metadata) {
806         WC_UNMASK_FIELD(wc, metadata);
807     }
808
809     match_format(&match, ds, OFP_DEFAULT_PRIORITY);
810 }
811
812 void
813 flow_print(FILE *stream, const struct flow *flow)
814 {
815     char *s = flow_to_string(flow);
816     fputs(s, stream);
817     free(s);
818 }
819 \f
820 /* flow_wildcards functions. */
821
822 /* Initializes 'wc' as a set of wildcards that matches every packet. */
823 void
824 flow_wildcards_init_catchall(struct flow_wildcards *wc)
825 {
826     memset(&wc->masks, 0, sizeof wc->masks);
827 }
828
829 /* Converts a flow into flow wildcards.  It sets the wildcard masks based on
830  * the packet headers extracted to 'flow'.  It will not set the mask for fields
831  * that do not make sense for the packet type.  OpenFlow-only metadata is
832  * wildcarded, but other metadata is unconditionally exact-matched. */
833 void flow_wildcards_init_for_packet(struct flow_wildcards *wc,
834                                     const struct flow *flow)
835 {
836     memset(&wc->masks, 0x0, sizeof wc->masks);
837
838     /* Update this function whenever struct flow changes. */
839     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 28);
840
841     if (flow->tunnel.ip_dst) {
842         if (flow->tunnel.flags & FLOW_TNL_F_KEY) {
843             WC_MASK_FIELD(wc, tunnel.tun_id);
844         }
845         WC_MASK_FIELD(wc, tunnel.ip_src);
846         WC_MASK_FIELD(wc, tunnel.ip_dst);
847         WC_MASK_FIELD(wc, tunnel.flags);
848         WC_MASK_FIELD(wc, tunnel.ip_tos);
849         WC_MASK_FIELD(wc, tunnel.ip_ttl);
850         WC_MASK_FIELD(wc, tunnel.tp_src);
851         WC_MASK_FIELD(wc, tunnel.tp_dst);
852     } else if (flow->tunnel.tun_id) {
853         WC_MASK_FIELD(wc, tunnel.tun_id);
854     }
855
856     /* metadata and regs wildcarded. */
857
858     WC_MASK_FIELD(wc, skb_priority);
859     WC_MASK_FIELD(wc, pkt_mark);
860     WC_MASK_FIELD(wc, recirc_id);
861     WC_MASK_FIELD(wc, dp_hash);
862     WC_MASK_FIELD(wc, in_port);
863
864     /* actset_output wildcarded. */
865
866     WC_MASK_FIELD(wc, dl_dst);
867     WC_MASK_FIELD(wc, dl_src);
868     WC_MASK_FIELD(wc, dl_type);
869     WC_MASK_FIELD(wc, vlan_tci);
870
871     if (flow->dl_type == htons(ETH_TYPE_IP)) {
872         WC_MASK_FIELD(wc, nw_src);
873         WC_MASK_FIELD(wc, nw_dst);
874     } else if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
875         WC_MASK_FIELD(wc, ipv6_src);
876         WC_MASK_FIELD(wc, ipv6_dst);
877         WC_MASK_FIELD(wc, ipv6_label);
878     } else if (flow->dl_type == htons(ETH_TYPE_ARP) ||
879                flow->dl_type == htons(ETH_TYPE_RARP)) {
880         WC_MASK_FIELD(wc, nw_src);
881         WC_MASK_FIELD(wc, nw_dst);
882         WC_MASK_FIELD(wc, nw_proto);
883         WC_MASK_FIELD(wc, arp_sha);
884         WC_MASK_FIELD(wc, arp_tha);
885         return;
886     } else if (eth_type_mpls(flow->dl_type)) {
887         for (int i = 0; i < FLOW_MAX_MPLS_LABELS; i++) {
888             WC_MASK_FIELD(wc, mpls_lse[i]);
889             if (flow->mpls_lse[i] & htonl(MPLS_BOS_MASK)) {
890                 break;
891             }
892         }
893         return;
894     } else {
895         return; /* Unknown ethertype. */
896     }
897
898     /* IPv4 or IPv6. */
899     WC_MASK_FIELD(wc, nw_frag);
900     WC_MASK_FIELD(wc, nw_tos);
901     WC_MASK_FIELD(wc, nw_ttl);
902     WC_MASK_FIELD(wc, nw_proto);
903
904     /* No transport layer header in later fragments. */
905     if (!(flow->nw_frag & FLOW_NW_FRAG_LATER) &&
906         (flow->nw_proto == IPPROTO_ICMP ||
907          flow->nw_proto == IPPROTO_ICMPV6 ||
908          flow->nw_proto == IPPROTO_TCP ||
909          flow->nw_proto == IPPROTO_UDP ||
910          flow->nw_proto == IPPROTO_SCTP ||
911          flow->nw_proto == IPPROTO_IGMP)) {
912         WC_MASK_FIELD(wc, tp_src);
913         WC_MASK_FIELD(wc, tp_dst);
914
915         if (flow->nw_proto == IPPROTO_TCP) {
916             WC_MASK_FIELD(wc, tcp_flags);
917         } else if (flow->nw_proto == IPPROTO_ICMPV6) {
918             WC_MASK_FIELD(wc, arp_sha);
919             WC_MASK_FIELD(wc, arp_tha);
920             WC_MASK_FIELD(wc, nd_target);
921         } else if (flow->nw_proto == IPPROTO_IGMP) {
922             WC_MASK_FIELD(wc, igmp_group_ip4);
923         }
924     }
925 }
926
927 /* Return a map of possible fields for a packet of the same type as 'flow'.
928  * Including extra bits in the returned mask is not wrong, it is just less
929  * optimal.
930  *
931  * This is a less precise version of flow_wildcards_init_for_packet() above. */
932 uint64_t
933 flow_wc_map(const struct flow *flow)
934 {
935     /* Update this function whenever struct flow changes. */
936     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 28);
937
938     uint64_t map = (flow->tunnel.ip_dst) ? MINIFLOW_MAP(tunnel) : 0;
939
940     /* Metadata fields that can appear on packet input. */
941     map |= MINIFLOW_MAP(skb_priority) | MINIFLOW_MAP(pkt_mark)
942         | MINIFLOW_MAP(recirc_id) | MINIFLOW_MAP(dp_hash)
943         | MINIFLOW_MAP(in_port)
944         | MINIFLOW_MAP(dl_dst) | MINIFLOW_MAP(dl_src)
945         | MINIFLOW_MAP(dl_type) | MINIFLOW_MAP(vlan_tci);
946
947     /* Ethertype-dependent fields. */
948     if (OVS_LIKELY(flow->dl_type == htons(ETH_TYPE_IP))) {
949         map |= MINIFLOW_MAP(nw_src) | MINIFLOW_MAP(nw_dst)
950             | MINIFLOW_MAP(nw_proto) | MINIFLOW_MAP(nw_frag)
951             | MINIFLOW_MAP(nw_tos) | MINIFLOW_MAP(nw_ttl);
952         if (OVS_UNLIKELY(flow->nw_proto == IPPROTO_IGMP)) {
953             map |= MINIFLOW_MAP(igmp_group_ip4);
954         } else {
955             map |= MINIFLOW_MAP(tcp_flags)
956                 | MINIFLOW_MAP(tp_src) | MINIFLOW_MAP(tp_dst);
957         }
958     } else if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
959         map |= MINIFLOW_MAP(ipv6_src) | MINIFLOW_MAP(ipv6_dst)
960             | MINIFLOW_MAP(ipv6_label)
961             | MINIFLOW_MAP(nw_proto) | MINIFLOW_MAP(nw_frag)
962             | MINIFLOW_MAP(nw_tos) | MINIFLOW_MAP(nw_ttl);
963         if (OVS_UNLIKELY(flow->nw_proto == IPPROTO_ICMPV6)) {
964             map |= MINIFLOW_MAP(nd_target)
965                 | MINIFLOW_MAP(arp_sha) | MINIFLOW_MAP(arp_tha);
966         } else {
967             map |= MINIFLOW_MAP(tcp_flags)
968                 | MINIFLOW_MAP(tp_src) | MINIFLOW_MAP(tp_dst);
969         }
970     } else if (eth_type_mpls(flow->dl_type)) {
971         map |= MINIFLOW_MAP(mpls_lse);
972     } else if (flow->dl_type == htons(ETH_TYPE_ARP) ||
973                flow->dl_type == htons(ETH_TYPE_RARP)) {
974         map |= MINIFLOW_MAP(nw_src) | MINIFLOW_MAP(nw_dst)
975             | MINIFLOW_MAP(nw_proto)
976             | MINIFLOW_MAP(arp_sha) | MINIFLOW_MAP(arp_tha);
977     }
978
979     return map;
980 }
981
982 /* Clear the metadata and register wildcard masks. They are not packet
983  * header fields. */
984 void
985 flow_wildcards_clear_non_packet_fields(struct flow_wildcards *wc)
986 {
987     /* Update this function whenever struct flow changes. */
988     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 28);
989
990     memset(&wc->masks.metadata, 0, sizeof wc->masks.metadata);
991     memset(&wc->masks.regs, 0, sizeof wc->masks.regs);
992     wc->masks.actset_output = 0;
993 }
994
995 /* Returns true if 'wc' matches every packet, false if 'wc' fixes any bits or
996  * fields. */
997 bool
998 flow_wildcards_is_catchall(const struct flow_wildcards *wc)
999 {
1000     const uint32_t *wc_u32 = (const uint32_t *) &wc->masks;
1001     size_t i;
1002
1003     for (i = 0; i < FLOW_U32S; i++) {
1004         if (wc_u32[i]) {
1005             return false;
1006         }
1007     }
1008     return true;
1009 }
1010
1011 /* Sets 'dst' as the bitwise AND of wildcards in 'src1' and 'src2'.
1012  * That is, a bit or a field is wildcarded in 'dst' if it is wildcarded
1013  * in 'src1' or 'src2' or both.  */
1014 void
1015 flow_wildcards_and(struct flow_wildcards *dst,
1016                    const struct flow_wildcards *src1,
1017                    const struct flow_wildcards *src2)
1018 {
1019     uint32_t *dst_u32 = (uint32_t *) &dst->masks;
1020     const uint32_t *src1_u32 = (const uint32_t *) &src1->masks;
1021     const uint32_t *src2_u32 = (const uint32_t *) &src2->masks;
1022     size_t i;
1023
1024     for (i = 0; i < FLOW_U32S; i++) {
1025         dst_u32[i] = src1_u32[i] & src2_u32[i];
1026     }
1027 }
1028
1029 /* Sets 'dst' as the bitwise OR of wildcards in 'src1' and 'src2'.  That
1030  * is, a bit or a field is wildcarded in 'dst' if it is neither
1031  * wildcarded in 'src1' nor 'src2'. */
1032 void
1033 flow_wildcards_or(struct flow_wildcards *dst,
1034                   const struct flow_wildcards *src1,
1035                   const struct flow_wildcards *src2)
1036 {
1037     uint32_t *dst_u32 = (uint32_t *) &dst->masks;
1038     const uint32_t *src1_u32 = (const uint32_t *) &src1->masks;
1039     const uint32_t *src2_u32 = (const uint32_t *) &src2->masks;
1040     size_t i;
1041
1042     for (i = 0; i < FLOW_U32S; i++) {
1043         dst_u32[i] = src1_u32[i] | src2_u32[i];
1044     }
1045 }
1046
1047 /* Returns a hash of the wildcards in 'wc'. */
1048 uint32_t
1049 flow_wildcards_hash(const struct flow_wildcards *wc, uint32_t basis)
1050 {
1051     return flow_hash(&wc->masks, basis);
1052 }
1053
1054 /* Returns true if 'a' and 'b' represent the same wildcards, false if they are
1055  * different. */
1056 bool
1057 flow_wildcards_equal(const struct flow_wildcards *a,
1058                      const struct flow_wildcards *b)
1059 {
1060     return flow_equal(&a->masks, &b->masks);
1061 }
1062
1063 /* Returns true if at least one bit or field is wildcarded in 'a' but not in
1064  * 'b', false otherwise. */
1065 bool
1066 flow_wildcards_has_extra(const struct flow_wildcards *a,
1067                          const struct flow_wildcards *b)
1068 {
1069     const uint32_t *a_u32 = (const uint32_t *) &a->masks;
1070     const uint32_t *b_u32 = (const uint32_t *) &b->masks;
1071     size_t i;
1072
1073     for (i = 0; i < FLOW_U32S; i++) {
1074         if ((a_u32[i] & b_u32[i]) != b_u32[i]) {
1075             return true;
1076         }
1077     }
1078     return false;
1079 }
1080
1081 /* Returns true if 'a' and 'b' are equal, except that 0-bits (wildcarded bits)
1082  * in 'wc' do not need to be equal in 'a' and 'b'. */
1083 bool
1084 flow_equal_except(const struct flow *a, const struct flow *b,
1085                   const struct flow_wildcards *wc)
1086 {
1087     const uint32_t *a_u32 = (const uint32_t *) a;
1088     const uint32_t *b_u32 = (const uint32_t *) b;
1089     const uint32_t *wc_u32 = (const uint32_t *) &wc->masks;
1090     size_t i;
1091
1092     for (i = 0; i < FLOW_U32S; i++) {
1093         if ((a_u32[i] ^ b_u32[i]) & wc_u32[i]) {
1094             return false;
1095         }
1096     }
1097     return true;
1098 }
1099
1100 /* Sets the wildcard mask for register 'idx' in 'wc' to 'mask'.
1101  * (A 0-bit indicates a wildcard bit.) */
1102 void
1103 flow_wildcards_set_reg_mask(struct flow_wildcards *wc, int idx, uint32_t mask)
1104 {
1105     wc->masks.regs[idx] = mask;
1106 }
1107
1108 /* Sets the wildcard mask for register 'idx' in 'wc' to 'mask'.
1109  * (A 0-bit indicates a wildcard bit.) */
1110 void
1111 flow_wildcards_set_xreg_mask(struct flow_wildcards *wc, int idx, uint64_t mask)
1112 {
1113     flow_set_xreg(&wc->masks, idx, mask);
1114 }
1115
1116 /* Calculates the 5-tuple hash from the given miniflow.
1117  * This returns the same value as flow_hash_5tuple for the corresponding
1118  * flow. */
1119 uint32_t
1120 miniflow_hash_5tuple(const struct miniflow *flow, uint32_t basis)
1121 {
1122     uint32_t hash = basis;
1123
1124     if (flow) {
1125         ovs_be16 dl_type = MINIFLOW_GET_BE16(flow, dl_type);
1126
1127         hash = hash_add(hash, MINIFLOW_GET_U8(flow, nw_proto));
1128
1129         /* Separate loops for better optimization. */
1130         if (dl_type == htons(ETH_TYPE_IPV6)) {
1131             uint64_t map = MINIFLOW_MAP(ipv6_src) | MINIFLOW_MAP(ipv6_dst)
1132                 | MINIFLOW_MAP(tp_src); /* Covers both ports */
1133             uint32_t value;
1134
1135             MINIFLOW_FOR_EACH_IN_MAP(value, flow, map) {
1136                 hash = hash_add(hash, value);
1137             }
1138         } else {
1139             uint64_t map = MINIFLOW_MAP(nw_src) | MINIFLOW_MAP(nw_dst)
1140                 | MINIFLOW_MAP(tp_src); /* Covers both ports */
1141             uint32_t value;
1142
1143             MINIFLOW_FOR_EACH_IN_MAP(value, flow, map) {
1144                 hash = hash_add(hash, value);
1145             }
1146         }
1147         hash = hash_finish(hash, 42); /* Arbitrary number. */
1148     }
1149     return hash;
1150 }
1151
1152 BUILD_ASSERT_DECL(offsetof(struct flow, tp_src) + 2
1153                   == offsetof(struct flow, tp_dst) &&
1154                   offsetof(struct flow, tp_src) / 4
1155                   == offsetof(struct flow, tp_dst) / 4);
1156 BUILD_ASSERT_DECL(offsetof(struct flow, ipv6_src) + 16
1157                   == offsetof(struct flow, ipv6_dst));
1158
1159 /* Calculates the 5-tuple hash from the given flow. */
1160 uint32_t
1161 flow_hash_5tuple(const struct flow *flow, uint32_t basis)
1162 {
1163     uint32_t hash = basis;
1164
1165     if (flow) {
1166         const uint32_t *flow_u32 = (const uint32_t *)flow;
1167
1168         hash = hash_add(hash, flow->nw_proto);
1169
1170         if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
1171             int ofs = offsetof(struct flow, ipv6_src) / 4;
1172             int end = ofs + 2 * sizeof flow->ipv6_src / 4;
1173
1174             while (ofs < end) {
1175                 hash = hash_add(hash, flow_u32[ofs++]);
1176             }
1177         } else {
1178             hash = hash_add(hash, (OVS_FORCE uint32_t) flow->nw_src);
1179             hash = hash_add(hash, (OVS_FORCE uint32_t) flow->nw_dst);
1180         }
1181         hash = hash_add(hash, flow_u32[offsetof(struct flow, tp_src) / 4]);
1182
1183         hash = hash_finish(hash, 42); /* Arbitrary number. */
1184     }
1185     return hash;
1186 }
1187
1188 /* Hashes 'flow' based on its L2 through L4 protocol information. */
1189 uint32_t
1190 flow_hash_symmetric_l4(const struct flow *flow, uint32_t basis)
1191 {
1192     struct {
1193         union {
1194             ovs_be32 ipv4_addr;
1195             struct in6_addr ipv6_addr;
1196         };
1197         ovs_be16 eth_type;
1198         ovs_be16 vlan_tci;
1199         ovs_be16 tp_port;
1200         uint8_t eth_addr[ETH_ADDR_LEN];
1201         uint8_t ip_proto;
1202     } fields;
1203
1204     int i;
1205
1206     memset(&fields, 0, sizeof fields);
1207     for (i = 0; i < ETH_ADDR_LEN; i++) {
1208         fields.eth_addr[i] = flow->dl_src[i] ^ flow->dl_dst[i];
1209     }
1210     fields.vlan_tci = flow->vlan_tci & htons(VLAN_VID_MASK);
1211     fields.eth_type = flow->dl_type;
1212
1213     /* UDP source and destination port are not taken into account because they
1214      * will not necessarily be symmetric in a bidirectional flow. */
1215     if (fields.eth_type == htons(ETH_TYPE_IP)) {
1216         fields.ipv4_addr = flow->nw_src ^ flow->nw_dst;
1217         fields.ip_proto = flow->nw_proto;
1218         if (fields.ip_proto == IPPROTO_TCP || fields.ip_proto == IPPROTO_SCTP) {
1219             fields.tp_port = flow->tp_src ^ flow->tp_dst;
1220         }
1221     } else if (fields.eth_type == htons(ETH_TYPE_IPV6)) {
1222         const uint8_t *a = &flow->ipv6_src.s6_addr[0];
1223         const uint8_t *b = &flow->ipv6_dst.s6_addr[0];
1224         uint8_t *ipv6_addr = &fields.ipv6_addr.s6_addr[0];
1225
1226         for (i=0; i<16; i++) {
1227             ipv6_addr[i] = a[i] ^ b[i];
1228         }
1229         fields.ip_proto = flow->nw_proto;
1230         if (fields.ip_proto == IPPROTO_TCP || fields.ip_proto == IPPROTO_SCTP) {
1231             fields.tp_port = flow->tp_src ^ flow->tp_dst;
1232         }
1233     }
1234     return jhash_bytes(&fields, sizeof fields, basis);
1235 }
1236
1237 /* Initialize a flow with random fields that matter for nx_hash_fields. */
1238 void
1239 flow_random_hash_fields(struct flow *flow)
1240 {
1241     uint16_t rnd = random_uint16();
1242
1243     /* Initialize to all zeros. */
1244     memset(flow, 0, sizeof *flow);
1245
1246     eth_addr_random(flow->dl_src);
1247     eth_addr_random(flow->dl_dst);
1248
1249     flow->vlan_tci = (OVS_FORCE ovs_be16) (random_uint16() & VLAN_VID_MASK);
1250
1251     /* Make most of the random flows IPv4, some IPv6, and rest random. */
1252     flow->dl_type = rnd < 0x8000 ? htons(ETH_TYPE_IP) :
1253         rnd < 0xc000 ? htons(ETH_TYPE_IPV6) : (OVS_FORCE ovs_be16)rnd;
1254
1255     if (dl_type_is_ip_any(flow->dl_type)) {
1256         if (flow->dl_type == htons(ETH_TYPE_IP)) {
1257             flow->nw_src = (OVS_FORCE ovs_be32)random_uint32();
1258             flow->nw_dst = (OVS_FORCE ovs_be32)random_uint32();
1259         } else {
1260             random_bytes(&flow->ipv6_src, sizeof flow->ipv6_src);
1261             random_bytes(&flow->ipv6_dst, sizeof flow->ipv6_dst);
1262         }
1263         /* Make most of IP flows TCP, some UDP or SCTP, and rest random. */
1264         rnd = random_uint16();
1265         flow->nw_proto = rnd < 0x8000 ? IPPROTO_TCP :
1266             rnd < 0xc000 ? IPPROTO_UDP :
1267             rnd < 0xd000 ? IPPROTO_SCTP : (uint8_t)rnd;
1268         if (flow->nw_proto == IPPROTO_TCP ||
1269             flow->nw_proto == IPPROTO_UDP ||
1270             flow->nw_proto == IPPROTO_SCTP) {
1271             flow->tp_src = (OVS_FORCE ovs_be16)random_uint16();
1272             flow->tp_dst = (OVS_FORCE ovs_be16)random_uint16();
1273         }
1274     }
1275 }
1276
1277 /* Masks the fields in 'wc' that are used by the flow hash 'fields'. */
1278 void
1279 flow_mask_hash_fields(const struct flow *flow, struct flow_wildcards *wc,
1280                       enum nx_hash_fields fields)
1281 {
1282     switch (fields) {
1283     case NX_HASH_FIELDS_ETH_SRC:
1284         memset(&wc->masks.dl_src, 0xff, sizeof wc->masks.dl_src);
1285         break;
1286
1287     case NX_HASH_FIELDS_SYMMETRIC_L4:
1288         memset(&wc->masks.dl_src, 0xff, sizeof wc->masks.dl_src);
1289         memset(&wc->masks.dl_dst, 0xff, sizeof wc->masks.dl_dst);
1290         if (flow->dl_type == htons(ETH_TYPE_IP)) {
1291             memset(&wc->masks.nw_src, 0xff, sizeof wc->masks.nw_src);
1292             memset(&wc->masks.nw_dst, 0xff, sizeof wc->masks.nw_dst);
1293         } else if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
1294             memset(&wc->masks.ipv6_src, 0xff, sizeof wc->masks.ipv6_src);
1295             memset(&wc->masks.ipv6_dst, 0xff, sizeof wc->masks.ipv6_dst);
1296         }
1297         if (is_ip_any(flow)) {
1298             memset(&wc->masks.nw_proto, 0xff, sizeof wc->masks.nw_proto);
1299             flow_unwildcard_tp_ports(flow, wc);
1300         }
1301         wc->masks.vlan_tci |= htons(VLAN_VID_MASK | VLAN_CFI);
1302         break;
1303
1304     default:
1305         OVS_NOT_REACHED();
1306     }
1307 }
1308
1309 /* Hashes the portions of 'flow' designated by 'fields'. */
1310 uint32_t
1311 flow_hash_fields(const struct flow *flow, enum nx_hash_fields fields,
1312                  uint16_t basis)
1313 {
1314     switch (fields) {
1315
1316     case NX_HASH_FIELDS_ETH_SRC:
1317         return jhash_bytes(flow->dl_src, sizeof flow->dl_src, basis);
1318
1319     case NX_HASH_FIELDS_SYMMETRIC_L4:
1320         return flow_hash_symmetric_l4(flow, basis);
1321     }
1322
1323     OVS_NOT_REACHED();
1324 }
1325
1326 /* Returns a string representation of 'fields'. */
1327 const char *
1328 flow_hash_fields_to_str(enum nx_hash_fields fields)
1329 {
1330     switch (fields) {
1331     case NX_HASH_FIELDS_ETH_SRC: return "eth_src";
1332     case NX_HASH_FIELDS_SYMMETRIC_L4: return "symmetric_l4";
1333     default: return "<unknown>";
1334     }
1335 }
1336
1337 /* Returns true if the value of 'fields' is supported. Otherwise false. */
1338 bool
1339 flow_hash_fields_valid(enum nx_hash_fields fields)
1340 {
1341     return fields == NX_HASH_FIELDS_ETH_SRC
1342         || fields == NX_HASH_FIELDS_SYMMETRIC_L4;
1343 }
1344
1345 /* Returns a hash value for the bits of 'flow' that are active based on
1346  * 'wc', given 'basis'. */
1347 uint32_t
1348 flow_hash_in_wildcards(const struct flow *flow,
1349                        const struct flow_wildcards *wc, uint32_t basis)
1350 {
1351     const uint32_t *wc_u32 = (const uint32_t *) &wc->masks;
1352     const uint32_t *flow_u32 = (const uint32_t *) flow;
1353     uint32_t hash;
1354     size_t i;
1355
1356     hash = basis;
1357     for (i = 0; i < FLOW_U32S; i++) {
1358         hash = hash_add(hash, flow_u32[i] & wc_u32[i]);
1359     }
1360     return hash_finish(hash, 4 * FLOW_U32S);
1361 }
1362
1363 /* Sets the VLAN VID that 'flow' matches to 'vid', which is interpreted as an
1364  * OpenFlow 1.0 "dl_vlan" value:
1365  *
1366  *      - If it is in the range 0...4095, 'flow->vlan_tci' is set to match
1367  *        that VLAN.  Any existing PCP match is unchanged (it becomes 0 if
1368  *        'flow' previously matched packets without a VLAN header).
1369  *
1370  *      - If it is OFP_VLAN_NONE, 'flow->vlan_tci' is set to match a packet
1371  *        without a VLAN tag.
1372  *
1373  *      - Other values of 'vid' should not be used. */
1374 void
1375 flow_set_dl_vlan(struct flow *flow, ovs_be16 vid)
1376 {
1377     if (vid == htons(OFP10_VLAN_NONE)) {
1378         flow->vlan_tci = htons(0);
1379     } else {
1380         vid &= htons(VLAN_VID_MASK);
1381         flow->vlan_tci &= ~htons(VLAN_VID_MASK);
1382         flow->vlan_tci |= htons(VLAN_CFI) | vid;
1383     }
1384 }
1385
1386 /* Sets the VLAN VID that 'flow' matches to 'vid', which is interpreted as an
1387  * OpenFlow 1.2 "vlan_vid" value, that is, the low 13 bits of 'vlan_tci' (VID
1388  * plus CFI). */
1389 void
1390 flow_set_vlan_vid(struct flow *flow, ovs_be16 vid)
1391 {
1392     ovs_be16 mask = htons(VLAN_VID_MASK | VLAN_CFI);
1393     flow->vlan_tci &= ~mask;
1394     flow->vlan_tci |= vid & mask;
1395 }
1396
1397 /* Sets the VLAN PCP that 'flow' matches to 'pcp', which should be in the
1398  * range 0...7.
1399  *
1400  * This function has no effect on the VLAN ID that 'flow' matches.
1401  *
1402  * After calling this function, 'flow' will not match packets without a VLAN
1403  * header. */
1404 void
1405 flow_set_vlan_pcp(struct flow *flow, uint8_t pcp)
1406 {
1407     pcp &= 0x07;
1408     flow->vlan_tci &= ~htons(VLAN_PCP_MASK);
1409     flow->vlan_tci |= htons((pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
1410 }
1411
1412 /* Returns the number of MPLS LSEs present in 'flow'
1413  *
1414  * Returns 0 if the 'dl_type' of 'flow' is not an MPLS ethernet type.
1415  * Otherwise traverses 'flow''s MPLS label stack stopping at the
1416  * first entry that has the BoS bit set. If no such entry exists then
1417  * the maximum number of LSEs that can be stored in 'flow' is returned.
1418  */
1419 int
1420 flow_count_mpls_labels(const struct flow *flow, struct flow_wildcards *wc)
1421 {
1422     /* dl_type is always masked. */
1423     if (eth_type_mpls(flow->dl_type)) {
1424         int i;
1425         int len = FLOW_MAX_MPLS_LABELS;
1426
1427         for (i = 0; i < len; i++) {
1428             if (wc) {
1429                 wc->masks.mpls_lse[i] |= htonl(MPLS_BOS_MASK);
1430             }
1431             if (flow->mpls_lse[i] & htonl(MPLS_BOS_MASK)) {
1432                 return i + 1;
1433             }
1434         }
1435
1436         return len;
1437     } else {
1438         return 0;
1439     }
1440 }
1441
1442 /* Returns the number consecutive of MPLS LSEs, starting at the
1443  * innermost LSE, that are common in 'a' and 'b'.
1444  *
1445  * 'an' must be flow_count_mpls_labels(a).
1446  * 'bn' must be flow_count_mpls_labels(b).
1447  */
1448 int
1449 flow_count_common_mpls_labels(const struct flow *a, int an,
1450                               const struct flow *b, int bn,
1451                               struct flow_wildcards *wc)
1452 {
1453     int min_n = MIN(an, bn);
1454     if (min_n == 0) {
1455         return 0;
1456     } else {
1457         int common_n = 0;
1458         int a_last = an - 1;
1459         int b_last = bn - 1;
1460         int i;
1461
1462         for (i = 0; i < min_n; i++) {
1463             if (wc) {
1464                 wc->masks.mpls_lse[a_last - i] = OVS_BE32_MAX;
1465                 wc->masks.mpls_lse[b_last - i] = OVS_BE32_MAX;
1466             }
1467             if (a->mpls_lse[a_last - i] != b->mpls_lse[b_last - i]) {
1468                 break;
1469             } else {
1470                 common_n++;
1471             }
1472         }
1473
1474         return common_n;
1475     }
1476 }
1477
1478 /* Adds a new outermost MPLS label to 'flow' and changes 'flow''s Ethernet type
1479  * to 'mpls_eth_type', which must be an MPLS Ethertype.
1480  *
1481  * If the new label is the first MPLS label in 'flow', it is generated as;
1482  *
1483  *     - label: 2, if 'flow' is IPv6, otherwise 0.
1484  *
1485  *     - TTL: IPv4 or IPv6 TTL, if present and nonzero, otherwise 64.
1486  *
1487  *     - TC: IPv4 or IPv6 TOS, if present, otherwise 0.
1488  *
1489  *     - BoS: 1.
1490  *
1491  * If the new label is the second or later label MPLS label in 'flow', it is
1492  * generated as;
1493  *
1494  *     - label: Copied from outer label.
1495  *
1496  *     - TTL: Copied from outer label.
1497  *
1498  *     - TC: Copied from outer label.
1499  *
1500  *     - BoS: 0.
1501  *
1502  * 'n' must be flow_count_mpls_labels(flow).  'n' must be less than
1503  * FLOW_MAX_MPLS_LABELS (because otherwise flow->mpls_lse[] would overflow).
1504  */
1505 void
1506 flow_push_mpls(struct flow *flow, int n, ovs_be16 mpls_eth_type,
1507                struct flow_wildcards *wc)
1508 {
1509     ovs_assert(eth_type_mpls(mpls_eth_type));
1510     ovs_assert(n < FLOW_MAX_MPLS_LABELS);
1511
1512     if (n) {
1513         int i;
1514
1515         if (wc) {
1516             memset(&wc->masks.mpls_lse, 0xff, sizeof *wc->masks.mpls_lse * n);
1517         }
1518         for (i = n; i >= 1; i--) {
1519             flow->mpls_lse[i] = flow->mpls_lse[i - 1];
1520         }
1521         flow->mpls_lse[0] = (flow->mpls_lse[1] & htonl(~MPLS_BOS_MASK));
1522     } else {
1523         int label = 0;          /* IPv4 Explicit Null. */
1524         int tc = 0;
1525         int ttl = 64;
1526
1527         if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
1528             label = 2;
1529         }
1530
1531         if (is_ip_any(flow)) {
1532             tc = (flow->nw_tos & IP_DSCP_MASK) >> 2;
1533             if (wc) {
1534                 wc->masks.nw_tos |= IP_DSCP_MASK;
1535                 wc->masks.nw_ttl = 0xff;
1536             }
1537
1538             if (flow->nw_ttl) {
1539                 ttl = flow->nw_ttl;
1540             }
1541         }
1542
1543         flow->mpls_lse[0] = set_mpls_lse_values(ttl, tc, 1, htonl(label));
1544
1545         /* Clear all L3 and L4 fields. */
1546         BUILD_ASSERT(FLOW_WC_SEQ == 28);
1547         memset((char *) flow + FLOW_SEGMENT_2_ENDS_AT, 0,
1548                sizeof(struct flow) - FLOW_SEGMENT_2_ENDS_AT);
1549     }
1550     flow->dl_type = mpls_eth_type;
1551 }
1552
1553 /* Tries to remove the outermost MPLS label from 'flow'.  Returns true if
1554  * successful, false otherwise.  On success, sets 'flow''s Ethernet type to
1555  * 'eth_type'.
1556  *
1557  * 'n' must be flow_count_mpls_labels(flow). */
1558 bool
1559 flow_pop_mpls(struct flow *flow, int n, ovs_be16 eth_type,
1560               struct flow_wildcards *wc)
1561 {
1562     int i;
1563
1564     if (n == 0) {
1565         /* Nothing to pop. */
1566         return false;
1567     } else if (n == FLOW_MAX_MPLS_LABELS) {
1568         if (wc) {
1569             wc->masks.mpls_lse[n - 1] |= htonl(MPLS_BOS_MASK);
1570         }
1571         if (!(flow->mpls_lse[n - 1] & htonl(MPLS_BOS_MASK))) {
1572             /* Can't pop because don't know what to fill in mpls_lse[n - 1]. */
1573             return false;
1574         }
1575     }
1576
1577     if (wc) {
1578         memset(&wc->masks.mpls_lse[1], 0xff,
1579                sizeof *wc->masks.mpls_lse * (n - 1));
1580     }
1581     for (i = 1; i < n; i++) {
1582         flow->mpls_lse[i - 1] = flow->mpls_lse[i];
1583     }
1584     flow->mpls_lse[n - 1] = 0;
1585     flow->dl_type = eth_type;
1586     return true;
1587 }
1588
1589 /* Sets the MPLS Label that 'flow' matches to 'label', which is interpreted
1590  * as an OpenFlow 1.1 "mpls_label" value. */
1591 void
1592 flow_set_mpls_label(struct flow *flow, int idx, ovs_be32 label)
1593 {
1594     set_mpls_lse_label(&flow->mpls_lse[idx], label);
1595 }
1596
1597 /* Sets the MPLS TTL that 'flow' matches to 'ttl', which should be in the
1598  * range 0...255. */
1599 void
1600 flow_set_mpls_ttl(struct flow *flow, int idx, uint8_t ttl)
1601 {
1602     set_mpls_lse_ttl(&flow->mpls_lse[idx], ttl);
1603 }
1604
1605 /* Sets the MPLS TC that 'flow' matches to 'tc', which should be in the
1606  * range 0...7. */
1607 void
1608 flow_set_mpls_tc(struct flow *flow, int idx, uint8_t tc)
1609 {
1610     set_mpls_lse_tc(&flow->mpls_lse[idx], tc);
1611 }
1612
1613 /* Sets the MPLS BOS bit that 'flow' matches to which should be 0 or 1. */
1614 void
1615 flow_set_mpls_bos(struct flow *flow, int idx, uint8_t bos)
1616 {
1617     set_mpls_lse_bos(&flow->mpls_lse[idx], bos);
1618 }
1619
1620 /* Sets the entire MPLS LSE. */
1621 void
1622 flow_set_mpls_lse(struct flow *flow, int idx, ovs_be32 lse)
1623 {
1624     flow->mpls_lse[idx] = lse;
1625 }
1626
1627 static size_t
1628 flow_compose_l4(struct ofpbuf *b, const struct flow *flow)
1629 {
1630     size_t l4_len = 0;
1631
1632     if (!(flow->nw_frag & FLOW_NW_FRAG_ANY)
1633         || !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
1634         if (flow->nw_proto == IPPROTO_TCP) {
1635             struct tcp_header *tcp;
1636
1637             l4_len = sizeof *tcp;
1638             tcp = ofpbuf_put_zeros(b, l4_len);
1639             tcp->tcp_src = flow->tp_src;
1640             tcp->tcp_dst = flow->tp_dst;
1641             tcp->tcp_ctl = TCP_CTL(ntohs(flow->tcp_flags), 5);
1642         } else if (flow->nw_proto == IPPROTO_UDP) {
1643             struct udp_header *udp;
1644
1645             l4_len = sizeof *udp;
1646             udp = ofpbuf_put_zeros(b, l4_len);
1647             udp->udp_src = flow->tp_src;
1648             udp->udp_dst = flow->tp_dst;
1649         } else if (flow->nw_proto == IPPROTO_SCTP) {
1650             struct sctp_header *sctp;
1651
1652             l4_len = sizeof *sctp;
1653             sctp = ofpbuf_put_zeros(b, l4_len);
1654             sctp->sctp_src = flow->tp_src;
1655             sctp->sctp_dst = flow->tp_dst;
1656         } else if (flow->nw_proto == IPPROTO_ICMP) {
1657             struct icmp_header *icmp;
1658
1659             l4_len = sizeof *icmp;
1660             icmp = ofpbuf_put_zeros(b, l4_len);
1661             icmp->icmp_type = ntohs(flow->tp_src);
1662             icmp->icmp_code = ntohs(flow->tp_dst);
1663             icmp->icmp_csum = csum(icmp, ICMP_HEADER_LEN);
1664         } else if (flow->nw_proto == IPPROTO_IGMP) {
1665             struct igmp_header *igmp;
1666
1667             l4_len = sizeof *igmp;
1668             igmp = ofpbuf_put_zeros(b, l4_len);
1669             igmp->igmp_type = ntohs(flow->tp_src);
1670             igmp->igmp_code = ntohs(flow->tp_dst);
1671             put_16aligned_be32(&igmp->group, flow->igmp_group_ip4);
1672             igmp->igmp_csum = csum(igmp, IGMP_HEADER_LEN);
1673         } else if (flow->nw_proto == IPPROTO_ICMPV6) {
1674             struct icmp6_hdr *icmp;
1675
1676             l4_len = sizeof *icmp;
1677             icmp = ofpbuf_put_zeros(b, l4_len);
1678             icmp->icmp6_type = ntohs(flow->tp_src);
1679             icmp->icmp6_code = ntohs(flow->tp_dst);
1680
1681             if (icmp->icmp6_code == 0 &&
1682                 (icmp->icmp6_type == ND_NEIGHBOR_SOLICIT ||
1683                  icmp->icmp6_type == ND_NEIGHBOR_ADVERT)) {
1684                 struct in6_addr *nd_target;
1685                 struct nd_opt_hdr *nd_opt;
1686
1687                 l4_len += sizeof *nd_target;
1688                 nd_target = ofpbuf_put_zeros(b, sizeof *nd_target);
1689                 *nd_target = flow->nd_target;
1690
1691                 if (!eth_addr_is_zero(flow->arp_sha)) {
1692                     l4_len += 8;
1693                     nd_opt = ofpbuf_put_zeros(b, 8);
1694                     nd_opt->nd_opt_len = 1;
1695                     nd_opt->nd_opt_type = ND_OPT_SOURCE_LINKADDR;
1696                     memcpy(nd_opt + 1, flow->arp_sha, ETH_ADDR_LEN);
1697                 }
1698                 if (!eth_addr_is_zero(flow->arp_tha)) {
1699                     l4_len += 8;
1700                     nd_opt = ofpbuf_put_zeros(b, 8);
1701                     nd_opt->nd_opt_len = 1;
1702                     nd_opt->nd_opt_type = ND_OPT_TARGET_LINKADDR;
1703                     memcpy(nd_opt + 1, flow->arp_tha, ETH_ADDR_LEN);
1704                 }
1705             }
1706             icmp->icmp6_cksum = (OVS_FORCE uint16_t)
1707                 csum(icmp, (char *)ofpbuf_tail(b) - (char *)icmp);
1708         }
1709     }
1710     return l4_len;
1711 }
1712
1713 /* Puts into 'b' a packet that flow_extract() would parse as having the given
1714  * 'flow'.
1715  *
1716  * (This is useful only for testing, obviously, and the packet isn't really
1717  * valid. It hasn't got some checksums filled in, for one, and lots of fields
1718  * are just zeroed.) */
1719 void
1720 flow_compose(struct ofpbuf *b, const struct flow *flow)
1721 {
1722     size_t l4_len;
1723
1724     /* eth_compose() sets l3 pointer and makes sure it is 32-bit aligned. */
1725     eth_compose(b, flow->dl_dst, flow->dl_src, ntohs(flow->dl_type), 0);
1726     if (flow->dl_type == htons(FLOW_DL_TYPE_NONE)) {
1727         struct eth_header *eth = ofpbuf_l2(b);
1728         eth->eth_type = htons(ofpbuf_size(b));
1729         return;
1730     }
1731
1732     if (flow->vlan_tci & htons(VLAN_CFI)) {
1733         eth_push_vlan(b, htons(ETH_TYPE_VLAN), flow->vlan_tci);
1734     }
1735
1736     if (flow->dl_type == htons(ETH_TYPE_IP)) {
1737         struct ip_header *ip;
1738
1739         ip = ofpbuf_put_zeros(b, sizeof *ip);
1740         ip->ip_ihl_ver = IP_IHL_VER(5, 4);
1741         ip->ip_tos = flow->nw_tos;
1742         ip->ip_ttl = flow->nw_ttl;
1743         ip->ip_proto = flow->nw_proto;
1744         put_16aligned_be32(&ip->ip_src, flow->nw_src);
1745         put_16aligned_be32(&ip->ip_dst, flow->nw_dst);
1746
1747         if (flow->nw_frag & FLOW_NW_FRAG_ANY) {
1748             ip->ip_frag_off |= htons(IP_MORE_FRAGMENTS);
1749             if (flow->nw_frag & FLOW_NW_FRAG_LATER) {
1750                 ip->ip_frag_off |= htons(100);
1751             }
1752         }
1753
1754         ofpbuf_set_l4(b, ofpbuf_tail(b));
1755
1756         l4_len = flow_compose_l4(b, flow);
1757
1758         ip = ofpbuf_l3(b);
1759         ip->ip_tot_len = htons(b->l4_ofs - b->l3_ofs + l4_len);
1760         ip->ip_csum = csum(ip, sizeof *ip);
1761     } else if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
1762         struct ovs_16aligned_ip6_hdr *nh;
1763
1764         nh = ofpbuf_put_zeros(b, sizeof *nh);
1765         put_16aligned_be32(&nh->ip6_flow, htonl(6 << 28) |
1766                            htonl(flow->nw_tos << 20) | flow->ipv6_label);
1767         nh->ip6_hlim = flow->nw_ttl;
1768         nh->ip6_nxt = flow->nw_proto;
1769
1770         memcpy(&nh->ip6_src, &flow->ipv6_src, sizeof(nh->ip6_src));
1771         memcpy(&nh->ip6_dst, &flow->ipv6_dst, sizeof(nh->ip6_dst));
1772
1773         ofpbuf_set_l4(b, ofpbuf_tail(b));
1774
1775         l4_len = flow_compose_l4(b, flow);
1776
1777         nh = ofpbuf_l3(b);
1778         nh->ip6_plen = htons(l4_len);
1779     } else if (flow->dl_type == htons(ETH_TYPE_ARP) ||
1780                flow->dl_type == htons(ETH_TYPE_RARP)) {
1781         struct arp_eth_header *arp;
1782
1783         arp = ofpbuf_put_zeros(b, sizeof *arp);
1784         ofpbuf_set_l3(b, arp);
1785         arp->ar_hrd = htons(1);
1786         arp->ar_pro = htons(ETH_TYPE_IP);
1787         arp->ar_hln = ETH_ADDR_LEN;
1788         arp->ar_pln = 4;
1789         arp->ar_op = htons(flow->nw_proto);
1790
1791         if (flow->nw_proto == ARP_OP_REQUEST ||
1792             flow->nw_proto == ARP_OP_REPLY) {
1793             put_16aligned_be32(&arp->ar_spa, flow->nw_src);
1794             put_16aligned_be32(&arp->ar_tpa, flow->nw_dst);
1795             memcpy(arp->ar_sha, flow->arp_sha, ETH_ADDR_LEN);
1796             memcpy(arp->ar_tha, flow->arp_tha, ETH_ADDR_LEN);
1797         }
1798     }
1799
1800     if (eth_type_mpls(flow->dl_type)) {
1801         int n;
1802
1803         b->l2_5_ofs = b->l3_ofs;
1804         for (n = 1; n < FLOW_MAX_MPLS_LABELS; n++) {
1805             if (flow->mpls_lse[n - 1] & htonl(MPLS_BOS_MASK)) {
1806                 break;
1807             }
1808         }
1809         while (n > 0) {
1810             push_mpls(b, flow->dl_type, flow->mpls_lse[--n]);
1811         }
1812     }
1813 }
1814 \f
1815 /* Compressed flow. */
1816
1817 static int
1818 miniflow_n_values(const struct miniflow *flow)
1819 {
1820     return count_1bits(flow->map);
1821 }
1822
1823 static uint32_t *
1824 miniflow_alloc_values(struct miniflow *flow, int n)
1825 {
1826     int size = MINIFLOW_VALUES_SIZE(n);
1827
1828     if (size <= sizeof flow->inline_values) {
1829         flow->values_inline = true;
1830         return flow->inline_values;
1831     } else {
1832         COVERAGE_INC(miniflow_malloc);
1833         flow->values_inline = false;
1834         flow->offline_values = xmalloc(size);
1835         return flow->offline_values;
1836     }
1837 }
1838
1839 /* Completes an initialization of 'dst' as a miniflow copy of 'src' begun by
1840  * the caller.  The caller must have already initialized 'dst->map' properly
1841  * to indicate the significant uint32_t elements of 'src'.  'n' must be the
1842  * number of 1-bits in 'dst->map'.
1843  *
1844  * Normally the significant elements are the ones that are non-zero.  However,
1845  * when a miniflow is initialized from a (mini)mask, the values can be zeroes,
1846  * so that the flow and mask always have the same maps.
1847  *
1848  * This function initializes values (either inline if possible or with
1849  * malloc() otherwise) and copies the uint32_t elements of 'src' indicated by
1850  * 'dst->map' into it. */
1851 static void
1852 miniflow_init__(struct miniflow *dst, const struct flow *src, int n)
1853 {
1854     const uint32_t *src_u32 = (const uint32_t *) src;
1855     uint32_t *dst_u32 = miniflow_alloc_values(dst, n);
1856     uint64_t map;
1857
1858     for (map = dst->map; map; map = zero_rightmost_1bit(map)) {
1859         *dst_u32++ = src_u32[raw_ctz(map)];
1860     }
1861 }
1862
1863 /* Initializes 'dst' as a copy of 'src'.  The caller must eventually free 'dst'
1864  * with miniflow_destroy().
1865  * Always allocates offline storage. */
1866 void
1867 miniflow_init(struct miniflow *dst, const struct flow *src)
1868 {
1869     const uint32_t *src_u32 = (const uint32_t *) src;
1870     unsigned int i;
1871     int n;
1872
1873     /* Initialize dst->map, counting the number of nonzero elements. */
1874     n = 0;
1875     dst->map = 0;
1876
1877     for (i = 0; i < FLOW_U32S; i++) {
1878         if (src_u32[i]) {
1879             dst->map |= UINT64_C(1) << i;
1880             n++;
1881         }
1882     }
1883
1884     miniflow_init__(dst, src, n);
1885 }
1886
1887 /* Initializes 'dst' as a copy of 'src', using 'mask->map' as 'dst''s map.  The
1888  * caller must eventually free 'dst' with miniflow_destroy(). */
1889 void
1890 miniflow_init_with_minimask(struct miniflow *dst, const struct flow *src,
1891                             const struct minimask *mask)
1892 {
1893     dst->map = mask->masks.map;
1894     miniflow_init__(dst, src, miniflow_n_values(dst));
1895 }
1896
1897 /* Initializes 'dst' as a copy of 'src'.  The caller must eventually free 'dst'
1898  * with miniflow_destroy(). */
1899 void
1900 miniflow_clone(struct miniflow *dst, const struct miniflow *src)
1901 {
1902     int size = MINIFLOW_VALUES_SIZE(miniflow_n_values(src));
1903     uint32_t *values;
1904
1905     dst->map = src->map;
1906     if (size <= sizeof dst->inline_values) {
1907         dst->values_inline = true;
1908         values = dst->inline_values;
1909     } else {
1910         dst->values_inline = false;
1911         COVERAGE_INC(miniflow_malloc);
1912         dst->offline_values = xmalloc(size);
1913         values = dst->offline_values;
1914     }
1915     memcpy(values, miniflow_get_values(src), size);
1916 }
1917
1918 /* Initializes 'dst' as a copy of 'src'.  The caller must have allocated
1919  * 'dst' to have inline space all data in 'src'. */
1920 void
1921 miniflow_clone_inline(struct miniflow *dst, const struct miniflow *src,
1922                       size_t n_values)
1923 {
1924     dst->values_inline = true;
1925     dst->map = src->map;
1926     memcpy(dst->inline_values, miniflow_get_values(src),
1927            MINIFLOW_VALUES_SIZE(n_values));
1928 }
1929
1930 /* Initializes 'dst' with the data in 'src', destroying 'src'.
1931  * The caller must eventually free 'dst' with miniflow_destroy().
1932  * 'dst' must be regularly sized miniflow, but 'src' can have
1933  * storage for more than the default MINI_N_INLINE inline
1934  * values. */
1935 void
1936 miniflow_move(struct miniflow *dst, struct miniflow *src)
1937 {
1938     int size = MINIFLOW_VALUES_SIZE(miniflow_n_values(src));
1939
1940     dst->map = src->map;
1941     if (size <= sizeof dst->inline_values) {
1942         dst->values_inline = true;
1943         memcpy(dst->inline_values, miniflow_get_values(src), size);
1944         miniflow_destroy(src);
1945     } else if (src->values_inline) {
1946         dst->values_inline = false;
1947         COVERAGE_INC(miniflow_malloc);
1948         dst->offline_values = xmalloc(size);
1949         memcpy(dst->offline_values, src->inline_values, size);
1950     } else {
1951         dst->values_inline = false;
1952         dst->offline_values = src->offline_values;
1953     }
1954 }
1955
1956 /* Frees any memory owned by 'flow'.  Does not free the storage in which 'flow'
1957  * itself resides; the caller is responsible for that. */
1958 void
1959 miniflow_destroy(struct miniflow *flow)
1960 {
1961     if (!flow->values_inline) {
1962         free(flow->offline_values);
1963     }
1964 }
1965
1966 /* Initializes 'dst' as a copy of 'src'. */
1967 void
1968 miniflow_expand(const struct miniflow *src, struct flow *dst)
1969 {
1970     memset(dst, 0, sizeof *dst);
1971     flow_union_with_miniflow(dst, src);
1972 }
1973
1974 /* Returns the uint32_t that would be at byte offset '4 * u32_ofs' if 'flow'
1975  * were expanded into a "struct flow". */
1976 static uint32_t
1977 miniflow_get(const struct miniflow *flow, unsigned int u32_ofs)
1978 {
1979     return flow->map & (UINT64_C(1) << u32_ofs)
1980         ? miniflow_get__(flow, u32_ofs) : 0;
1981 }
1982
1983 /* Returns true if 'a' and 'b' are the equal miniflow, false otherwise. */
1984 bool
1985 miniflow_equal(const struct miniflow *a, const struct miniflow *b)
1986 {
1987     const uint32_t *ap = miniflow_get_u32_values(a);
1988     const uint32_t *bp = miniflow_get_u32_values(b);
1989     const uint64_t a_map = a->map;
1990     const uint64_t b_map = b->map;
1991
1992     if (OVS_LIKELY(a_map == b_map)) {
1993         int count = miniflow_n_values(a);
1994
1995         return !memcmp(ap, bp, count * sizeof *ap);
1996     } else {
1997         uint64_t map;
1998
1999         for (map = a_map | b_map; map; map = zero_rightmost_1bit(map)) {
2000             uint64_t bit = rightmost_1bit(map);
2001             uint64_t a_value = a_map & bit ? *ap++ : 0;
2002             uint64_t b_value = b_map & bit ? *bp++ : 0;
2003
2004             if (a_value != b_value) {
2005                 return false;
2006             }
2007         }
2008     }
2009
2010     return true;
2011 }
2012
2013 /* Returns false if 'a' and 'b' differ at the places where there are 1-bits
2014  * in 'mask', true otherwise. */
2015 bool
2016 miniflow_equal_in_minimask(const struct miniflow *a, const struct miniflow *b,
2017                            const struct minimask *mask)
2018 {
2019     const uint32_t *p = miniflow_get_u32_values(&mask->masks);
2020     uint64_t map;
2021
2022     for (map = mask->masks.map; map; map = zero_rightmost_1bit(map)) {
2023         int ofs = raw_ctz(map);
2024
2025         if ((miniflow_get(a, ofs) ^ miniflow_get(b, ofs)) & *p++) {
2026             return false;
2027         }
2028     }
2029
2030     return true;
2031 }
2032
2033 /* Returns true if 'a' and 'b' are equal at the places where there are 1-bits
2034  * in 'mask', false if they differ. */
2035 bool
2036 miniflow_equal_flow_in_minimask(const struct miniflow *a, const struct flow *b,
2037                                 const struct minimask *mask)
2038 {
2039     const uint32_t *b_u32 = (const uint32_t *) b;
2040     const uint32_t *p = miniflow_get_u32_values(&mask->masks);
2041     uint64_t map;
2042
2043     for (map = mask->masks.map; map; map = zero_rightmost_1bit(map)) {
2044         int ofs = raw_ctz(map);
2045
2046         if ((miniflow_get(a, ofs) ^ b_u32[ofs]) & *p++) {
2047             return false;
2048         }
2049     }
2050
2051     return true;
2052 }
2053
2054 \f
2055 /* Initializes 'dst' as a copy of 'src'.  The caller must eventually free 'dst'
2056  * with minimask_destroy(). */
2057 void
2058 minimask_init(struct minimask *mask, const struct flow_wildcards *wc)
2059 {
2060     miniflow_init(&mask->masks, &wc->masks);
2061 }
2062
2063 /* Initializes 'dst' as a copy of 'src'.  The caller must eventually free 'dst'
2064  * with minimask_destroy(). */
2065 void
2066 minimask_clone(struct minimask *dst, const struct minimask *src)
2067 {
2068     miniflow_clone(&dst->masks, &src->masks);
2069 }
2070
2071 /* Initializes 'dst' with the data in 'src', destroying 'src'.
2072  * The caller must eventually free 'dst' with minimask_destroy(). */
2073 void
2074 minimask_move(struct minimask *dst, struct minimask *src)
2075 {
2076     miniflow_move(&dst->masks, &src->masks);
2077 }
2078
2079 /* Initializes 'dst_' as the bit-wise "and" of 'a_' and 'b_'.
2080  *
2081  * The caller must provide room for FLOW_U32S "uint32_t"s in 'storage', for use
2082  * by 'dst_'.  The caller must *not* free 'dst_' with minimask_destroy(). */
2083 void
2084 minimask_combine(struct minimask *dst_,
2085                  const struct minimask *a_, const struct minimask *b_,
2086                  uint32_t storage[FLOW_U32S])
2087 {
2088     struct miniflow *dst = &dst_->masks;
2089     uint32_t *dst_values = storage;
2090     const struct miniflow *a = &a_->masks;
2091     const struct miniflow *b = &b_->masks;
2092     uint64_t map;
2093     int n = 0;
2094
2095     dst->values_inline = false;
2096     dst->offline_values = storage;
2097
2098     dst->map = 0;
2099     for (map = a->map & b->map; map; map = zero_rightmost_1bit(map)) {
2100         int ofs = raw_ctz(map);
2101         /* Both 'a' and 'b' have non-zero data at 'idx'. */
2102         uint32_t mask = miniflow_get__(a, ofs) & miniflow_get__(b, ofs);
2103
2104         if (mask) {
2105             dst->map |= rightmost_1bit(map);
2106             dst_values[n++] = mask;
2107         }
2108     }
2109 }
2110
2111 /* Frees any memory owned by 'mask'.  Does not free the storage in which 'mask'
2112  * itself resides; the caller is responsible for that. */
2113 void
2114 minimask_destroy(struct minimask *mask)
2115 {
2116     miniflow_destroy(&mask->masks);
2117 }
2118
2119 /* Initializes 'dst' as a copy of 'src'. */
2120 void
2121 minimask_expand(const struct minimask *mask, struct flow_wildcards *wc)
2122 {
2123     miniflow_expand(&mask->masks, &wc->masks);
2124 }
2125
2126 /* Returns the uint32_t that would be at byte offset '4 * u32_ofs' if 'mask'
2127  * were expanded into a "struct flow_wildcards". */
2128 uint32_t
2129 minimask_get(const struct minimask *mask, unsigned int u32_ofs)
2130 {
2131     return miniflow_get(&mask->masks, u32_ofs);
2132 }
2133
2134 /* Returns true if 'a' and 'b' are the same flow mask, false otherwise.  */
2135 bool
2136 minimask_equal(const struct minimask *a, const struct minimask *b)
2137 {
2138     return miniflow_equal(&a->masks, &b->masks);
2139 }
2140
2141 /* Returns true if at least one bit matched by 'b' is wildcarded by 'a',
2142  * false otherwise. */
2143 bool
2144 minimask_has_extra(const struct minimask *a, const struct minimask *b)
2145 {
2146     const uint32_t *p = miniflow_get_u32_values(&b->masks);
2147     uint64_t map;
2148
2149     for (map = b->masks.map; map; map = zero_rightmost_1bit(map)) {
2150         uint32_t a_u32 = minimask_get(a, raw_ctz(map));
2151         uint32_t b_u32 = *p++;
2152
2153         if ((a_u32 & b_u32) != b_u32) {
2154             return true;
2155         }
2156     }
2157
2158     return false;
2159 }