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