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