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