lib/flow: Use BUILD_MESSAGE() to warn if BUILD_SEQ is not updated
[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, pad) &&
76                   offsetof(struct flow, tcp_flags) / 4
77                   == offsetof(struct flow, pad) / 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 != 27)
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
427         if (OVS_UNLIKELY(size < IP_HEADER_LEN)) {
428             goto out;
429         }
430         ip_len = IP_IHL(nh->ip_ihl_ver) * 4;
431
432         if (OVS_UNLIKELY(ip_len < IP_HEADER_LEN)) {
433             goto out;
434         }
435
436         /* Push both source and destination address at once. */
437         miniflow_push_words(mf, nw_src, &nh->ip_src, 2);
438
439         nw_tos = nh->ip_tos;
440         nw_ttl = nh->ip_ttl;
441         nw_proto = nh->ip_proto;
442         if (OVS_UNLIKELY(IP_IS_FRAGMENT(nh->ip_frag_off))) {
443             nw_frag = FLOW_NW_FRAG_ANY;
444             if (nh->ip_frag_off & htons(IP_FRAG_OFF_MASK)) {
445                 nw_frag |= FLOW_NW_FRAG_LATER;
446             }
447         }
448         if (OVS_UNLIKELY(size < ip_len)) {
449             goto out;
450         }
451         data_pull(&data, &size, ip_len);
452
453     } else if (dl_type == htons(ETH_TYPE_IPV6)) {
454         const struct ovs_16aligned_ip6_hdr *nh;
455         ovs_be32 tc_flow;
456
457         if (OVS_UNLIKELY(size < sizeof *nh)) {
458             goto out;
459         }
460         nh = data_pull(&data, &size, sizeof *nh);
461
462         miniflow_push_words(mf, ipv6_src, &nh->ip6_src,
463                             sizeof nh->ip6_src / 4);
464         miniflow_push_words(mf, ipv6_dst, &nh->ip6_dst,
465                             sizeof nh->ip6_dst / 4);
466
467         tc_flow = get_16aligned_be32(&nh->ip6_flow);
468         {
469             ovs_be32 label = tc_flow & htonl(IPV6_LABEL_MASK);
470             miniflow_push_be32_check(mf, ipv6_label, label);
471         }
472
473         nw_tos = ntohl(tc_flow) >> 20;
474         nw_ttl = nh->ip6_hlim;
475         nw_proto = nh->ip6_nxt;
476
477         while (1) {
478             if (OVS_LIKELY((nw_proto != IPPROTO_HOPOPTS)
479                            && (nw_proto != IPPROTO_ROUTING)
480                            && (nw_proto != IPPROTO_DSTOPTS)
481                            && (nw_proto != IPPROTO_AH)
482                            && (nw_proto != IPPROTO_FRAGMENT))) {
483                 /* It's either a terminal header (e.g., TCP, UDP) or one we
484                  * don't understand.  In either case, we're done with the
485                  * packet, so use it to fill in 'nw_proto'. */
486                 break;
487             }
488
489             /* We only verify that at least 8 bytes of the next header are
490              * available, but many of these headers are longer.  Ensure that
491              * accesses within the extension header are within those first 8
492              * bytes. All extension headers are required to be at least 8
493              * bytes. */
494             if (OVS_UNLIKELY(size < 8)) {
495                 goto out;
496             }
497
498             if ((nw_proto == IPPROTO_HOPOPTS)
499                 || (nw_proto == IPPROTO_ROUTING)
500                 || (nw_proto == IPPROTO_DSTOPTS)) {
501                 /* These headers, while different, have the fields we care
502                  * about in the same location and with the same
503                  * interpretation. */
504                 const struct ip6_ext *ext_hdr = data;
505                 nw_proto = ext_hdr->ip6e_nxt;
506                 if (OVS_UNLIKELY(!data_try_pull(&data, &size,
507                                                 (ext_hdr->ip6e_len + 1) * 8))) {
508                     goto out;
509                 }
510             } else if (nw_proto == IPPROTO_AH) {
511                 /* A standard AH definition isn't available, but the fields
512                  * we care about are in the same location as the generic
513                  * option header--only the header length is calculated
514                  * differently. */
515                 const struct ip6_ext *ext_hdr = data;
516                 nw_proto = ext_hdr->ip6e_nxt;
517                 if (OVS_UNLIKELY(!data_try_pull(&data, &size,
518                                                 (ext_hdr->ip6e_len + 2) * 4))) {
519                     goto out;
520                 }
521             } else if (nw_proto == IPPROTO_FRAGMENT) {
522                 const struct ovs_16aligned_ip6_frag *frag_hdr = data;
523
524                 nw_proto = frag_hdr->ip6f_nxt;
525                 if (!data_try_pull(&data, &size, sizeof *frag_hdr)) {
526                     goto out;
527                 }
528
529                 /* We only process the first fragment. */
530                 if (frag_hdr->ip6f_offlg != htons(0)) {
531                     nw_frag = FLOW_NW_FRAG_ANY;
532                     if ((frag_hdr->ip6f_offlg & IP6F_OFF_MASK) != htons(0)) {
533                         nw_frag |= FLOW_NW_FRAG_LATER;
534                         nw_proto = IPPROTO_FRAGMENT;
535                         break;
536                     }
537                 }
538             }
539         }
540     } else {
541         if (dl_type == htons(ETH_TYPE_ARP) ||
542             dl_type == htons(ETH_TYPE_RARP)) {
543             uint8_t arp_buf[2][ETH_ADDR_LEN];
544             const struct arp_eth_header *arp = (const struct arp_eth_header *)
545                 data_try_pull(&data, &size, ARP_ETH_HEADER_LEN);
546
547             if (OVS_LIKELY(arp) && OVS_LIKELY(arp->ar_hrd == htons(1))
548                 && OVS_LIKELY(arp->ar_pro == htons(ETH_TYPE_IP))
549                 && OVS_LIKELY(arp->ar_hln == ETH_ADDR_LEN)
550                 && OVS_LIKELY(arp->ar_pln == 4)) {
551                 miniflow_push_words(mf, nw_src, &arp->ar_spa, 1);
552                 miniflow_push_words(mf, nw_dst, &arp->ar_tpa, 1);
553
554                 /* We only match on the lower 8 bits of the opcode. */
555                 if (OVS_LIKELY(ntohs(arp->ar_op) <= 0xff)) {
556                     miniflow_push_be32(mf, nw_frag, htonl(ntohs(arp->ar_op)));
557                 }
558
559                 /* Must be adjacent. */
560                 BUILD_ASSERT(offsetof(struct flow, arp_sha) + 6
561                              == offsetof(struct flow, arp_tha));
562
563                 memcpy(arp_buf[0], arp->ar_sha, ETH_ADDR_LEN);
564                 memcpy(arp_buf[1], arp->ar_tha, ETH_ADDR_LEN);
565                 miniflow_push_words(mf, arp_sha, arp_buf,
566                                     ETH_ADDR_LEN * 2 / 4);
567             }
568         }
569         goto out;
570     }
571
572     packet->l4_ofs = (char *)data - l2;
573     miniflow_push_be32(mf, nw_frag,
574                        BYTES_TO_BE32(nw_frag, nw_tos, nw_ttl, nw_proto));
575
576     if (OVS_LIKELY(!(nw_frag & FLOW_NW_FRAG_LATER))) {
577         if (OVS_LIKELY(nw_proto == IPPROTO_TCP)) {
578             if (OVS_LIKELY(size >= TCP_HEADER_LEN)) {
579                 const struct tcp_header *tcp = data;
580
581                 miniflow_push_be32(mf, tcp_flags,
582                                    TCP_FLAGS_BE32(tcp->tcp_ctl));
583                 miniflow_push_words(mf, tp_src, &tcp->tcp_src, 1);
584             }
585         } else if (OVS_LIKELY(nw_proto == IPPROTO_UDP)) {
586             if (OVS_LIKELY(size >= UDP_HEADER_LEN)) {
587                 const struct udp_header *udp = data;
588
589                 miniflow_push_words(mf, tp_src, &udp->udp_src, 1);
590             }
591         } else if (OVS_LIKELY(nw_proto == IPPROTO_SCTP)) {
592             if (OVS_LIKELY(size >= SCTP_HEADER_LEN)) {
593                 const struct sctp_header *sctp = data;
594
595                 miniflow_push_words(mf, tp_src, &sctp->sctp_src, 1);
596             }
597         } else if (OVS_LIKELY(nw_proto == IPPROTO_ICMP)) {
598             if (OVS_LIKELY(size >= ICMP_HEADER_LEN)) {
599                 const struct icmp_header *icmp = data;
600
601                 miniflow_push_be16(mf, tp_src, htons(icmp->icmp_type));
602                 miniflow_push_be16(mf, tp_dst, htons(icmp->icmp_code));
603             }
604         } else if (OVS_LIKELY(nw_proto == IPPROTO_IGMP)) {
605             if (OVS_LIKELY(size >= IGMP_HEADER_LEN)) {
606                 const struct igmp_header *igmp = data;
607
608                 miniflow_push_be16(mf, tp_src, htons(igmp->igmp_type));
609                 miniflow_push_be16(mf, tp_dst, htons(igmp->igmp_code));
610                 miniflow_push_be32(mf, igmp_group_ip4,
611                                    get_16aligned_be32(&igmp->group));
612             }
613         } else if (OVS_LIKELY(nw_proto == IPPROTO_ICMPV6)) {
614             if (OVS_LIKELY(size >= sizeof(struct icmp6_hdr))) {
615                 const struct in6_addr *nd_target = NULL;
616                 uint8_t arp_buf[2][ETH_ADDR_LEN];
617                 const struct icmp6_hdr *icmp = data_pull(&data, &size,
618                                                          sizeof *icmp);
619                 memset(arp_buf, 0, sizeof arp_buf);
620                 if (OVS_LIKELY(parse_icmpv6(&data, &size, icmp, &nd_target,
621                                             arp_buf))) {
622                     miniflow_push_words(mf, arp_sha, arp_buf,
623                                              ETH_ADDR_LEN * 2 / 4);
624                     if (nd_target) {
625                         miniflow_push_words(mf, nd_target, nd_target,
626                                             sizeof *nd_target / 4);
627                     }
628                     miniflow_push_be16(mf, tp_src, htons(icmp->icmp6_type));
629                     miniflow_push_be16(mf, tp_dst, htons(icmp->icmp6_code));
630                 }
631             }
632         }
633     }
634     if (md) {
635         miniflow_push_uint32_check(mf, dp_hash, md->dp_hash);
636     }
637  out:
638     dst->map = mf.map;
639 }
640
641 /* For every bit of a field that is wildcarded in 'wildcards', sets the
642  * corresponding bit in 'flow' to zero. */
643 void
644 flow_zero_wildcards(struct flow *flow, const struct flow_wildcards *wildcards)
645 {
646     uint32_t *flow_u32 = (uint32_t *) flow;
647     const uint32_t *wc_u32 = (const uint32_t *) &wildcards->masks;
648     size_t i;
649
650     for (i = 0; i < FLOW_U32S; i++) {
651         flow_u32[i] &= wc_u32[i];
652     }
653 }
654
655 void
656 flow_unwildcard_tp_ports(const struct flow *flow, struct flow_wildcards *wc)
657 {
658     if (flow->nw_proto != IPPROTO_ICMP) {
659         memset(&wc->masks.tp_src, 0xff, sizeof wc->masks.tp_src);
660         memset(&wc->masks.tp_dst, 0xff, sizeof wc->masks.tp_dst);
661     } else {
662         wc->masks.tp_src = htons(0xff);
663         wc->masks.tp_dst = htons(0xff);
664     }
665 }
666
667 /* Initializes 'fmd' with the metadata found in 'flow'. */
668 void
669 flow_get_metadata(const struct flow *flow, struct flow_metadata *fmd)
670 {
671     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 27);
672
673     fmd->dp_hash = flow->dp_hash;
674     fmd->recirc_id = flow->recirc_id;
675     fmd->tun_id = flow->tunnel.tun_id;
676     fmd->tun_src = flow->tunnel.ip_src;
677     fmd->tun_dst = flow->tunnel.ip_dst;
678     fmd->metadata = flow->metadata;
679     memcpy(fmd->regs, flow->regs, sizeof fmd->regs);
680     fmd->pkt_mark = flow->pkt_mark;
681     fmd->in_port = flow->in_port.ofp_port;
682 }
683
684 char *
685 flow_to_string(const struct flow *flow)
686 {
687     struct ds ds = DS_EMPTY_INITIALIZER;
688     flow_format(&ds, flow);
689     return ds_cstr(&ds);
690 }
691
692 const char *
693 flow_tun_flag_to_string(uint32_t flags)
694 {
695     switch (flags) {
696     case FLOW_TNL_F_DONT_FRAGMENT:
697         return "df";
698     case FLOW_TNL_F_CSUM:
699         return "csum";
700     case FLOW_TNL_F_KEY:
701         return "key";
702     case FLOW_TNL_F_OAM:
703         return "oam";
704     default:
705         return NULL;
706     }
707 }
708
709 void
710 format_flags(struct ds *ds, const char *(*bit_to_string)(uint32_t),
711              uint32_t flags, char del)
712 {
713     uint32_t bad = 0;
714
715     if (!flags) {
716         return;
717     }
718     while (flags) {
719         uint32_t bit = rightmost_1bit(flags);
720         const char *s;
721
722         s = bit_to_string(bit);
723         if (s) {
724             ds_put_format(ds, "%s%c", s, del);
725         } else {
726             bad |= bit;
727         }
728
729         flags &= ~bit;
730     }
731
732     if (bad) {
733         ds_put_format(ds, "0x%"PRIx32"%c", bad, del);
734     }
735     ds_chomp(ds, del);
736 }
737
738 void
739 format_flags_masked(struct ds *ds, const char *name,
740                     const char *(*bit_to_string)(uint32_t), uint32_t flags,
741                     uint32_t mask)
742 {
743     if (name) {
744         ds_put_format(ds, "%s=", name);
745     }
746     while (mask) {
747         uint32_t bit = rightmost_1bit(mask);
748         const char *s = bit_to_string(bit);
749
750         ds_put_format(ds, "%s%s", (flags & bit) ? "+" : "-",
751                       s ? s : "[Unknown]");
752         mask &= ~bit;
753     }
754 }
755
756 void
757 flow_format(struct ds *ds, const struct flow *flow)
758 {
759     struct match match;
760
761     match_wc_init(&match, flow);
762     match_format(&match, ds, OFP_DEFAULT_PRIORITY);
763 }
764
765 void
766 flow_print(FILE *stream, const struct flow *flow)
767 {
768     char *s = flow_to_string(flow);
769     fputs(s, stream);
770     free(s);
771 }
772 \f
773 /* flow_wildcards functions. */
774
775 /* Initializes 'wc' as a set of wildcards that matches every packet. */
776 void
777 flow_wildcards_init_catchall(struct flow_wildcards *wc)
778 {
779     memset(&wc->masks, 0, sizeof wc->masks);
780 }
781
782 /* Clear the metadata and register wildcard masks. They are not packet
783  * header fields. */
784 void
785 flow_wildcards_clear_non_packet_fields(struct flow_wildcards *wc)
786 {
787     memset(&wc->masks.metadata, 0, sizeof wc->masks.metadata);
788     memset(&wc->masks.regs, 0, sizeof wc->masks.regs);
789 }
790
791 /* Returns true if 'wc' matches every packet, false if 'wc' fixes any bits or
792  * fields. */
793 bool
794 flow_wildcards_is_catchall(const struct flow_wildcards *wc)
795 {
796     const uint32_t *wc_u32 = (const uint32_t *) &wc->masks;
797     size_t i;
798
799     for (i = 0; i < FLOW_U32S; i++) {
800         if (wc_u32[i]) {
801             return false;
802         }
803     }
804     return true;
805 }
806
807 /* Sets 'dst' as the bitwise AND of wildcards in 'src1' and 'src2'.
808  * That is, a bit or a field is wildcarded in 'dst' if it is wildcarded
809  * in 'src1' or 'src2' or both.  */
810 void
811 flow_wildcards_and(struct flow_wildcards *dst,
812                    const struct flow_wildcards *src1,
813                    const struct flow_wildcards *src2)
814 {
815     uint32_t *dst_u32 = (uint32_t *) &dst->masks;
816     const uint32_t *src1_u32 = (const uint32_t *) &src1->masks;
817     const uint32_t *src2_u32 = (const uint32_t *) &src2->masks;
818     size_t i;
819
820     for (i = 0; i < FLOW_U32S; i++) {
821         dst_u32[i] = src1_u32[i] & src2_u32[i];
822     }
823 }
824
825 /* Sets 'dst' as the bitwise OR of wildcards in 'src1' and 'src2'.  That
826  * is, a bit or a field is wildcarded in 'dst' if it is neither
827  * wildcarded in 'src1' nor 'src2'. */
828 void
829 flow_wildcards_or(struct flow_wildcards *dst,
830                   const struct flow_wildcards *src1,
831                   const struct flow_wildcards *src2)
832 {
833     uint32_t *dst_u32 = (uint32_t *) &dst->masks;
834     const uint32_t *src1_u32 = (const uint32_t *) &src1->masks;
835     const uint32_t *src2_u32 = (const uint32_t *) &src2->masks;
836     size_t i;
837
838     for (i = 0; i < FLOW_U32S; i++) {
839         dst_u32[i] = src1_u32[i] | src2_u32[i];
840     }
841 }
842
843 /* Returns a hash of the wildcards in 'wc'. */
844 uint32_t
845 flow_wildcards_hash(const struct flow_wildcards *wc, uint32_t basis)
846 {
847     return flow_hash(&wc->masks, basis);
848 }
849
850 /* Returns true if 'a' and 'b' represent the same wildcards, false if they are
851  * different. */
852 bool
853 flow_wildcards_equal(const struct flow_wildcards *a,
854                      const struct flow_wildcards *b)
855 {
856     return flow_equal(&a->masks, &b->masks);
857 }
858
859 /* Returns true if at least one bit or field is wildcarded in 'a' but not in
860  * 'b', false otherwise. */
861 bool
862 flow_wildcards_has_extra(const struct flow_wildcards *a,
863                          const struct flow_wildcards *b)
864 {
865     const uint32_t *a_u32 = (const uint32_t *) &a->masks;
866     const uint32_t *b_u32 = (const uint32_t *) &b->masks;
867     size_t i;
868
869     for (i = 0; i < FLOW_U32S; i++) {
870         if ((a_u32[i] & b_u32[i]) != b_u32[i]) {
871             return true;
872         }
873     }
874     return false;
875 }
876
877 /* Returns true if 'a' and 'b' are equal, except that 0-bits (wildcarded bits)
878  * in 'wc' do not need to be equal in 'a' and 'b'. */
879 bool
880 flow_equal_except(const struct flow *a, const struct flow *b,
881                   const struct flow_wildcards *wc)
882 {
883     const uint32_t *a_u32 = (const uint32_t *) a;
884     const uint32_t *b_u32 = (const uint32_t *) b;
885     const uint32_t *wc_u32 = (const uint32_t *) &wc->masks;
886     size_t i;
887
888     for (i = 0; i < FLOW_U32S; i++) {
889         if ((a_u32[i] ^ b_u32[i]) & wc_u32[i]) {
890             return false;
891         }
892     }
893     return true;
894 }
895
896 /* Sets the wildcard mask for register 'idx' in 'wc' to 'mask'.
897  * (A 0-bit indicates a wildcard bit.) */
898 void
899 flow_wildcards_set_reg_mask(struct flow_wildcards *wc, int idx, uint32_t mask)
900 {
901     wc->masks.regs[idx] = mask;
902 }
903
904 /* Sets the wildcard mask for register 'idx' in 'wc' to 'mask'.
905  * (A 0-bit indicates a wildcard bit.) */
906 void
907 flow_wildcards_set_xreg_mask(struct flow_wildcards *wc, int idx, uint64_t mask)
908 {
909     flow_set_xreg(&wc->masks, idx, mask);
910 }
911
912 /* Calculates the 5-tuple hash from the given miniflow.
913  * This returns the same value as flow_hash_5tuple for the corresponding
914  * flow. */
915 uint32_t
916 miniflow_hash_5tuple(const struct miniflow *flow, uint32_t basis)
917 {
918     uint32_t hash = basis;
919
920     if (flow) {
921         ovs_be16 dl_type = MINIFLOW_GET_BE16(flow, dl_type);
922
923         hash = hash_add(hash, MINIFLOW_GET_U8(flow, nw_proto));
924
925         /* Separate loops for better optimization. */
926         if (dl_type == htons(ETH_TYPE_IPV6)) {
927             uint64_t map = MINIFLOW_MAP(ipv6_src) | MINIFLOW_MAP(ipv6_dst)
928                 | MINIFLOW_MAP(tp_src); /* Covers both ports */
929             uint32_t value;
930
931             MINIFLOW_FOR_EACH_IN_MAP(value, flow, map) {
932                 hash = hash_add(hash, value);
933             }
934         } else {
935             uint64_t map = MINIFLOW_MAP(nw_src) | MINIFLOW_MAP(nw_dst)
936                 | MINIFLOW_MAP(tp_src); /* Covers both ports */
937             uint32_t value;
938
939             MINIFLOW_FOR_EACH_IN_MAP(value, flow, map) {
940                 hash = hash_add(hash, value);
941             }
942         }
943         hash = hash_finish(hash, 42); /* Arbitrary number. */
944     }
945     return hash;
946 }
947
948 BUILD_ASSERT_DECL(offsetof(struct flow, tp_src) + 2
949                   == offsetof(struct flow, tp_dst) &&
950                   offsetof(struct flow, tp_src) / 4
951                   == offsetof(struct flow, tp_dst) / 4);
952 BUILD_ASSERT_DECL(offsetof(struct flow, ipv6_src) + 16
953                   == offsetof(struct flow, ipv6_dst));
954
955 /* Calculates the 5-tuple hash from the given flow. */
956 uint32_t
957 flow_hash_5tuple(const struct flow *flow, uint32_t basis)
958 {
959     uint32_t hash = basis;
960
961     if (flow) {
962         const uint32_t *flow_u32 = (const uint32_t *)flow;
963
964         hash = hash_add(hash, flow->nw_proto);
965
966         if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
967             int ofs = offsetof(struct flow, ipv6_src) / 4;
968             int end = ofs + 2 * sizeof flow->ipv6_src / 4;
969
970             while (ofs < end) {
971                 hash = hash_add(hash, flow_u32[ofs++]);
972             }
973         } else {
974             hash = hash_add(hash, (OVS_FORCE uint32_t) flow->nw_src);
975             hash = hash_add(hash, (OVS_FORCE uint32_t) flow->nw_dst);
976         }
977         hash = hash_add(hash, flow_u32[offsetof(struct flow, tp_src) / 4]);
978
979         hash = hash_finish(hash, 42); /* Arbitrary number. */
980     }
981     return hash;
982 }
983
984 /* Hashes 'flow' based on its L2 through L4 protocol information. */
985 uint32_t
986 flow_hash_symmetric_l4(const struct flow *flow, uint32_t basis)
987 {
988     struct {
989         union {
990             ovs_be32 ipv4_addr;
991             struct in6_addr ipv6_addr;
992         };
993         ovs_be16 eth_type;
994         ovs_be16 vlan_tci;
995         ovs_be16 tp_port;
996         uint8_t eth_addr[ETH_ADDR_LEN];
997         uint8_t ip_proto;
998     } fields;
999
1000     int i;
1001
1002     memset(&fields, 0, sizeof fields);
1003     for (i = 0; i < ETH_ADDR_LEN; i++) {
1004         fields.eth_addr[i] = flow->dl_src[i] ^ flow->dl_dst[i];
1005     }
1006     fields.vlan_tci = flow->vlan_tci & htons(VLAN_VID_MASK);
1007     fields.eth_type = flow->dl_type;
1008
1009     /* UDP source and destination port are not taken into account because they
1010      * will not necessarily be symmetric in a bidirectional flow. */
1011     if (fields.eth_type == htons(ETH_TYPE_IP)) {
1012         fields.ipv4_addr = flow->nw_src ^ flow->nw_dst;
1013         fields.ip_proto = flow->nw_proto;
1014         if (fields.ip_proto == IPPROTO_TCP || fields.ip_proto == IPPROTO_SCTP) {
1015             fields.tp_port = flow->tp_src ^ flow->tp_dst;
1016         }
1017     } else if (fields.eth_type == htons(ETH_TYPE_IPV6)) {
1018         const uint8_t *a = &flow->ipv6_src.s6_addr[0];
1019         const uint8_t *b = &flow->ipv6_dst.s6_addr[0];
1020         uint8_t *ipv6_addr = &fields.ipv6_addr.s6_addr[0];
1021
1022         for (i=0; i<16; i++) {
1023             ipv6_addr[i] = a[i] ^ b[i];
1024         }
1025         fields.ip_proto = flow->nw_proto;
1026         if (fields.ip_proto == IPPROTO_TCP || fields.ip_proto == IPPROTO_SCTP) {
1027             fields.tp_port = flow->tp_src ^ flow->tp_dst;
1028         }
1029     }
1030     return jhash_bytes(&fields, sizeof fields, basis);
1031 }
1032
1033 /* Initialize a flow with random fields that matter for nx_hash_fields. */
1034 void
1035 flow_random_hash_fields(struct flow *flow)
1036 {
1037     uint16_t rnd = random_uint16();
1038
1039     /* Initialize to all zeros. */
1040     memset(flow, 0, sizeof *flow);
1041
1042     eth_addr_random(flow->dl_src);
1043     eth_addr_random(flow->dl_dst);
1044
1045     flow->vlan_tci = (OVS_FORCE ovs_be16) (random_uint16() & VLAN_VID_MASK);
1046
1047     /* Make most of the random flows IPv4, some IPv6, and rest random. */
1048     flow->dl_type = rnd < 0x8000 ? htons(ETH_TYPE_IP) :
1049         rnd < 0xc000 ? htons(ETH_TYPE_IPV6) : (OVS_FORCE ovs_be16)rnd;
1050
1051     if (dl_type_is_ip_any(flow->dl_type)) {
1052         if (flow->dl_type == htons(ETH_TYPE_IP)) {
1053             flow->nw_src = (OVS_FORCE ovs_be32)random_uint32();
1054             flow->nw_dst = (OVS_FORCE ovs_be32)random_uint32();
1055         } else {
1056             random_bytes(&flow->ipv6_src, sizeof flow->ipv6_src);
1057             random_bytes(&flow->ipv6_dst, sizeof flow->ipv6_dst);
1058         }
1059         /* Make most of IP flows TCP, some UDP or SCTP, and rest random. */
1060         rnd = random_uint16();
1061         flow->nw_proto = rnd < 0x8000 ? IPPROTO_TCP :
1062             rnd < 0xc000 ? IPPROTO_UDP :
1063             rnd < 0xd000 ? IPPROTO_SCTP : (uint8_t)rnd;
1064         if (flow->nw_proto == IPPROTO_TCP ||
1065             flow->nw_proto == IPPROTO_UDP ||
1066             flow->nw_proto == IPPROTO_SCTP) {
1067             flow->tp_src = (OVS_FORCE ovs_be16)random_uint16();
1068             flow->tp_dst = (OVS_FORCE ovs_be16)random_uint16();
1069         }
1070     }
1071 }
1072
1073 /* Masks the fields in 'wc' that are used by the flow hash 'fields'. */
1074 void
1075 flow_mask_hash_fields(const struct flow *flow, struct flow_wildcards *wc,
1076                       enum nx_hash_fields fields)
1077 {
1078     switch (fields) {
1079     case NX_HASH_FIELDS_ETH_SRC:
1080         memset(&wc->masks.dl_src, 0xff, sizeof wc->masks.dl_src);
1081         break;
1082
1083     case NX_HASH_FIELDS_SYMMETRIC_L4:
1084         memset(&wc->masks.dl_src, 0xff, sizeof wc->masks.dl_src);
1085         memset(&wc->masks.dl_dst, 0xff, sizeof wc->masks.dl_dst);
1086         if (flow->dl_type == htons(ETH_TYPE_IP)) {
1087             memset(&wc->masks.nw_src, 0xff, sizeof wc->masks.nw_src);
1088             memset(&wc->masks.nw_dst, 0xff, sizeof wc->masks.nw_dst);
1089         } else if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
1090             memset(&wc->masks.ipv6_src, 0xff, sizeof wc->masks.ipv6_src);
1091             memset(&wc->masks.ipv6_dst, 0xff, sizeof wc->masks.ipv6_dst);
1092         }
1093         if (is_ip_any(flow)) {
1094             memset(&wc->masks.nw_proto, 0xff, sizeof wc->masks.nw_proto);
1095             flow_unwildcard_tp_ports(flow, wc);
1096         }
1097         wc->masks.vlan_tci |= htons(VLAN_VID_MASK | VLAN_CFI);
1098         break;
1099
1100     default:
1101         OVS_NOT_REACHED();
1102     }
1103 }
1104
1105 /* Hashes the portions of 'flow' designated by 'fields'. */
1106 uint32_t
1107 flow_hash_fields(const struct flow *flow, enum nx_hash_fields fields,
1108                  uint16_t basis)
1109 {
1110     switch (fields) {
1111
1112     case NX_HASH_FIELDS_ETH_SRC:
1113         return jhash_bytes(flow->dl_src, sizeof flow->dl_src, basis);
1114
1115     case NX_HASH_FIELDS_SYMMETRIC_L4:
1116         return flow_hash_symmetric_l4(flow, basis);
1117     }
1118
1119     OVS_NOT_REACHED();
1120 }
1121
1122 /* Returns a string representation of 'fields'. */
1123 const char *
1124 flow_hash_fields_to_str(enum nx_hash_fields fields)
1125 {
1126     switch (fields) {
1127     case NX_HASH_FIELDS_ETH_SRC: return "eth_src";
1128     case NX_HASH_FIELDS_SYMMETRIC_L4: return "symmetric_l4";
1129     default: return "<unknown>";
1130     }
1131 }
1132
1133 /* Returns true if the value of 'fields' is supported. Otherwise false. */
1134 bool
1135 flow_hash_fields_valid(enum nx_hash_fields fields)
1136 {
1137     return fields == NX_HASH_FIELDS_ETH_SRC
1138         || fields == NX_HASH_FIELDS_SYMMETRIC_L4;
1139 }
1140
1141 /* Returns a hash value for the bits of 'flow' that are active based on
1142  * 'wc', given 'basis'. */
1143 uint32_t
1144 flow_hash_in_wildcards(const struct flow *flow,
1145                        const struct flow_wildcards *wc, uint32_t basis)
1146 {
1147     const uint32_t *wc_u32 = (const uint32_t *) &wc->masks;
1148     const uint32_t *flow_u32 = (const uint32_t *) flow;
1149     uint32_t hash;
1150     size_t i;
1151
1152     hash = basis;
1153     for (i = 0; i < FLOW_U32S; i++) {
1154         hash = hash_add(hash, flow_u32[i] & wc_u32[i]);
1155     }
1156     return hash_finish(hash, 4 * FLOW_U32S);
1157 }
1158
1159 /* Sets the VLAN VID that 'flow' matches to 'vid', which is interpreted as an
1160  * OpenFlow 1.0 "dl_vlan" value:
1161  *
1162  *      - If it is in the range 0...4095, 'flow->vlan_tci' is set to match
1163  *        that VLAN.  Any existing PCP match is unchanged (it becomes 0 if
1164  *        'flow' previously matched packets without a VLAN header).
1165  *
1166  *      - If it is OFP_VLAN_NONE, 'flow->vlan_tci' is set to match a packet
1167  *        without a VLAN tag.
1168  *
1169  *      - Other values of 'vid' should not be used. */
1170 void
1171 flow_set_dl_vlan(struct flow *flow, ovs_be16 vid)
1172 {
1173     if (vid == htons(OFP10_VLAN_NONE)) {
1174         flow->vlan_tci = htons(0);
1175     } else {
1176         vid &= htons(VLAN_VID_MASK);
1177         flow->vlan_tci &= ~htons(VLAN_VID_MASK);
1178         flow->vlan_tci |= htons(VLAN_CFI) | vid;
1179     }
1180 }
1181
1182 /* Sets the VLAN VID that 'flow' matches to 'vid', which is interpreted as an
1183  * OpenFlow 1.2 "vlan_vid" value, that is, the low 13 bits of 'vlan_tci' (VID
1184  * plus CFI). */
1185 void
1186 flow_set_vlan_vid(struct flow *flow, ovs_be16 vid)
1187 {
1188     ovs_be16 mask = htons(VLAN_VID_MASK | VLAN_CFI);
1189     flow->vlan_tci &= ~mask;
1190     flow->vlan_tci |= vid & mask;
1191 }
1192
1193 /* Sets the VLAN PCP that 'flow' matches to 'pcp', which should be in the
1194  * range 0...7.
1195  *
1196  * This function has no effect on the VLAN ID that 'flow' matches.
1197  *
1198  * After calling this function, 'flow' will not match packets without a VLAN
1199  * header. */
1200 void
1201 flow_set_vlan_pcp(struct flow *flow, uint8_t pcp)
1202 {
1203     pcp &= 0x07;
1204     flow->vlan_tci &= ~htons(VLAN_PCP_MASK);
1205     flow->vlan_tci |= htons((pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
1206 }
1207
1208 /* Returns the number of MPLS LSEs present in 'flow'
1209  *
1210  * Returns 0 if the 'dl_type' of 'flow' is not an MPLS ethernet type.
1211  * Otherwise traverses 'flow''s MPLS label stack stopping at the
1212  * first entry that has the BoS bit set. If no such entry exists then
1213  * the maximum number of LSEs that can be stored in 'flow' is returned.
1214  */
1215 int
1216 flow_count_mpls_labels(const struct flow *flow, struct flow_wildcards *wc)
1217 {
1218     if (wc) {
1219         wc->masks.dl_type = OVS_BE16_MAX;
1220     }
1221     if (eth_type_mpls(flow->dl_type)) {
1222         int i;
1223         int len = FLOW_MAX_MPLS_LABELS;
1224
1225         for (i = 0; i < len; i++) {
1226             if (wc) {
1227                 wc->masks.mpls_lse[i] |= htonl(MPLS_BOS_MASK);
1228             }
1229             if (flow->mpls_lse[i] & htonl(MPLS_BOS_MASK)) {
1230                 return i + 1;
1231             }
1232         }
1233
1234         return len;
1235     } else {
1236         return 0;
1237     }
1238 }
1239
1240 /* Returns the number consecutive of MPLS LSEs, starting at the
1241  * innermost LSE, that are common in 'a' and 'b'.
1242  *
1243  * 'an' must be flow_count_mpls_labels(a).
1244  * 'bn' must be flow_count_mpls_labels(b).
1245  */
1246 int
1247 flow_count_common_mpls_labels(const struct flow *a, int an,
1248                               const struct flow *b, int bn,
1249                               struct flow_wildcards *wc)
1250 {
1251     int min_n = MIN(an, bn);
1252     if (min_n == 0) {
1253         return 0;
1254     } else {
1255         int common_n = 0;
1256         int a_last = an - 1;
1257         int b_last = bn - 1;
1258         int i;
1259
1260         for (i = 0; i < min_n; i++) {
1261             if (wc) {
1262                 wc->masks.mpls_lse[a_last - i] = OVS_BE32_MAX;
1263                 wc->masks.mpls_lse[b_last - i] = OVS_BE32_MAX;
1264             }
1265             if (a->mpls_lse[a_last - i] != b->mpls_lse[b_last - i]) {
1266                 break;
1267             } else {
1268                 common_n++;
1269             }
1270         }
1271
1272         return common_n;
1273     }
1274 }
1275
1276 /* Adds a new outermost MPLS label to 'flow' and changes 'flow''s Ethernet type
1277  * to 'mpls_eth_type', which must be an MPLS Ethertype.
1278  *
1279  * If the new label is the first MPLS label in 'flow', it is generated as;
1280  *
1281  *     - label: 2, if 'flow' is IPv6, otherwise 0.
1282  *
1283  *     - TTL: IPv4 or IPv6 TTL, if present and nonzero, otherwise 64.
1284  *
1285  *     - TC: IPv4 or IPv6 TOS, if present, otherwise 0.
1286  *
1287  *     - BoS: 1.
1288  *
1289  * If the new label is the second or label MPLS label in 'flow', it is
1290  * generated as;
1291  *
1292  *     - label: Copied from outer label.
1293  *
1294  *     - TTL: Copied from outer label.
1295  *
1296  *     - TC: Copied from outer label.
1297  *
1298  *     - BoS: 0.
1299  *
1300  * 'n' must be flow_count_mpls_labels(flow).  'n' must be less than
1301  * FLOW_MAX_MPLS_LABELS (because otherwise flow->mpls_lse[] would overflow).
1302  */
1303 void
1304 flow_push_mpls(struct flow *flow, int n, ovs_be16 mpls_eth_type,
1305                struct flow_wildcards *wc)
1306 {
1307     ovs_assert(eth_type_mpls(mpls_eth_type));
1308     ovs_assert(n < FLOW_MAX_MPLS_LABELS);
1309
1310     memset(wc->masks.mpls_lse, 0xff, sizeof wc->masks.mpls_lse);
1311     if (n) {
1312         int i;
1313
1314         for (i = n; i >= 1; i--) {
1315             flow->mpls_lse[i] = flow->mpls_lse[i - 1];
1316         }
1317         flow->mpls_lse[0] = (flow->mpls_lse[1]
1318                              & htonl(~MPLS_BOS_MASK));
1319     } else {
1320         int label = 0;          /* IPv4 Explicit Null. */
1321         int tc = 0;
1322         int ttl = 64;
1323
1324         if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
1325             label = 2;
1326         }
1327
1328         if (is_ip_any(flow)) {
1329             tc = (flow->nw_tos & IP_DSCP_MASK) >> 2;
1330             wc->masks.nw_tos |= IP_DSCP_MASK;
1331
1332             if (flow->nw_ttl) {
1333                 ttl = flow->nw_ttl;
1334             }
1335             wc->masks.nw_ttl = 0xff;
1336         }
1337
1338         flow->mpls_lse[0] = set_mpls_lse_values(ttl, tc, 1, htonl(label));
1339
1340         /* Clear all L3 and L4 fields. */
1341         BUILD_ASSERT(FLOW_WC_SEQ == 27);
1342         memset((char *) flow + FLOW_SEGMENT_2_ENDS_AT, 0,
1343                sizeof(struct flow) - FLOW_SEGMENT_2_ENDS_AT);
1344     }
1345     flow->dl_type = mpls_eth_type;
1346 }
1347
1348 /* Tries to remove the outermost MPLS label from 'flow'.  Returns true if
1349  * successful, false otherwise.  On success, sets 'flow''s Ethernet type to
1350  * 'eth_type'.
1351  *
1352  * 'n' must be flow_count_mpls_labels(flow). */
1353 bool
1354 flow_pop_mpls(struct flow *flow, int n, ovs_be16 eth_type,
1355               struct flow_wildcards *wc)
1356 {
1357     int i;
1358
1359     if (n == 0) {
1360         /* Nothing to pop. */
1361         return false;
1362     } else if (n == FLOW_MAX_MPLS_LABELS
1363                && !(flow->mpls_lse[n - 1] & htonl(MPLS_BOS_MASK))) {
1364         /* Can't pop because we don't know what to fill in mpls_lse[n - 1]. */
1365         return false;
1366     }
1367
1368     memset(wc->masks.mpls_lse, 0xff, sizeof wc->masks.mpls_lse);
1369     for (i = 1; i < n; i++) {
1370         flow->mpls_lse[i - 1] = flow->mpls_lse[i];
1371     }
1372     flow->mpls_lse[n - 1] = 0;
1373     flow->dl_type = eth_type;
1374     return true;
1375 }
1376
1377 /* Sets the MPLS Label that 'flow' matches to 'label', which is interpreted
1378  * as an OpenFlow 1.1 "mpls_label" value. */
1379 void
1380 flow_set_mpls_label(struct flow *flow, int idx, ovs_be32 label)
1381 {
1382     set_mpls_lse_label(&flow->mpls_lse[idx], label);
1383 }
1384
1385 /* Sets the MPLS TTL that 'flow' matches to 'ttl', which should be in the
1386  * range 0...255. */
1387 void
1388 flow_set_mpls_ttl(struct flow *flow, int idx, uint8_t ttl)
1389 {
1390     set_mpls_lse_ttl(&flow->mpls_lse[idx], ttl);
1391 }
1392
1393 /* Sets the MPLS TC that 'flow' matches to 'tc', which should be in the
1394  * range 0...7. */
1395 void
1396 flow_set_mpls_tc(struct flow *flow, int idx, uint8_t tc)
1397 {
1398     set_mpls_lse_tc(&flow->mpls_lse[idx], tc);
1399 }
1400
1401 /* Sets the MPLS BOS bit that 'flow' matches to which should be 0 or 1. */
1402 void
1403 flow_set_mpls_bos(struct flow *flow, int idx, uint8_t bos)
1404 {
1405     set_mpls_lse_bos(&flow->mpls_lse[idx], bos);
1406 }
1407
1408 /* Sets the entire MPLS LSE. */
1409 void
1410 flow_set_mpls_lse(struct flow *flow, int idx, ovs_be32 lse)
1411 {
1412     flow->mpls_lse[idx] = lse;
1413 }
1414
1415 static size_t
1416 flow_compose_l4(struct ofpbuf *b, const struct flow *flow)
1417 {
1418     size_t l4_len = 0;
1419
1420     if (!(flow->nw_frag & FLOW_NW_FRAG_ANY)
1421         || !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
1422         if (flow->nw_proto == IPPROTO_TCP) {
1423             struct tcp_header *tcp;
1424
1425             l4_len = sizeof *tcp;
1426             tcp = ofpbuf_put_zeros(b, l4_len);
1427             tcp->tcp_src = flow->tp_src;
1428             tcp->tcp_dst = flow->tp_dst;
1429             tcp->tcp_ctl = TCP_CTL(ntohs(flow->tcp_flags), 5);
1430         } else if (flow->nw_proto == IPPROTO_UDP) {
1431             struct udp_header *udp;
1432
1433             l4_len = sizeof *udp;
1434             udp = ofpbuf_put_zeros(b, l4_len);
1435             udp->udp_src = flow->tp_src;
1436             udp->udp_dst = flow->tp_dst;
1437         } else if (flow->nw_proto == IPPROTO_SCTP) {
1438             struct sctp_header *sctp;
1439
1440             l4_len = sizeof *sctp;
1441             sctp = ofpbuf_put_zeros(b, l4_len);
1442             sctp->sctp_src = flow->tp_src;
1443             sctp->sctp_dst = flow->tp_dst;
1444         } else if (flow->nw_proto == IPPROTO_ICMP) {
1445             struct icmp_header *icmp;
1446
1447             l4_len = sizeof *icmp;
1448             icmp = ofpbuf_put_zeros(b, l4_len);
1449             icmp->icmp_type = ntohs(flow->tp_src);
1450             icmp->icmp_code = ntohs(flow->tp_dst);
1451             icmp->icmp_csum = csum(icmp, ICMP_HEADER_LEN);
1452         } else if (flow->nw_proto == IPPROTO_IGMP) {
1453             struct igmp_header *igmp;
1454
1455             l4_len = sizeof *igmp;
1456             igmp = ofpbuf_put_zeros(b, l4_len);
1457             igmp->igmp_type = ntohs(flow->tp_src);
1458             igmp->igmp_code = ntohs(flow->tp_dst);
1459             put_16aligned_be32(&igmp->group, flow->igmp_group_ip4);
1460             igmp->igmp_csum = csum(igmp, IGMP_HEADER_LEN);
1461         } else if (flow->nw_proto == IPPROTO_ICMPV6) {
1462             struct icmp6_hdr *icmp;
1463
1464             l4_len = sizeof *icmp;
1465             icmp = ofpbuf_put_zeros(b, l4_len);
1466             icmp->icmp6_type = ntohs(flow->tp_src);
1467             icmp->icmp6_code = ntohs(flow->tp_dst);
1468
1469             if (icmp->icmp6_code == 0 &&
1470                 (icmp->icmp6_type == ND_NEIGHBOR_SOLICIT ||
1471                  icmp->icmp6_type == ND_NEIGHBOR_ADVERT)) {
1472                 struct in6_addr *nd_target;
1473                 struct nd_opt_hdr *nd_opt;
1474
1475                 l4_len += sizeof *nd_target;
1476                 nd_target = ofpbuf_put_zeros(b, sizeof *nd_target);
1477                 *nd_target = flow->nd_target;
1478
1479                 if (!eth_addr_is_zero(flow->arp_sha)) {
1480                     l4_len += 8;
1481                     nd_opt = ofpbuf_put_zeros(b, 8);
1482                     nd_opt->nd_opt_len = 1;
1483                     nd_opt->nd_opt_type = ND_OPT_SOURCE_LINKADDR;
1484                     memcpy(nd_opt + 1, flow->arp_sha, ETH_ADDR_LEN);
1485                 }
1486                 if (!eth_addr_is_zero(flow->arp_tha)) {
1487                     l4_len += 8;
1488                     nd_opt = ofpbuf_put_zeros(b, 8);
1489                     nd_opt->nd_opt_len = 1;
1490                     nd_opt->nd_opt_type = ND_OPT_TARGET_LINKADDR;
1491                     memcpy(nd_opt + 1, flow->arp_tha, ETH_ADDR_LEN);
1492                 }
1493             }
1494             icmp->icmp6_cksum = (OVS_FORCE uint16_t)
1495                 csum(icmp, (char *)ofpbuf_tail(b) - (char *)icmp);
1496         }
1497     }
1498     return l4_len;
1499 }
1500
1501 /* Puts into 'b' a packet that flow_extract() would parse as having the given
1502  * 'flow'.
1503  *
1504  * (This is useful only for testing, obviously, and the packet isn't really
1505  * valid. It hasn't got some checksums filled in, for one, and lots of fields
1506  * are just zeroed.) */
1507 void
1508 flow_compose(struct ofpbuf *b, const struct flow *flow)
1509 {
1510     size_t l4_len;
1511
1512     /* eth_compose() sets l3 pointer and makes sure it is 32-bit aligned. */
1513     eth_compose(b, flow->dl_dst, flow->dl_src, ntohs(flow->dl_type), 0);
1514     if (flow->dl_type == htons(FLOW_DL_TYPE_NONE)) {
1515         struct eth_header *eth = ofpbuf_l2(b);
1516         eth->eth_type = htons(ofpbuf_size(b));
1517         return;
1518     }
1519
1520     if (flow->vlan_tci & htons(VLAN_CFI)) {
1521         eth_push_vlan(b, htons(ETH_TYPE_VLAN), flow->vlan_tci);
1522     }
1523
1524     if (flow->dl_type == htons(ETH_TYPE_IP)) {
1525         struct ip_header *ip;
1526
1527         ip = ofpbuf_put_zeros(b, sizeof *ip);
1528         ip->ip_ihl_ver = IP_IHL_VER(5, 4);
1529         ip->ip_tos = flow->nw_tos;
1530         ip->ip_ttl = flow->nw_ttl;
1531         ip->ip_proto = flow->nw_proto;
1532         put_16aligned_be32(&ip->ip_src, flow->nw_src);
1533         put_16aligned_be32(&ip->ip_dst, flow->nw_dst);
1534
1535         if (flow->nw_frag & FLOW_NW_FRAG_ANY) {
1536             ip->ip_frag_off |= htons(IP_MORE_FRAGMENTS);
1537             if (flow->nw_frag & FLOW_NW_FRAG_LATER) {
1538                 ip->ip_frag_off |= htons(100);
1539             }
1540         }
1541
1542         ofpbuf_set_l4(b, ofpbuf_tail(b));
1543
1544         l4_len = flow_compose_l4(b, flow);
1545
1546         ip = ofpbuf_l3(b);
1547         ip->ip_tot_len = htons(b->l4_ofs - b->l3_ofs + l4_len);
1548         ip->ip_csum = csum(ip, sizeof *ip);
1549     } else if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
1550         struct ovs_16aligned_ip6_hdr *nh;
1551
1552         nh = ofpbuf_put_zeros(b, sizeof *nh);
1553         put_16aligned_be32(&nh->ip6_flow, htonl(6 << 28) |
1554                            htonl(flow->nw_tos << 20) | flow->ipv6_label);
1555         nh->ip6_hlim = flow->nw_ttl;
1556         nh->ip6_nxt = flow->nw_proto;
1557
1558         memcpy(&nh->ip6_src, &flow->ipv6_src, sizeof(nh->ip6_src));
1559         memcpy(&nh->ip6_dst, &flow->ipv6_dst, sizeof(nh->ip6_dst));
1560
1561         ofpbuf_set_l4(b, ofpbuf_tail(b));
1562
1563         l4_len = flow_compose_l4(b, flow);
1564
1565         nh = ofpbuf_l3(b);
1566         nh->ip6_plen = htons(l4_len);
1567     } else if (flow->dl_type == htons(ETH_TYPE_ARP) ||
1568                flow->dl_type == htons(ETH_TYPE_RARP)) {
1569         struct arp_eth_header *arp;
1570
1571         arp = ofpbuf_put_zeros(b, sizeof *arp);
1572         ofpbuf_set_l3(b, arp);
1573         arp->ar_hrd = htons(1);
1574         arp->ar_pro = htons(ETH_TYPE_IP);
1575         arp->ar_hln = ETH_ADDR_LEN;
1576         arp->ar_pln = 4;
1577         arp->ar_op = htons(flow->nw_proto);
1578
1579         if (flow->nw_proto == ARP_OP_REQUEST ||
1580             flow->nw_proto == ARP_OP_REPLY) {
1581             put_16aligned_be32(&arp->ar_spa, flow->nw_src);
1582             put_16aligned_be32(&arp->ar_tpa, flow->nw_dst);
1583             memcpy(arp->ar_sha, flow->arp_sha, ETH_ADDR_LEN);
1584             memcpy(arp->ar_tha, flow->arp_tha, ETH_ADDR_LEN);
1585         }
1586     }
1587
1588     if (eth_type_mpls(flow->dl_type)) {
1589         int n;
1590
1591         b->l2_5_ofs = b->l3_ofs;
1592         for (n = 1; n < FLOW_MAX_MPLS_LABELS; n++) {
1593             if (flow->mpls_lse[n - 1] & htonl(MPLS_BOS_MASK)) {
1594                 break;
1595             }
1596         }
1597         while (n > 0) {
1598             push_mpls(b, flow->dl_type, flow->mpls_lse[--n]);
1599         }
1600     }
1601 }
1602 \f
1603 /* Compressed flow. */
1604
1605 static int
1606 miniflow_n_values(const struct miniflow *flow)
1607 {
1608     return count_1bits(flow->map);
1609 }
1610
1611 static uint32_t *
1612 miniflow_alloc_values(struct miniflow *flow, int n)
1613 {
1614     int size = MINIFLOW_VALUES_SIZE(n);
1615
1616     if (size <= sizeof flow->inline_values) {
1617         flow->values_inline = true;
1618         return flow->inline_values;
1619     } else {
1620         COVERAGE_INC(miniflow_malloc);
1621         flow->values_inline = false;
1622         flow->offline_values = xmalloc(size);
1623         return flow->offline_values;
1624     }
1625 }
1626
1627 /* Completes an initialization of 'dst' as a miniflow copy of 'src' begun by
1628  * the caller.  The caller must have already initialized 'dst->map' properly
1629  * to indicate the significant uint32_t elements of 'src'.  'n' must be the
1630  * number of 1-bits in 'dst->map'.
1631  *
1632  * Normally the significant elements are the ones that are non-zero.  However,
1633  * when a miniflow is initialized from a (mini)mask, the values can be zeroes,
1634  * so that the flow and mask always have the same maps.
1635  *
1636  * This function initializes values (either inline if possible or with
1637  * malloc() otherwise) and copies the uint32_t elements of 'src' indicated by
1638  * 'dst->map' into it. */
1639 static void
1640 miniflow_init__(struct miniflow *dst, const struct flow *src, int n)
1641 {
1642     const uint32_t *src_u32 = (const uint32_t *) src;
1643     uint32_t *dst_u32 = miniflow_alloc_values(dst, n);
1644     uint64_t map;
1645
1646     for (map = dst->map; map; map = zero_rightmost_1bit(map)) {
1647         *dst_u32++ = src_u32[raw_ctz(map)];
1648     }
1649 }
1650
1651 /* Initializes 'dst' as a copy of 'src'.  The caller must eventually free 'dst'
1652  * with miniflow_destroy().
1653  * Always allocates offline storage. */
1654 void
1655 miniflow_init(struct miniflow *dst, const struct flow *src)
1656 {
1657     const uint32_t *src_u32 = (const uint32_t *) src;
1658     unsigned int i;
1659     int n;
1660
1661     /* Initialize dst->map, counting the number of nonzero elements. */
1662     n = 0;
1663     dst->map = 0;
1664
1665     for (i = 0; i < FLOW_U32S; i++) {
1666         if (src_u32[i]) {
1667             dst->map |= UINT64_C(1) << i;
1668             n++;
1669         }
1670     }
1671
1672     miniflow_init__(dst, src, n);
1673 }
1674
1675 /* Initializes 'dst' as a copy of 'src', using 'mask->map' as 'dst''s map.  The
1676  * caller must eventually free 'dst' with miniflow_destroy(). */
1677 void
1678 miniflow_init_with_minimask(struct miniflow *dst, const struct flow *src,
1679                             const struct minimask *mask)
1680 {
1681     dst->map = mask->masks.map;
1682     miniflow_init__(dst, src, miniflow_n_values(dst));
1683 }
1684
1685 /* Initializes 'dst' as a copy of 'src'.  The caller must eventually free 'dst'
1686  * with miniflow_destroy(). */
1687 void
1688 miniflow_clone(struct miniflow *dst, const struct miniflow *src)
1689 {
1690     int size = MINIFLOW_VALUES_SIZE(miniflow_n_values(src));
1691     uint32_t *values;
1692
1693     dst->map = src->map;
1694     if (size <= sizeof dst->inline_values) {
1695         dst->values_inline = true;
1696         values = dst->inline_values;
1697     } else {
1698         dst->values_inline = false;
1699         COVERAGE_INC(miniflow_malloc);
1700         dst->offline_values = xmalloc(size);
1701         values = dst->offline_values;
1702     }
1703     memcpy(values, miniflow_get_values(src), size);
1704 }
1705
1706 /* Initializes 'dst' as a copy of 'src'.  The caller must have allocated
1707  * 'dst' to have inline space all data in 'src'. */
1708 void
1709 miniflow_clone_inline(struct miniflow *dst, const struct miniflow *src,
1710                       size_t n_values)
1711 {
1712     dst->values_inline = true;
1713     dst->map = src->map;
1714     memcpy(dst->inline_values, miniflow_get_values(src),
1715            MINIFLOW_VALUES_SIZE(n_values));
1716 }
1717
1718 /* Initializes 'dst' with the data in 'src', destroying 'src'.
1719  * The caller must eventually free 'dst' with miniflow_destroy().
1720  * 'dst' must be regularly sized miniflow, but 'src' can have
1721  * storage for more than the default MINI_N_INLINE inline
1722  * values. */
1723 void
1724 miniflow_move(struct miniflow *dst, struct miniflow *src)
1725 {
1726     int size = MINIFLOW_VALUES_SIZE(miniflow_n_values(src));
1727
1728     dst->map = src->map;
1729     if (size <= sizeof dst->inline_values) {
1730         dst->values_inline = true;
1731         memcpy(dst->inline_values, miniflow_get_values(src), size);
1732         miniflow_destroy(src);
1733     } else if (src->values_inline) {
1734         dst->values_inline = false;
1735         COVERAGE_INC(miniflow_malloc);
1736         dst->offline_values = xmalloc(size);
1737         memcpy(dst->offline_values, src->inline_values, size);
1738     } else {
1739         dst->values_inline = false;
1740         dst->offline_values = src->offline_values;
1741     }
1742 }
1743
1744 /* Frees any memory owned by 'flow'.  Does not free the storage in which 'flow'
1745  * itself resides; the caller is responsible for that. */
1746 void
1747 miniflow_destroy(struct miniflow *flow)
1748 {
1749     if (!flow->values_inline) {
1750         free(flow->offline_values);
1751     }
1752 }
1753
1754 /* Initializes 'dst' as a copy of 'src'. */
1755 void
1756 miniflow_expand(const struct miniflow *src, struct flow *dst)
1757 {
1758     memset(dst, 0, sizeof *dst);
1759     flow_union_with_miniflow(dst, src);
1760 }
1761
1762 /* Returns the uint32_t that would be at byte offset '4 * u32_ofs' if 'flow'
1763  * were expanded into a "struct flow". */
1764 static uint32_t
1765 miniflow_get(const struct miniflow *flow, unsigned int u32_ofs)
1766 {
1767     return (flow->map & UINT64_C(1) << u32_ofs)
1768         ? *(miniflow_get_u32_values(flow) +
1769             count_1bits(flow->map & ((UINT64_C(1) << u32_ofs) - 1)))
1770         : 0;
1771 }
1772
1773 /* Returns true if 'a' and 'b' are the same flow, false otherwise.  */
1774 bool
1775 miniflow_equal(const struct miniflow *a, const struct miniflow *b)
1776 {
1777     const uint32_t *ap = miniflow_get_u32_values(a);
1778     const uint32_t *bp = miniflow_get_u32_values(b);
1779     const uint64_t a_map = a->map;
1780     const uint64_t b_map = b->map;
1781
1782     if (OVS_LIKELY(a_map == b_map)) {
1783         int count = miniflow_n_values(a);
1784
1785         return !memcmp(ap, bp, count * sizeof *ap);
1786     } else {
1787         uint64_t map;
1788
1789         for (map = a_map | b_map; map; map = zero_rightmost_1bit(map)) {
1790             uint64_t bit = rightmost_1bit(map);
1791             uint64_t a_value = a_map & bit ? *ap++ : 0;
1792             uint64_t b_value = b_map & bit ? *bp++ : 0;
1793
1794             if (a_value != b_value) {
1795                 return false;
1796             }
1797         }
1798     }
1799
1800     return true;
1801 }
1802
1803 /* Returns true if 'a' and 'b' are equal at the places where there are 1-bits
1804  * in 'mask', false if they differ. */
1805 bool
1806 miniflow_equal_in_minimask(const struct miniflow *a, const struct miniflow *b,
1807                            const struct minimask *mask)
1808 {
1809     const uint32_t *p = miniflow_get_u32_values(&mask->masks);
1810     uint64_t map;
1811
1812     for (map = mask->masks.map; map; map = zero_rightmost_1bit(map)) {
1813         int ofs = raw_ctz(map);
1814
1815         if ((miniflow_get(a, ofs) ^ miniflow_get(b, ofs)) & *p++) {
1816             return false;
1817         }
1818     }
1819
1820     return true;
1821 }
1822
1823 /* Returns true if 'a' and 'b' are equal at the places where there are 1-bits
1824  * in 'mask', false if they differ. */
1825 bool
1826 miniflow_equal_flow_in_minimask(const struct miniflow *a, const struct flow *b,
1827                                 const struct minimask *mask)
1828 {
1829     const uint32_t *b_u32 = (const uint32_t *) b;
1830     const uint32_t *p = miniflow_get_u32_values(&mask->masks);
1831     uint64_t map;
1832
1833     for (map = mask->masks.map; map; map = zero_rightmost_1bit(map)) {
1834         int ofs = raw_ctz(map);
1835
1836         if ((miniflow_get(a, ofs) ^ b_u32[ofs]) & *p++) {
1837             return false;
1838         }
1839     }
1840
1841     return true;
1842 }
1843
1844 \f
1845 /* Initializes 'dst' as a copy of 'src'.  The caller must eventually free 'dst'
1846  * with minimask_destroy(). */
1847 void
1848 minimask_init(struct minimask *mask, const struct flow_wildcards *wc)
1849 {
1850     miniflow_init(&mask->masks, &wc->masks);
1851 }
1852
1853 /* Initializes 'dst' as a copy of 'src'.  The caller must eventually free 'dst'
1854  * with minimask_destroy(). */
1855 void
1856 minimask_clone(struct minimask *dst, const struct minimask *src)
1857 {
1858     miniflow_clone(&dst->masks, &src->masks);
1859 }
1860
1861 /* Initializes 'dst' with the data in 'src', destroying 'src'.
1862  * The caller must eventually free 'dst' with minimask_destroy(). */
1863 void
1864 minimask_move(struct minimask *dst, struct minimask *src)
1865 {
1866     miniflow_move(&dst->masks, &src->masks);
1867 }
1868
1869 /* Initializes 'dst_' as the bit-wise "and" of 'a_' and 'b_'.
1870  *
1871  * The caller must provide room for FLOW_U32S "uint32_t"s in 'storage', for use
1872  * by 'dst_'.  The caller must *not* free 'dst_' with minimask_destroy(). */
1873 void
1874 minimask_combine(struct minimask *dst_,
1875                  const struct minimask *a_, const struct minimask *b_,
1876                  uint32_t storage[FLOW_U32S])
1877 {
1878     struct miniflow *dst = &dst_->masks;
1879     uint32_t *dst_values = storage;
1880     const struct miniflow *a = &a_->masks;
1881     const struct miniflow *b = &b_->masks;
1882     uint64_t map;
1883     int n = 0;
1884
1885     dst->values_inline = false;
1886     dst->offline_values = storage;
1887
1888     dst->map = 0;
1889     for (map = a->map & b->map; map; map = zero_rightmost_1bit(map)) {
1890         int ofs = raw_ctz(map);
1891         uint32_t mask = miniflow_get(a, ofs) & miniflow_get(b, ofs);
1892
1893         if (mask) {
1894             dst->map |= rightmost_1bit(map);
1895             dst_values[n++] = mask;
1896         }
1897     }
1898 }
1899
1900 /* Frees any memory owned by 'mask'.  Does not free the storage in which 'mask'
1901  * itself resides; the caller is responsible for that. */
1902 void
1903 minimask_destroy(struct minimask *mask)
1904 {
1905     miniflow_destroy(&mask->masks);
1906 }
1907
1908 /* Initializes 'dst' as a copy of 'src'. */
1909 void
1910 minimask_expand(const struct minimask *mask, struct flow_wildcards *wc)
1911 {
1912     miniflow_expand(&mask->masks, &wc->masks);
1913 }
1914
1915 /* Returns the uint32_t that would be at byte offset '4 * u32_ofs' if 'mask'
1916  * were expanded into a "struct flow_wildcards". */
1917 uint32_t
1918 minimask_get(const struct minimask *mask, unsigned int u32_ofs)
1919 {
1920     return miniflow_get(&mask->masks, u32_ofs);
1921 }
1922
1923 /* Returns true if 'a' and 'b' are the same flow mask, false otherwise.  */
1924 bool
1925 minimask_equal(const struct minimask *a, const struct minimask *b)
1926 {
1927     return miniflow_equal(&a->masks, &b->masks);
1928 }
1929
1930 /* Returns true if at least one bit matched by 'b' is wildcarded by 'a',
1931  * false otherwise. */
1932 bool
1933 minimask_has_extra(const struct minimask *a, const struct minimask *b)
1934 {
1935     const uint32_t *p = miniflow_get_u32_values(&b->masks);
1936     uint64_t map;
1937
1938     for (map = b->masks.map; map; map = zero_rightmost_1bit(map)) {
1939         uint32_t a_u32 = minimask_get(a, raw_ctz(map));
1940         uint32_t b_u32 = *p++;
1941
1942         if ((a_u32 & b_u32) != b_u32) {
1943             return true;
1944         }
1945     }
1946
1947     return false;
1948 }