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