d8632ff97feadb229417699c18f9c24a758c9cc7
[cascardo/ovs.git] / lib / flow.h
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 #ifndef FLOW_H
17 #define FLOW_H 1
18
19 #include <sys/types.h>
20 #include <netinet/in.h>
21 #include <stdbool.h>
22 #include <stdint.h>
23 #include <string.h>
24 #include "bitmap.h"
25 #include "byte-order.h"
26 #include "openflow/nicira-ext.h"
27 #include "openflow/openflow.h"
28 #include "packets.h"
29 #include "hash.h"
30 #include "util.h"
31
32 struct dpif_flow_stats;
33 struct ds;
34 struct flow_wildcards;
35 struct minimask;
36 struct dp_packet;
37 struct pkt_metadata;
38 struct match;
39
40 /* This sequence number should be incremented whenever anything involving flows
41  * or the wildcarding of flows changes.  This will cause build assertion
42  * failures in places which likely need to be updated. */
43 #define FLOW_WC_SEQ 33
44
45 /* Number of Open vSwitch extension 32-bit registers. */
46 #define FLOW_N_REGS 8
47 BUILD_ASSERT_DECL(FLOW_N_REGS <= NXM_NX_MAX_REGS);
48 BUILD_ASSERT_DECL(FLOW_N_REGS % 2 == 0); /* Even. */
49
50 /* Number of OpenFlow 1.5+ 64-bit registers.
51  *
52  * Each of these overlays a pair of Open vSwitch 32-bit registers, so there
53  * are half as many of them.*/
54 #define FLOW_N_XREGS (FLOW_N_REGS / 2)
55
56 /* Used for struct flow's dl_type member for frames that have no Ethernet
57  * type, that is, pure 802.2 frames. */
58 #define FLOW_DL_TYPE_NONE 0x5ff
59
60 /* Fragment bits, used for IPv4 and IPv6, always zero for non-IP flows. */
61 #define FLOW_NW_FRAG_ANY   (1 << 0) /* Set for any IP frag. */
62 #define FLOW_NW_FRAG_LATER (1 << 1) /* Set for IP frag with nonzero offset. */
63 #define FLOW_NW_FRAG_MASK  (FLOW_NW_FRAG_ANY | FLOW_NW_FRAG_LATER)
64
65 BUILD_ASSERT_DECL(FLOW_NW_FRAG_ANY == NX_IP_FRAG_ANY);
66 BUILD_ASSERT_DECL(FLOW_NW_FRAG_LATER == NX_IP_FRAG_LATER);
67
68 BUILD_ASSERT_DECL(FLOW_TNL_F_OAM == NX_TUN_FLAG_OAM);
69
70 const char *flow_tun_flag_to_string(uint32_t flags);
71
72 /* Maximum number of supported MPLS labels. */
73 #define FLOW_MAX_MPLS_LABELS 3
74
75 /*
76  * A flow in the network.
77  *
78  * Must be initialized to all zeros to make any compiler-induced padding
79  * zeroed.  Helps also in keeping unused fields (such as mutually exclusive
80  * IPv4 and IPv6 addresses) zeroed out.
81  *
82  * The meaning of 'in_port' is context-dependent.  In most cases, it is a
83  * 16-bit OpenFlow 1.0 port number.  In the software datapath interface (dpif)
84  * layer and its implementations (e.g. dpif-netlink, dpif-netdev), it is
85  * instead a 32-bit datapath port number.
86  *
87  * The fields are organized in four segments to facilitate staged lookup, where
88  * lower layer fields are first used to determine if the later fields need to
89  * be looked at.  This enables better wildcarding for datapath flows.
90  *
91  * NOTE: Order of the fields is significant, any change in the order must be
92  * reflected in miniflow_extract()!
93  */
94 struct flow {
95     /* Metadata */
96     struct flow_tnl tunnel;     /* Encapsulating tunnel parameters. */
97     ovs_be64 metadata;          /* OpenFlow Metadata. */
98     uint32_t regs[FLOW_N_REGS]; /* Registers. */
99     uint32_t skb_priority;      /* Packet priority for QoS. */
100     uint32_t pkt_mark;          /* Packet mark. */
101     uint32_t dp_hash;           /* Datapath computed hash value. The exact
102                                  * computation is opaque to the user space. */
103     union flow_in_port in_port; /* Input port.*/
104     uint32_t recirc_id;         /* Must be exact match. */
105     uint32_t conj_id;           /* Conjunction ID. */
106     ofp_port_t actset_output;   /* Output port in action set. */
107     uint8_t pad1[6];            /* Pad to 64 bits. */
108
109     /* L2, Order the same as in the Ethernet header! (64-bit aligned) */
110     struct eth_addr dl_dst;     /* Ethernet destination address. */
111     struct eth_addr dl_src;     /* Ethernet source address. */
112     ovs_be16 dl_type;           /* Ethernet frame type. */
113     ovs_be16 vlan_tci;          /* If 802.1Q, TCI | VLAN_CFI; otherwise 0. */
114     ovs_be32 mpls_lse[ROUND_UP(FLOW_MAX_MPLS_LABELS, 2)]; /* MPLS label stack
115                                                              (with padding). */
116     /* L3 (64-bit aligned) */
117     ovs_be32 nw_src;            /* IPv4 source address. */
118     ovs_be32 nw_dst;            /* IPv4 destination address. */
119     struct in6_addr ipv6_src;   /* IPv6 source address. */
120     struct in6_addr ipv6_dst;   /* IPv6 destination address. */
121     ovs_be32 ipv6_label;        /* IPv6 flow label. */
122     uint8_t nw_frag;            /* FLOW_FRAG_* flags. */
123     uint8_t nw_tos;             /* IP ToS (including DSCP and ECN). */
124     uint8_t nw_ttl;             /* IP TTL/Hop Limit. */
125     uint8_t nw_proto;           /* IP protocol or low 8 bits of ARP opcode. */
126     struct in6_addr nd_target;  /* IPv6 neighbor discovery (ND) target. */
127     struct eth_addr arp_sha;    /* ARP/ND source hardware address. */
128     struct eth_addr arp_tha;    /* ARP/ND target hardware address. */
129     ovs_be16 tcp_flags;         /* TCP flags. With L3 to avoid matching L4. */
130     ovs_be16 pad2;              /* Pad to 64 bits. */
131
132     /* L4 (64-bit aligned) */
133     ovs_be16 tp_src;            /* TCP/UDP/SCTP source port. */
134     ovs_be16 tp_dst;            /* TCP/UDP/SCTP destination port. */
135     ovs_be32 igmp_group_ip4;    /* IGMP group IPv4 address.
136                                  * Keep last for BUILD_ASSERT_DECL below. */
137 };
138 BUILD_ASSERT_DECL(sizeof(struct flow) % sizeof(uint64_t) == 0);
139 BUILD_ASSERT_DECL(sizeof(struct flow_tnl) % sizeof(uint64_t) == 0);
140
141 #define FLOW_U64S (sizeof(struct flow) / sizeof(uint64_t))
142
143 /* Some flow fields are mutually exclusive or only appear within the flow
144  * pipeline.  IPv6 headers are bigger than IPv4 and MPLS, and IPv6 ND packets
145  * are bigger than TCP,UDP and IGMP packets. */
146 #define FLOW_MAX_PACKET_U64S (FLOW_U64S                                   \
147     /* Unused in datapath */  - FLOW_U64_SIZE(regs)                       \
148                               - FLOW_U64_SIZE(metadata)                   \
149     /* L2.5/3 */              - FLOW_U64_SIZE(nw_src)  /* incl. nw_dst */ \
150                               - FLOW_U64_SIZE(mpls_lse)                   \
151     /* L4 */                  - FLOW_U64_SIZE(tp_src)                     \
152                              )
153
154 /* Remember to update FLOW_WC_SEQ when changing 'struct flow'. */
155 BUILD_ASSERT_DECL(offsetof(struct flow, igmp_group_ip4) + sizeof(uint32_t)
156                   == sizeof(struct flow_tnl) + 192
157                   && FLOW_WC_SEQ == 33);
158
159 /* Incremental points at which flow classification may be performed in
160  * segments.
161  * This is located here since this is dependent on the structure of the
162  * struct flow defined above:
163  * Each offset must be on a distinct, successive U64 boundary strictly
164  * within the struct flow. */
165 enum {
166     FLOW_SEGMENT_1_ENDS_AT = offsetof(struct flow, dl_dst),
167     FLOW_SEGMENT_2_ENDS_AT = offsetof(struct flow, nw_src),
168     FLOW_SEGMENT_3_ENDS_AT = offsetof(struct flow, tp_src),
169 };
170 BUILD_ASSERT_DECL(FLOW_SEGMENT_1_ENDS_AT % sizeof(uint64_t) == 0);
171 BUILD_ASSERT_DECL(FLOW_SEGMENT_2_ENDS_AT % sizeof(uint64_t) == 0);
172 BUILD_ASSERT_DECL(FLOW_SEGMENT_3_ENDS_AT % sizeof(uint64_t) == 0);
173 BUILD_ASSERT_DECL(                     0 < FLOW_SEGMENT_1_ENDS_AT);
174 BUILD_ASSERT_DECL(FLOW_SEGMENT_1_ENDS_AT < FLOW_SEGMENT_2_ENDS_AT);
175 BUILD_ASSERT_DECL(FLOW_SEGMENT_2_ENDS_AT < FLOW_SEGMENT_3_ENDS_AT);
176 BUILD_ASSERT_DECL(FLOW_SEGMENT_3_ENDS_AT < sizeof(struct flow));
177
178 extern const uint8_t flow_segment_u64s[];
179
180 #define FLOW_U64_OFFSET(FIELD)                          \
181     (offsetof(struct flow, FIELD) / sizeof(uint64_t))
182 #define FLOW_U64_OFFREM(FIELD)                          \
183     (offsetof(struct flow, FIELD) % sizeof(uint64_t))
184
185 /* Number of 64-bit units spanned by a 'FIELD'. */
186 #define FLOW_U64_SIZE(FIELD)                                            \
187     DIV_ROUND_UP(FLOW_U64_OFFREM(FIELD) + MEMBER_SIZEOF(struct flow, FIELD), \
188                  sizeof(uint64_t))
189
190 void flow_extract(struct dp_packet *, struct flow *);
191
192 void flow_zero_wildcards(struct flow *, const struct flow_wildcards *);
193 void flow_unwildcard_tp_ports(const struct flow *, struct flow_wildcards *);
194 void flow_get_metadata(const struct flow *, struct match *flow_metadata);
195
196 char *flow_to_string(const struct flow *);
197 void format_flags(struct ds *ds, const char *(*bit_to_string)(uint32_t),
198                   uint32_t flags, char del);
199 void format_flags_masked(struct ds *ds, const char *name,
200                          const char *(*bit_to_string)(uint32_t),
201                          uint32_t flags, uint32_t mask, uint32_t max_mask);
202 int parse_flags(const char *s, const char *(*bit_to_string)(uint32_t),
203                 char end, const char *field_name, char **res_string,
204                 uint32_t *res_flags, uint32_t allowed, uint32_t *res_mask);
205
206 void flow_format(struct ds *, const struct flow *);
207 void flow_print(FILE *, const struct flow *);
208 static inline int flow_compare_3way(const struct flow *, const struct flow *);
209 static inline bool flow_equal(const struct flow *, const struct flow *);
210 static inline size_t flow_hash(const struct flow *, uint32_t basis);
211
212 void flow_set_dl_vlan(struct flow *, ovs_be16 vid);
213 void flow_set_vlan_vid(struct flow *, ovs_be16 vid);
214 void flow_set_vlan_pcp(struct flow *, uint8_t pcp);
215
216 int flow_count_mpls_labels(const struct flow *, struct flow_wildcards *);
217 int flow_count_common_mpls_labels(const struct flow *a, int an,
218                                   const struct flow *b, int bn,
219                                   struct flow_wildcards *wc);
220 void flow_push_mpls(struct flow *, int n, ovs_be16 mpls_eth_type,
221                     struct flow_wildcards *);
222 bool flow_pop_mpls(struct flow *, int n, ovs_be16 eth_type,
223                    struct flow_wildcards *);
224 void flow_set_mpls_label(struct flow *, int idx, ovs_be32 label);
225 void flow_set_mpls_ttl(struct flow *, int idx, uint8_t ttl);
226 void flow_set_mpls_tc(struct flow *, int idx, uint8_t tc);
227 void flow_set_mpls_bos(struct flow *, int idx, uint8_t stack);
228 void flow_set_mpls_lse(struct flow *, int idx, ovs_be32 lse);
229
230 void flow_compose(struct dp_packet *, const struct flow *);
231
232 static inline uint64_t
233 flow_get_xreg(const struct flow *flow, int idx)
234 {
235     return ((uint64_t) flow->regs[idx * 2] << 32) | flow->regs[idx * 2 + 1];
236 }
237
238 static inline void
239 flow_set_xreg(struct flow *flow, int idx, uint64_t value)
240 {
241     flow->regs[idx * 2] = value >> 32;
242     flow->regs[idx * 2 + 1] = value;
243 }
244
245 static inline int
246 flow_compare_3way(const struct flow *a, const struct flow *b)
247 {
248     return memcmp(a, b, sizeof *a);
249 }
250
251 static inline bool
252 flow_equal(const struct flow *a, const struct flow *b)
253 {
254     return !flow_compare_3way(a, b);
255 }
256
257 static inline size_t
258 flow_hash(const struct flow *flow, uint32_t basis)
259 {
260     return hash_words64((const uint64_t *)flow,
261                         sizeof *flow / sizeof(uint64_t), basis);
262 }
263
264 static inline uint16_t
265 ofp_to_u16(ofp_port_t ofp_port)
266 {
267     return (OVS_FORCE uint16_t) ofp_port;
268 }
269
270 static inline uint32_t
271 odp_to_u32(odp_port_t odp_port)
272 {
273     return (OVS_FORCE uint32_t) odp_port;
274 }
275
276 static inline uint32_t
277 ofp11_to_u32(ofp11_port_t ofp11_port)
278 {
279     return (OVS_FORCE uint32_t) ofp11_port;
280 }
281
282 static inline ofp_port_t
283 u16_to_ofp(uint16_t port)
284 {
285     return OFP_PORT_C(port);
286 }
287
288 static inline odp_port_t
289 u32_to_odp(uint32_t port)
290 {
291     return ODP_PORT_C(port);
292 }
293
294 static inline ofp11_port_t
295 u32_to_ofp11(uint32_t port)
296 {
297     return OFP11_PORT_C(port);
298 }
299
300 static inline uint32_t
301 hash_ofp_port(ofp_port_t ofp_port)
302 {
303     return hash_int(ofp_to_u16(ofp_port), 0);
304 }
305
306 static inline uint32_t
307 hash_odp_port(odp_port_t odp_port)
308 {
309     return hash_int(odp_to_u32(odp_port), 0);
310 }
311 \f
312 /* Wildcards for a flow.
313  *
314  * A 1-bit in each bit in 'masks' indicates that the corresponding bit of
315  * the flow is significant (must match).  A 0-bit indicates that the
316  * corresponding bit of the flow is wildcarded (need not match). */
317 struct flow_wildcards {
318     struct flow masks;
319 };
320
321 #define WC_MASK_FIELD(WC, FIELD) \
322     memset(&(WC)->masks.FIELD, 0xff, sizeof (WC)->masks.FIELD)
323 #define WC_MASK_FIELD_MASK(WC, FIELD, MASK)     \
324     ((WC)->masks.FIELD |= (MASK))
325 #define WC_UNMASK_FIELD(WC, FIELD) \
326     memset(&(WC)->masks.FIELD, 0, sizeof (WC)->masks.FIELD)
327
328 void flow_wildcards_init_catchall(struct flow_wildcards *);
329
330 void flow_wildcards_init_for_packet(struct flow_wildcards *,
331                                     const struct flow *);
332
333 void flow_wildcards_clear_non_packet_fields(struct flow_wildcards *);
334
335 bool flow_wildcards_is_catchall(const struct flow_wildcards *);
336
337 void flow_wildcards_set_reg_mask(struct flow_wildcards *,
338                                  int idx, uint32_t mask);
339 void flow_wildcards_set_xreg_mask(struct flow_wildcards *,
340                                   int idx, uint64_t mask);
341
342 void flow_wildcards_and(struct flow_wildcards *dst,
343                         const struct flow_wildcards *src1,
344                         const struct flow_wildcards *src2);
345 void flow_wildcards_or(struct flow_wildcards *dst,
346                        const struct flow_wildcards *src1,
347                        const struct flow_wildcards *src2);
348 bool flow_wildcards_has_extra(const struct flow_wildcards *,
349                               const struct flow_wildcards *);
350 uint32_t flow_wildcards_hash(const struct flow_wildcards *, uint32_t basis);
351 bool flow_wildcards_equal(const struct flow_wildcards *,
352                           const struct flow_wildcards *);
353 uint32_t flow_hash_5tuple(const struct flow *flow, uint32_t basis);
354 uint32_t flow_hash_symmetric_l4(const struct flow *flow, uint32_t basis);
355 uint32_t flow_hash_symmetric_l3l4(const struct flow *flow, uint32_t basis,
356                          bool inc_udp_ports );
357
358 /* Initialize a flow with random fields that matter for nx_hash_fields. */
359 void flow_random_hash_fields(struct flow *);
360 void flow_mask_hash_fields(const struct flow *, struct flow_wildcards *,
361                            enum nx_hash_fields);
362 uint32_t flow_hash_fields(const struct flow *, enum nx_hash_fields,
363                           uint16_t basis);
364 const char *flow_hash_fields_to_str(enum nx_hash_fields);
365 bool flow_hash_fields_valid(enum nx_hash_fields);
366
367 uint32_t flow_hash_in_wildcards(const struct flow *,
368                                 const struct flow_wildcards *,
369                                 uint32_t basis);
370
371 bool flow_equal_except(const struct flow *a, const struct flow *b,
372                        const struct flow_wildcards *);
373 \f
374 /* Bitmap for flow values.  For each 1-bit the corresponding flow value is
375  * explicitly specified, other values are zeroes.
376  *
377  * map_t must be wide enough to hold any member of struct flow. */
378 typedef unsigned long long map_t;
379 #define MAP_T_BITS (sizeof(map_t) * CHAR_BIT)
380 #define MAP_1 (map_t)1
381 #define MAP_MAX TYPE_MAXIMUM(map_t)
382
383 #define MAP_IS_SET(MAP, IDX) ((MAP) & (MAP_1 << (IDX)))
384
385 /* Iterate through the indices of all 1-bits in 'MAP'. */
386 #define MAP_FOR_EACH_INDEX(IDX, MAP)            \
387     ULLONG_FOR_EACH_1(IDX, MAP)
388
389 #define FLOWMAP_UNITS DIV_ROUND_UP(FLOW_U64S, MAP_T_BITS)
390
391 struct flowmap {
392     map_t bits[FLOWMAP_UNITS];
393 };
394
395 #define FLOWMAP_EMPTY_INITIALIZER { { 0 } }
396
397 static inline void flowmap_init(struct flowmap *);
398 static inline bool flowmap_equal(struct flowmap, struct flowmap);
399 static inline bool flowmap_is_set(const struct flowmap *, size_t idx);
400 static inline bool flowmap_are_set(const struct flowmap *, size_t idx,
401                                    unsigned int n_bits);
402 static inline void flowmap_set(struct flowmap *, size_t idx,
403                                unsigned int n_bits);
404 static inline void flowmap_clear(struct flowmap *, size_t idx,
405                                  unsigned int n_bits);
406 static inline struct flowmap flowmap_or(struct flowmap, struct flowmap);
407 static inline struct flowmap flowmap_and(struct flowmap, struct flowmap);
408 static inline bool flowmap_is_empty(struct flowmap);
409 static inline unsigned int flowmap_n_1bits(struct flowmap);
410
411 #define FLOWMAP_HAS_FIELD(FM, FIELD)                                    \
412     flowmap_are_set(FM, FLOW_U64_OFFSET(FIELD), FLOW_U64_SIZE(FIELD))
413
414 #define FLOWMAP_SET(FM, FIELD)                                      \
415     flowmap_set(FM, FLOW_U64_OFFSET(FIELD), FLOW_U64_SIZE(FIELD))
416
417 #define FLOWMAP_SET__(FM, FIELD, SIZE)                  \
418     flowmap_set(FM, FLOW_U64_OFFSET(FIELD),             \
419                 DIV_ROUND_UP(SIZE, sizeof(uint64_t)))
420
421 /* XXX: Only works for full 64-bit units. */
422 #define FLOWMAP_CLEAR(FM, FIELD)                                        \
423     BUILD_ASSERT_DECL(FLOW_U64_OFFREM(FIELD) == 0);                     \
424     BUILD_ASSERT_DECL(sizeof(((struct flow *)0)->FIELD) % sizeof(uint64_t) == 0); \
425     flowmap_clear(FM, FLOW_U64_OFFSET(FIELD), FLOW_U64_SIZE(FIELD))
426
427 /* Iterate through all units in 'FMAP'. */
428 #define FLOWMAP_FOR_EACH_UNIT(UNIT)                     \
429     for ((UNIT) = 0; (UNIT) < FLOWMAP_UNITS; (UNIT)++)
430
431 /* Iterate through all map units in 'FMAP'. */
432 #define FLOWMAP_FOR_EACH_MAP(MAP, FLOWMAP)                              \
433     for (size_t unit__ = 0;                                       \
434          unit__ < FLOWMAP_UNITS && ((MAP) = (FLOWMAP).bits[unit__], true); \
435          unit__++)
436
437 struct flowmap_aux;
438 static inline bool flowmap_next_index(struct flowmap_aux *, size_t *idx);
439
440 #define FLOWMAP_AUX_INITIALIZER(FLOWMAP) { .unit = 0, .map = (FLOWMAP) }
441
442 /* Iterate through all struct flow u64 indices specified by 'MAP'.  This is a
443  * slower but easier version of the FLOWMAP_FOR_EACH_MAP() &
444  * MAP_FOR_EACH_INDEX() combination. */
445 #define FLOWMAP_FOR_EACH_INDEX(IDX, MAP)                            \
446     for (struct flowmap_aux aux__ = FLOWMAP_AUX_INITIALIZER(MAP);   \
447          flowmap_next_index(&aux__, &(IDX));)
448
449 /* Flowmap inline implementations. */
450 static inline void
451 flowmap_init(struct flowmap *fm)
452 {
453     memset(fm, 0, sizeof *fm);
454 }
455
456 static inline bool
457 flowmap_equal(struct flowmap a, struct flowmap b)
458 {
459     return !memcmp(&a, &b, sizeof a);
460 }
461
462 static inline bool
463 flowmap_is_set(const struct flowmap *fm, size_t idx)
464 {
465     return (fm->bits[idx / MAP_T_BITS] & (MAP_1 << (idx % MAP_T_BITS))) != 0;
466 }
467
468 /* Returns 'true' if any of the 'n_bits' bits starting at 'idx' are set in
469  * 'fm'.  'n_bits' can be at most MAP_T_BITS. */
470 static inline bool
471 flowmap_are_set(const struct flowmap *fm, size_t idx, unsigned int n_bits)
472 {
473     map_t n_bits_mask = (MAP_1 << n_bits) - 1;
474     size_t unit = idx / MAP_T_BITS;
475
476     idx %= MAP_T_BITS;
477
478     if (fm->bits[unit] & (n_bits_mask << idx)) {
479         return true;
480     }
481     /* The seemingly unnecessary bounds check on 'unit' is a workaround for a
482      * false-positive array out of bounds error by GCC 4.9. */
483     if (unit + 1 < FLOWMAP_UNITS && idx + n_bits > MAP_T_BITS) {
484         /* Check the remaining bits from the next unit. */
485         return fm->bits[unit + 1] & (n_bits_mask >> (MAP_T_BITS - idx));
486     }
487     return false;
488 }
489
490 /* Set the 'n_bits' consecutive bits in 'fm', starting at bit 'idx'.
491  * 'n_bits' can be at most MAP_T_BITS. */
492 static inline void
493 flowmap_set(struct flowmap *fm, size_t idx, unsigned int n_bits)
494 {
495     map_t n_bits_mask = (MAP_1 << n_bits) - 1;
496     size_t unit = idx / MAP_T_BITS;
497
498     idx %= MAP_T_BITS;
499
500     fm->bits[unit] |= n_bits_mask << idx;
501     /* The seemingly unnecessary bounds check on 'unit' is a workaround for a
502      * false-positive array out of bounds error by GCC 4.9. */
503     if (unit + 1 < FLOWMAP_UNITS && idx + n_bits > MAP_T_BITS) {
504         /* 'MAP_T_BITS - idx' bits were set on 'unit', set the remaining
505          * bits from the next unit. */
506         fm->bits[unit + 1] |= n_bits_mask >> (MAP_T_BITS - idx);
507     }
508 }
509
510 /* Clears the 'n_bits' consecutive bits in 'fm', starting at bit 'idx'.
511  * 'n_bits' can be at most MAP_T_BITS. */
512 static inline void
513 flowmap_clear(struct flowmap *fm, size_t idx, unsigned int n_bits)
514 {
515     map_t n_bits_mask = (MAP_1 << n_bits) - 1;
516     size_t unit = idx / MAP_T_BITS;
517
518     idx %= MAP_T_BITS;
519
520     fm->bits[unit] &= ~(n_bits_mask << idx);
521     /* The seemingly unnecessary bounds check on 'unit' is a workaround for a
522      * false-positive array out of bounds error by GCC 4.9. */
523     if (unit + 1 < FLOWMAP_UNITS && idx + n_bits > MAP_T_BITS) {
524         /* 'MAP_T_BITS - idx' bits were cleared on 'unit', clear the
525          * remaining bits from the next unit. */
526         fm->bits[unit + 1] &= ~(n_bits_mask >> (MAP_T_BITS - idx));
527     }
528 }
529
530 /* OR the bits in the flowmaps. */
531 static inline struct flowmap
532 flowmap_or(struct flowmap a, struct flowmap b)
533 {
534     struct flowmap map;
535     size_t unit;
536
537     FLOWMAP_FOR_EACH_UNIT (unit) {
538         map.bits[unit] = a.bits[unit] | b.bits[unit];
539     }
540     return map;
541 }
542
543 /* AND the bits in the flowmaps. */
544 static inline struct flowmap
545 flowmap_and(struct flowmap a, struct flowmap b)
546 {
547     struct flowmap map;
548     size_t unit;
549
550     FLOWMAP_FOR_EACH_UNIT (unit) {
551         map.bits[unit] = a.bits[unit] & b.bits[unit];
552     }
553     return map;
554 }
555
556 static inline bool
557 flowmap_is_empty(struct flowmap fm)
558 {
559     map_t map;
560
561     FLOWMAP_FOR_EACH_MAP (map, fm) {
562         if (map) {
563             return false;
564         }
565     }
566     return true;
567 }
568
569 static inline unsigned int
570 flowmap_n_1bits(struct flowmap fm)
571 {
572     unsigned int n_1bits = 0;
573     size_t unit;
574
575     FLOWMAP_FOR_EACH_UNIT (unit) {
576         n_1bits += count_1bits(fm.bits[unit]);
577     }
578     return n_1bits;
579 }
580
581 struct flowmap_aux {
582     size_t unit;
583     struct flowmap map;
584 };
585
586 static inline bool
587 flowmap_next_index(struct flowmap_aux *aux, size_t *idx)
588 {
589     for (;;) {
590         map_t *map = &aux->map.bits[aux->unit];
591         if (*map) {
592             *idx = aux->unit * MAP_T_BITS + raw_ctz(*map);
593             *map = zero_rightmost_1bit(*map);
594             return true;
595         }
596         if (++aux->unit >= FLOWMAP_UNITS) {
597             return false;
598         }
599     }
600 }
601
602 \f
603 /* Compressed flow. */
604
605 /* A sparse representation of a "struct flow".
606  *
607  * A "struct flow" is fairly large and tends to be mostly zeros.  Sparse
608  * representation has two advantages.  First, it saves memory and, more
609  * importantly, minimizes the number of accessed cache lines.  Second, it saves
610  * time when the goal is to iterate over only the nonzero parts of the struct.
611  *
612  * The map member hold one bit for each uint64_t in a "struct flow".  Each
613  * 0-bit indicates that the corresponding uint64_t is zero, each 1-bit that it
614  * *may* be nonzero (see below how this applies to minimasks).
615  *
616  * The values indicated by 'map' always follow the miniflow in memory.  The
617  * user of the miniflow is responsible for always having enough storage after
618  * the struct miniflow corresponding to the number of 1-bits in maps.
619  *
620  * Elements in values array are allowed to be zero.  This is useful for "struct
621  * minimatch", for which ensuring that the miniflow and minimask members have
622  * same maps allows optimization.  This allowance applies only to a miniflow
623  * that is not a mask.  That is, a minimask may NOT have zero elements in its
624  * values.
625  *
626  * A miniflow is always dynamically allocated so that the maps are followed by
627  * at least as many elements as there are 1-bits in maps. */
628 struct miniflow {
629     struct flowmap map;
630     /* Followed by:
631      *     uint64_t values[n];
632      * where 'n' is miniflow_n_values(miniflow). */
633 };
634 BUILD_ASSERT_DECL(sizeof(struct miniflow) % sizeof(uint64_t) == 0);
635
636 #define MINIFLOW_VALUES_SIZE(COUNT) ((COUNT) * sizeof(uint64_t))
637
638 static inline uint64_t *miniflow_values(struct miniflow *mf)
639 {
640     return (uint64_t *)(mf + 1);
641 }
642
643 static inline const uint64_t *miniflow_get_values(const struct miniflow *mf)
644 {
645     return (const uint64_t *)(mf + 1);
646 }
647
648 struct pkt_metadata;
649
650 /* The 'dst' must follow with buffer space for FLOW_U64S 64-bit units.
651  * 'dst->map' is ignored on input and set on output to indicate which fields
652  * were extracted. */
653 void miniflow_extract(struct dp_packet *packet, struct miniflow *dst);
654 void miniflow_map_init(struct miniflow *, const struct flow *);
655 void flow_wc_map(const struct flow *, struct flowmap *);
656 size_t miniflow_alloc(struct miniflow *dsts[], size_t n,
657                       const struct miniflow *src);
658 void miniflow_init(struct miniflow *, const struct flow *);
659 void miniflow_clone(struct miniflow *, const struct miniflow *,
660                     size_t n_values);
661 struct miniflow * miniflow_create(const struct flow *);
662
663 void miniflow_expand(const struct miniflow *, struct flow *);
664
665 static inline uint64_t flow_u64_value(const struct flow *flow, size_t index)
666 {
667     return ((uint64_t *)flow)[index];
668 }
669
670 static inline uint64_t *flow_u64_lvalue(struct flow *flow, size_t index)
671 {
672     return &((uint64_t *)flow)[index];
673 }
674
675 static inline size_t
676 miniflow_n_values(const struct miniflow *flow)
677 {
678     return flowmap_n_1bits(flow->map);
679 }
680
681 struct flow_for_each_in_maps_aux {
682     const struct flow *flow;
683     struct flowmap_aux map_aux;
684 };
685
686 static inline bool
687 flow_values_get_next_in_maps(struct flow_for_each_in_maps_aux *aux,
688                              uint64_t *value)
689 {
690     size_t idx;
691
692     if (flowmap_next_index(&aux->map_aux, &idx)) {
693         *value = flow_u64_value(aux->flow, idx);
694         return true;
695     }
696     return false;
697 }
698
699 /* Iterate through all flow u64 values specified by 'MAPS'. */
700 #define FLOW_FOR_EACH_IN_MAPS(VALUE, FLOW, MAPS)            \
701     for (struct flow_for_each_in_maps_aux aux__             \
702              = { (FLOW), FLOWMAP_AUX_INITIALIZER(MAPS) };   \
703          flow_values_get_next_in_maps(&aux__, &(VALUE));)
704
705 struct mf_for_each_in_map_aux {
706     size_t unit;
707     struct flowmap fmap;
708     struct flowmap map;
709     const uint64_t *values;
710 };
711
712 static inline bool
713 mf_get_next_in_map(struct mf_for_each_in_map_aux *aux,
714                    uint64_t *value)
715 {
716     map_t *map, *fmap;
717     map_t rm1bit;
718
719     while (OVS_UNLIKELY(!*(map = &aux->map.bits[aux->unit]))) {
720         /* Skip remaining data in the previous unit. */
721         aux->values += count_1bits(aux->fmap.bits[aux->unit]);
722         if (++aux->unit == FLOWMAP_UNITS) {
723             return false;
724         }
725     }
726
727     rm1bit = rightmost_1bit(*map);
728     *map -= rm1bit;
729     fmap = &aux->fmap.bits[aux->unit];
730
731     if (OVS_LIKELY(*fmap & rm1bit)) {
732         map_t trash = *fmap & (rm1bit - 1);
733
734         *fmap -= trash;
735         /* count_1bits() is fast for systems where speed matters (e.g.,
736          * DPDK), so we don't try avoid using it.
737          * Advance 'aux->values' to point to the value for 'rm1bit'. */
738         aux->values += count_1bits(trash);
739
740         *value = *aux->values;
741     } else {
742         *value = 0;
743     }
744     return true;
745 }
746
747 /* Iterate through miniflow u64 values specified by 'FLOWMAP'. */
748 #define MINIFLOW_FOR_EACH_IN_FLOWMAP(VALUE, FLOW, FLOWMAP)          \
749     for (struct mf_for_each_in_map_aux aux__ =                      \
750         { 0, (FLOW)->map, (FLOWMAP), miniflow_get_values(FLOW) };   \
751          mf_get_next_in_map(&aux__, &(VALUE));)
752
753 /* This can be used when it is known that 'idx' is set in 'map'. */
754 static inline const uint64_t *
755 miniflow_values_get__(const uint64_t *values, map_t map, size_t idx)
756 {
757     return values + count_1bits(map & ((MAP_1 << idx) - 1));
758 }
759
760 /* This can be used when it is known that 'u64_idx' is set in
761  * the map of 'mf'. */
762 static inline const uint64_t *
763 miniflow_get__(const struct miniflow *mf, size_t idx)
764 {
765     const uint64_t *values = miniflow_get_values(mf);
766     const map_t *map = mf->map.bits;
767
768     while (idx >= MAP_T_BITS) {
769         idx -= MAP_T_BITS;
770         values += count_1bits(*map++);
771     }
772     return miniflow_values_get__(values, *map, idx);
773 }
774
775 #define MINIFLOW_IN_MAP(MF, IDX) flowmap_is_set(&(MF)->map, IDX)
776
777 /* Get the value of the struct flow 'FIELD' as up to 8 byte wide integer type
778  * 'TYPE' from miniflow 'MF'. */
779 #define MINIFLOW_GET_TYPE(MF, TYPE, FIELD)                              \
780     (MINIFLOW_IN_MAP(MF, FLOW_U64_OFFSET(FIELD))                        \
781      ? ((OVS_FORCE const TYPE *)miniflow_get__(MF, FLOW_U64_OFFSET(FIELD))) \
782      [FLOW_U64_OFFREM(FIELD) / sizeof(TYPE)]                            \
783      : 0)
784
785 #define MINIFLOW_GET_U8(FLOW, FIELD)            \
786     MINIFLOW_GET_TYPE(FLOW, uint8_t, FIELD)
787 #define MINIFLOW_GET_U16(FLOW, FIELD)           \
788     MINIFLOW_GET_TYPE(FLOW, uint16_t, FIELD)
789 #define MINIFLOW_GET_BE16(FLOW, FIELD)          \
790     MINIFLOW_GET_TYPE(FLOW, ovs_be16, FIELD)
791 #define MINIFLOW_GET_U32(FLOW, FIELD)           \
792     MINIFLOW_GET_TYPE(FLOW, uint32_t, FIELD)
793 #define MINIFLOW_GET_BE32(FLOW, FIELD)          \
794     MINIFLOW_GET_TYPE(FLOW, ovs_be32, FIELD)
795 #define MINIFLOW_GET_U64(FLOW, FIELD)           \
796     MINIFLOW_GET_TYPE(FLOW, uint64_t, FIELD)
797 #define MINIFLOW_GET_BE64(FLOW, FIELD)          \
798     MINIFLOW_GET_TYPE(FLOW, ovs_be64, FIELD)
799
800 static inline uint64_t miniflow_get(const struct miniflow *,
801                                     unsigned int u64_ofs);
802 static inline uint32_t miniflow_get_u32(const struct miniflow *,
803                                         unsigned int u32_ofs);
804 static inline ovs_be32 miniflow_get_be32(const struct miniflow *,
805                                          unsigned int be32_ofs);
806 static inline uint16_t miniflow_get_vid(const struct miniflow *);
807 static inline uint16_t miniflow_get_tcp_flags(const struct miniflow *);
808 static inline ovs_be64 miniflow_get_metadata(const struct miniflow *);
809
810 bool miniflow_equal(const struct miniflow *a, const struct miniflow *b);
811 bool miniflow_equal_in_minimask(const struct miniflow *a,
812                                 const struct miniflow *b,
813                                 const struct minimask *);
814 bool miniflow_equal_flow_in_minimask(const struct miniflow *a,
815                                      const struct flow *b,
816                                      const struct minimask *);
817 uint32_t miniflow_hash_5tuple(const struct miniflow *flow, uint32_t basis);
818
819 \f
820 /* Compressed flow wildcards. */
821
822 /* A sparse representation of a "struct flow_wildcards".
823  *
824  * See the large comment on struct miniflow for details.
825  *
826  * Note: While miniflow can have zero data for a 1-bit in the map,
827  * a minimask may not!  We rely on this in the implementation. */
828 struct minimask {
829     struct miniflow masks;
830 };
831
832 void minimask_init(struct minimask *, const struct flow_wildcards *);
833 struct minimask * minimask_create(const struct flow_wildcards *);
834 void minimask_combine(struct minimask *dst,
835                       const struct minimask *a, const struct minimask *b,
836                       uint64_t storage[FLOW_U64S]);
837
838 void minimask_expand(const struct minimask *, struct flow_wildcards *);
839
840 static inline uint32_t minimask_get_u32(const struct minimask *,
841                                         unsigned int u32_ofs);
842 static inline ovs_be32 minimask_get_be32(const struct minimask *,
843                                          unsigned int be32_ofs);
844 static inline uint16_t minimask_get_vid_mask(const struct minimask *);
845 static inline ovs_be64 minimask_get_metadata_mask(const struct minimask *);
846
847 bool minimask_equal(const struct minimask *a, const struct minimask *b);
848 bool minimask_has_extra(const struct minimask *, const struct minimask *);
849
850 \f
851 /* Returns true if 'mask' matches every packet, false if 'mask' fixes any bits
852  * or fields. */
853 static inline bool
854 minimask_is_catchall(const struct minimask *mask)
855 {
856     /* For every 1-bit in mask's map, the corresponding value is non-zero,
857      * so the only way the mask can not fix any bits or fields is for the
858      * map the be zero. */
859     return flowmap_is_empty(mask->masks.map);
860 }
861
862 /* Returns the uint64_t that would be at byte offset '8 * u64_ofs' if 'flow'
863  * were expanded into a "struct flow". */
864 static inline uint64_t miniflow_get(const struct miniflow *flow,
865                                     unsigned int u64_ofs)
866 {
867     return MINIFLOW_IN_MAP(flow, u64_ofs) ? *miniflow_get__(flow, u64_ofs) : 0;
868 }
869
870 static inline uint32_t miniflow_get_u32(const struct miniflow *flow,
871                                         unsigned int u32_ofs)
872 {
873     uint64_t value = miniflow_get(flow, u32_ofs / 2);
874
875 #if WORDS_BIGENDIAN
876     return (u32_ofs & 1) ? value : value >> 32;
877 #else
878     return (u32_ofs & 1) ? value >> 32 : value;
879 #endif
880 }
881
882 static inline ovs_be32 miniflow_get_be32(const struct miniflow *flow,
883                                          unsigned int be32_ofs)
884 {
885     return (OVS_FORCE ovs_be32)miniflow_get_u32(flow, be32_ofs);
886 }
887
888 /* Returns the VID within the vlan_tci member of the "struct flow" represented
889  * by 'flow'. */
890 static inline uint16_t
891 miniflow_get_vid(const struct miniflow *flow)
892 {
893     ovs_be16 tci = MINIFLOW_GET_BE16(flow, vlan_tci);
894     return vlan_tci_to_vid(tci);
895 }
896
897 /* Returns the uint32_t that would be at byte offset '4 * u32_ofs' if 'mask'
898  * were expanded into a "struct flow_wildcards". */
899 static inline uint32_t
900 minimask_get_u32(const struct minimask *mask, unsigned int u32_ofs)
901 {
902     return miniflow_get_u32(&mask->masks, u32_ofs);
903 }
904
905 static inline ovs_be32
906 minimask_get_be32(const struct minimask *mask, unsigned int be32_ofs)
907 {
908     return (OVS_FORCE ovs_be32)minimask_get_u32(mask, be32_ofs);
909 }
910
911 /* Returns the VID mask within the vlan_tci member of the "struct
912  * flow_wildcards" represented by 'mask'. */
913 static inline uint16_t
914 minimask_get_vid_mask(const struct minimask *mask)
915 {
916     return miniflow_get_vid(&mask->masks);
917 }
918
919 /* Returns the value of the "tcp_flags" field in 'flow'. */
920 static inline uint16_t
921 miniflow_get_tcp_flags(const struct miniflow *flow)
922 {
923     return ntohs(MINIFLOW_GET_BE16(flow, tcp_flags));
924 }
925
926 /* Returns the value of the OpenFlow 1.1+ "metadata" field in 'flow'. */
927 static inline ovs_be64
928 miniflow_get_metadata(const struct miniflow *flow)
929 {
930     return MINIFLOW_GET_BE64(flow, metadata);
931 }
932
933 /* Returns the mask for the OpenFlow 1.1+ "metadata" field in 'mask'.
934  *
935  * The return value is all-1-bits if 'mask' matches on the whole value of the
936  * metadata field, all-0-bits if 'mask' entirely wildcards the metadata field,
937  * or some other value if the metadata field is partially matched, partially
938  * wildcarded. */
939 static inline ovs_be64
940 minimask_get_metadata_mask(const struct minimask *mask)
941 {
942     return MINIFLOW_GET_BE64(&mask->masks, metadata);
943 }
944
945 /* Perform a bitwise OR of miniflow 'src' flow data specified in 'subset' with
946  * the equivalent fields in 'dst', storing the result in 'dst'.  'subset' must
947  * be a subset of 'src's map. */
948 static inline void
949 flow_union_with_miniflow_subset(struct flow *dst, const struct miniflow *src,
950                                 struct flowmap subset)
951 {
952     uint64_t *dst_u64 = (uint64_t *) dst;
953     const uint64_t *p = miniflow_get_values(src);
954     map_t map;
955
956     FLOWMAP_FOR_EACH_MAP (map, subset) {
957         size_t idx;
958
959         MAP_FOR_EACH_INDEX(idx, map) {
960             dst_u64[idx] |= *p++;
961         }
962         dst_u64 += MAP_T_BITS;
963     }
964 }
965
966 /* Perform a bitwise OR of miniflow 'src' flow data with the equivalent
967  * fields in 'dst', storing the result in 'dst'. */
968 static inline void
969 flow_union_with_miniflow(struct flow *dst, const struct miniflow *src)
970 {
971     flow_union_with_miniflow_subset(dst, src, src->map);
972 }
973
974 static inline void
975 pkt_metadata_from_flow(struct pkt_metadata *md, const struct flow *flow)
976 {
977     md->recirc_id = flow->recirc_id;
978     md->dp_hash = flow->dp_hash;
979     flow_tnl_copy__(&md->tunnel, &flow->tunnel);
980     md->skb_priority = flow->skb_priority;
981     md->pkt_mark = flow->pkt_mark;
982     md->in_port = flow->in_port;
983 }
984
985 static inline bool is_ip_any(const struct flow *flow)
986 {
987     return dl_type_is_ip_any(flow->dl_type);
988 }
989
990 static inline bool is_icmpv4(const struct flow *flow)
991 {
992     return (flow->dl_type == htons(ETH_TYPE_IP)
993             && flow->nw_proto == IPPROTO_ICMP);
994 }
995
996 static inline bool is_icmpv6(const struct flow *flow)
997 {
998     return (flow->dl_type == htons(ETH_TYPE_IPV6)
999             && flow->nw_proto == IPPROTO_ICMPV6);
1000 }
1001
1002 static inline bool is_igmp(const struct flow *flow)
1003 {
1004     return (flow->dl_type == htons(ETH_TYPE_IP)
1005             && flow->nw_proto == IPPROTO_IGMP);
1006 }
1007
1008 static inline bool is_mld(const struct flow *flow)
1009 {
1010     return is_icmpv6(flow)
1011            && (flow->tp_src == htons(MLD_QUERY)
1012                || flow->tp_src == htons(MLD_REPORT)
1013                || flow->tp_src == htons(MLD_DONE)
1014                || flow->tp_src == htons(MLD2_REPORT));
1015 }
1016
1017 static inline bool is_mld_query(const struct flow *flow)
1018 {
1019     return is_icmpv6(flow) && flow->tp_src == htons(MLD_QUERY);
1020 }
1021
1022 static inline bool is_mld_report(const struct flow *flow)
1023 {
1024     return is_mld(flow) && !is_mld_query(flow);
1025 }
1026
1027 static inline bool is_stp(const struct flow *flow)
1028 {
1029     return (eth_addr_equals(flow->dl_dst, eth_addr_stp)
1030             && flow->dl_type == htons(FLOW_DL_TYPE_NONE));
1031 }
1032
1033 #endif /* flow.h */