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