2500efdd20dc710c7529cd2d8fca419b41d8c4d2
[sliver-openvswitch.git] / ofproto / ofproto-dpif-ipfix.c
1 /*
2  * Copyright (c) 2012, 2013 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
17 #include <config.h>
18 #include "ofproto-dpif-ipfix.h"
19 #include <sys/time.h>
20 #include "byte-order.h"
21 #include "collectors.h"
22 #include "flow.h"
23 #include "hash.h"
24 #include "hmap.h"
25 #include "list.h"
26 #include "ofpbuf.h"
27 #include "ofproto.h"
28 #include "packets.h"
29 #include "poll-loop.h"
30 #include "sset.h"
31 #include "util.h"
32 #include "timeval.h"
33 #include "util.h"
34 #include "vlog.h"
35
36 VLOG_DEFINE_THIS_MODULE(ipfix);
37
38 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
39 static struct ovs_mutex mutex = OVS_MUTEX_INITIALIZER;
40
41 /* Cf. IETF RFC 5101 Section 10.3.4. */
42 #define IPFIX_DEFAULT_COLLECTOR_PORT 4739
43
44 struct dpif_ipfix_exporter {
45     struct collectors *collectors;
46     uint32_t seq_number;
47     time_t last_template_set_time;
48     struct hmap cache_flow_key_map;  /* ipfix_flow_cache_entry. */
49     struct list cache_flow_start_timestamp_list;  /* ipfix_flow_cache_entry. */
50     uint32_t cache_active_timeout;  /* In seconds. */
51     uint32_t cache_max_flows;
52 };
53
54 struct dpif_ipfix_bridge_exporter {
55     struct dpif_ipfix_exporter exporter;
56     struct ofproto_ipfix_bridge_exporter_options *options;
57     uint32_t probability;
58 };
59
60 struct dpif_ipfix_flow_exporter {
61     struct dpif_ipfix_exporter exporter;
62     struct ofproto_ipfix_flow_exporter_options *options;
63 };
64
65 struct dpif_ipfix_flow_exporter_map_node {
66     struct hmap_node node;
67     struct dpif_ipfix_flow_exporter exporter;
68 };
69
70 struct dpif_ipfix {
71     struct dpif_ipfix_bridge_exporter bridge_exporter;
72     struct hmap flow_exporter_map;  /* dpif_ipfix_flow_exporter_map_node. */
73     struct ovs_refcount ref_cnt;
74 };
75
76 #define IPFIX_VERSION 0x000a
77
78 /* When using UDP, IPFIX Template Records must be re-sent regularly.
79  * The standard default interval is 10 minutes (600 seconds).
80  * Cf. IETF RFC 5101 Section 10.3.6. */
81 #define IPFIX_TEMPLATE_INTERVAL 600
82
83 /* Cf. IETF RFC 5101 Section 3.1. */
84 OVS_PACKED(
85 struct ipfix_header {
86     ovs_be16 version;  /* IPFIX_VERSION. */
87     ovs_be16 length;  /* Length in bytes including this header. */
88     ovs_be32 export_time;  /* Seconds since the epoch. */
89     ovs_be32 seq_number;  /* Message sequence number. */
90     ovs_be32 obs_domain_id;  /* Observation Domain ID. */
91 });
92 BUILD_ASSERT_DECL(sizeof(struct ipfix_header) == 16);
93
94 #define IPFIX_SET_ID_TEMPLATE 2
95 #define IPFIX_SET_ID_OPTION_TEMPLATE 3
96
97 /* Cf. IETF RFC 5101 Section 3.3.2. */
98 OVS_PACKED(
99 struct ipfix_set_header {
100     ovs_be16 set_id;  /* IPFIX_SET_ID_* or valid template ID for Data Sets. */
101     ovs_be16 length;  /* Length of the set in bytes including header. */
102 });
103 BUILD_ASSERT_DECL(sizeof(struct ipfix_set_header) == 4);
104
105 /* Alternatives for templates at each layer.  A template is defined by
106  * a combination of one value for each layer. */
107 enum ipfix_proto_l2 {
108     IPFIX_PROTO_L2_ETH = 0,  /* No VLAN. */
109     IPFIX_PROTO_L2_VLAN,
110     NUM_IPFIX_PROTO_L2
111 };
112 enum ipfix_proto_l3 {
113     IPFIX_PROTO_L3_UNKNOWN = 0,
114     IPFIX_PROTO_L3_IPV4,
115     IPFIX_PROTO_L3_IPV6,
116     NUM_IPFIX_PROTO_L3
117 };
118 enum ipfix_proto_l4 {
119     IPFIX_PROTO_L4_UNKNOWN = 0,
120     IPFIX_PROTO_L4_TCP_UDP,
121     NUM_IPFIX_PROTO_L4
122 };
123
124 /* Any Template ID > 255 is usable for Template Records. */
125 #define IPFIX_TEMPLATE_ID_MIN 256
126
127 /* Cf. IETF RFC 5101 Section 3.4.1. */
128 OVS_PACKED(
129 struct ipfix_template_record_header {
130     ovs_be16 template_id;
131     ovs_be16 field_count;
132 });
133 BUILD_ASSERT_DECL(sizeof(struct ipfix_template_record_header) == 4);
134
135 enum ipfix_entity_id {
136 #define IPFIX_ENTITY(ENUM, ID, SIZE, NAME)  IPFIX_ENTITY_ID_##ENUM = ID,
137 #include "ofproto/ipfix-entities.def"
138 };
139
140 enum ipfix_entity_size {
141 #define IPFIX_ENTITY(ENUM, ID, SIZE, NAME)  IPFIX_ENTITY_SIZE_##ENUM = SIZE,
142 #include "ofproto/ipfix-entities.def"
143 };
144
145 OVS_PACKED(
146 struct ipfix_template_field_specifier {
147     ovs_be16 element_id;  /* IPFIX_ENTITY_ID_*. */
148     ovs_be16 field_length;  /* Length of the field's value, in bytes. */
149     /* No Enterprise ID, since only standard element IDs are specified. */
150 });
151 BUILD_ASSERT_DECL(sizeof(struct ipfix_template_field_specifier) == 4);
152
153 /* Part of data record flow key for common metadata and Ethernet entities. */
154 OVS_PACKED(
155 struct ipfix_data_record_flow_key_common {
156     ovs_be32 observation_point_id;  /* OBSERVATION_POINT_ID */
157     uint8_t source_mac_address[6];  /* SOURCE_MAC_ADDRESS */
158     uint8_t destination_mac_address[6];  /* DESTINATION_MAC_ADDRESS */
159     ovs_be16 ethernet_type;  /* ETHERNET_TYPE */
160     uint8_t ethernet_header_length;  /* ETHERNET_HEADER_LENGTH */
161 });
162 BUILD_ASSERT_DECL(sizeof(struct ipfix_data_record_flow_key_common) == 19);
163
164 /* Part of data record flow key for VLAN entities. */
165 OVS_PACKED(
166 struct ipfix_data_record_flow_key_vlan {
167     ovs_be16 vlan_id;  /* VLAN_ID */
168     ovs_be16 dot1q_vlan_id;  /* DOT1Q_VLAN_ID */
169     uint8_t dot1q_priority;  /* DOT1Q_PRIORITY */
170 });
171 BUILD_ASSERT_DECL(sizeof(struct ipfix_data_record_flow_key_vlan) == 5);
172
173 /* Part of data record flow key for IP entities. */
174 /* XXX: Replace IP_TTL with MINIMUM_TTL and MAXIMUM_TTL? */
175 OVS_PACKED(
176 struct ipfix_data_record_flow_key_ip {
177     uint8_t ip_version;  /* IP_VERSION */
178     uint8_t ip_ttl;  /* IP_TTL */
179     uint8_t protocol_identifier;  /* PROTOCOL_IDENTIFIER */
180     uint8_t ip_diff_serv_code_point;  /* IP_DIFF_SERV_CODE_POINT */
181     uint8_t ip_precedence;  /* IP_PRECEDENCE */
182     uint8_t ip_class_of_service;  /* IP_CLASS_OF_SERVICE */
183 });
184 BUILD_ASSERT_DECL(sizeof(struct ipfix_data_record_flow_key_ip) == 6);
185
186 /* Part of data record flow key for IPv4 entities. */
187 OVS_PACKED(
188 struct ipfix_data_record_flow_key_ipv4 {
189     ovs_be32 source_ipv4_address;  /* SOURCE_IPV4_ADDRESS */
190     ovs_be32 destination_ipv4_address;  /* DESTINATION_IPV4_ADDRESS */
191 });
192 BUILD_ASSERT_DECL(sizeof(struct ipfix_data_record_flow_key_ipv4) == 8);
193
194 /* Part of data record flow key for IPv6 entities. */
195 OVS_PACKED(
196 struct ipfix_data_record_flow_key_ipv6 {
197     uint8_t source_ipv6_address[16];  /* SOURCE_IPV6_ADDRESS */
198     uint8_t destination_ipv6_address[16];  /* DESTINATION_IPV6_ADDRESS */
199     ovs_be32 flow_label_ipv6;  /* FLOW_LABEL_IPV6 */
200 });
201 BUILD_ASSERT_DECL(sizeof(struct ipfix_data_record_flow_key_ipv6) == 36);
202
203 /* Part of data record flow key for TCP/UDP entities. */
204 OVS_PACKED(
205 struct ipfix_data_record_flow_key_tcpudp {
206     ovs_be16 source_transport_port;  /* SOURCE_TRANSPORT_PORT */
207     ovs_be16 destination_transport_port;  /* DESTINATION_TRANSPORT_PORT */
208 });
209 BUILD_ASSERT_DECL(sizeof(struct ipfix_data_record_flow_key_tcpudp) == 4);
210
211 /* Cf. IETF RFC 5102 Section 5.11.3. */
212 enum ipfix_flow_end_reason {
213     IDLE_TIMEOUT = 0x01,
214     ACTIVE_TIMEOUT = 0x02,
215     END_OF_FLOW_DETECTED = 0x03,
216     FORCED_END = 0x04,
217     LACK_OF_RESOURCES = 0x05
218 };
219
220 /* Part of data record for common aggregated elements. */
221 OVS_PACKED(
222 struct ipfix_data_record_aggregated_common {
223     ovs_be32 flow_start_delta_microseconds; /* FLOW_START_DELTA_MICROSECONDS */
224     ovs_be32 flow_end_delta_microseconds; /* FLOW_END_DELTA_MICROSECONDS */
225     ovs_be64 packet_delta_count;  /* PACKET_DELTA_COUNT */
226     ovs_be64 layer2_octet_delta_count;  /* LAYER2_OCTET_DELTA_COUNT */
227     uint8_t flow_end_reason;  /* FLOW_END_REASON */
228 });
229 BUILD_ASSERT_DECL(sizeof(struct ipfix_data_record_aggregated_common) == 25);
230
231 /* Part of data record for IP aggregated elements. */
232 OVS_PACKED(
233 struct ipfix_data_record_aggregated_ip {
234     ovs_be64 octet_delta_sum_of_squares;  /* OCTET_DELTA_SUM_OF_SQUARES */
235     ovs_be64 minimum_ip_total_length;  /* MINIMUM_IP_TOTAL_LENGTH */
236     ovs_be64 maximum_ip_total_length;  /* MAXIMUM_IP_TOTAL_LENGTH */
237 });
238 BUILD_ASSERT_DECL(sizeof(struct ipfix_data_record_aggregated_ip) == 24);
239
240 #define MAX_FLOW_KEY_LEN                                 \
241     (sizeof(struct ipfix_data_record_flow_key_common)    \
242      + sizeof(struct ipfix_data_record_flow_key_vlan)    \
243      + sizeof(struct ipfix_data_record_flow_key_ip)      \
244      + sizeof(struct ipfix_data_record_flow_key_ipv6)    \
245      + sizeof(struct ipfix_data_record_flow_key_tcpudp))
246
247 #define MAX_DATA_RECORD_LEN                                 \
248     (MAX_FLOW_KEY_LEN                                       \
249      + sizeof(struct ipfix_data_record_aggregated_common)   \
250      + sizeof(struct ipfix_data_record_aggregated_ip))
251
252 /* Max length of a data set.  To simplify the implementation, each
253  * data record is sent in a separate data set, so each data set
254  * contains at most one data record. */
255 #define MAX_DATA_SET_LEN             \
256     (sizeof(struct ipfix_set_header) \
257      + MAX_DATA_RECORD_LEN)
258
259 /* Max length of an IPFIX message. Arbitrarily set to accomodate low
260  * MTU. */
261 #define MAX_MESSAGE_LEN 1024
262
263 /* Cache structures. */
264
265 /* Flow key. */
266 struct ipfix_flow_key {
267     uint32_t obs_domain_id;
268     uint16_t template_id;
269     size_t flow_key_msg_part_size;
270     uint64_t flow_key_msg_part[DIV_ROUND_UP(MAX_FLOW_KEY_LEN, 8)];
271 };
272
273 /* Flow cache entry. */
274 struct ipfix_flow_cache_entry {
275     struct hmap_node flow_key_map_node;
276     struct list cache_flow_start_timestamp_list_node;
277     struct ipfix_flow_key flow_key;
278     /* Common aggregated elements. */
279     uint64_t flow_start_timestamp_usec;
280     uint64_t flow_end_timestamp_usec;
281     uint64_t packet_delta_count;
282     uint64_t layer2_octet_delta_count;
283     uint64_t octet_delta_sum_of_squares;  /* 0 if not IP. */
284     uint16_t minimum_ip_total_length;  /* 0 if not IP. */
285     uint16_t maximum_ip_total_length;  /* 0 if not IP. */
286 };
287
288 static void dpif_ipfix_cache_expire(struct dpif_ipfix_exporter *, bool,
289                                     const uint64_t, const uint32_t);
290
291 static void get_export_time_now(uint64_t *, uint32_t *);
292
293 static void dpif_ipfix_cache_expire_now(struct dpif_ipfix_exporter *, bool);
294
295 static bool
296 ofproto_ipfix_bridge_exporter_options_equal(
297     const struct ofproto_ipfix_bridge_exporter_options *a,
298     const struct ofproto_ipfix_bridge_exporter_options *b)
299 {
300     return (a->obs_domain_id == b->obs_domain_id
301             && a->obs_point_id == b->obs_point_id
302             && a->sampling_rate == b->sampling_rate
303             && a->cache_active_timeout == b->cache_active_timeout
304             && a->cache_max_flows == b->cache_max_flows
305             && sset_equals(&a->targets, &b->targets));
306 }
307
308 static struct ofproto_ipfix_bridge_exporter_options *
309 ofproto_ipfix_bridge_exporter_options_clone(
310     const struct ofproto_ipfix_bridge_exporter_options *old)
311 {
312     struct ofproto_ipfix_bridge_exporter_options *new =
313         xmemdup(old, sizeof *old);
314     sset_clone(&new->targets, &old->targets);
315     return new;
316 }
317
318 static void
319 ofproto_ipfix_bridge_exporter_options_destroy(
320     struct ofproto_ipfix_bridge_exporter_options *options)
321 {
322     if (options) {
323         sset_destroy(&options->targets);
324         free(options);
325     }
326 }
327
328 static bool
329 ofproto_ipfix_flow_exporter_options_equal(
330     const struct ofproto_ipfix_flow_exporter_options *a,
331     const struct ofproto_ipfix_flow_exporter_options *b)
332 {
333     return (a->collector_set_id == b->collector_set_id
334             && a->cache_active_timeout == b->cache_active_timeout
335             && a->cache_max_flows == b->cache_max_flows
336             && sset_equals(&a->targets, &b->targets));
337 }
338
339 static struct ofproto_ipfix_flow_exporter_options *
340 ofproto_ipfix_flow_exporter_options_clone(
341     const struct ofproto_ipfix_flow_exporter_options *old)
342 {
343     struct ofproto_ipfix_flow_exporter_options *new =
344         xmemdup(old, sizeof *old);
345     sset_clone(&new->targets, &old->targets);
346     return new;
347 }
348
349 static void
350 ofproto_ipfix_flow_exporter_options_destroy(
351     struct ofproto_ipfix_flow_exporter_options *options)
352 {
353     if (options) {
354         sset_destroy(&options->targets);
355         free(options);
356     }
357 }
358
359 static void
360 dpif_ipfix_exporter_init(struct dpif_ipfix_exporter *exporter)
361 {
362     exporter->collectors = NULL;
363     exporter->seq_number = 1;
364     exporter->last_template_set_time = TIME_MIN;
365     hmap_init(&exporter->cache_flow_key_map);
366     list_init(&exporter->cache_flow_start_timestamp_list);
367     exporter->cache_active_timeout = 0;
368     exporter->cache_max_flows = 0;
369 }
370
371 static void
372 dpif_ipfix_exporter_clear(struct dpif_ipfix_exporter *exporter)
373 {
374     /* Flush the cache with flow end reason "forced end." */
375     dpif_ipfix_cache_expire_now(exporter, true);
376
377     collectors_destroy(exporter->collectors);
378     exporter->collectors = NULL;
379     exporter->seq_number = 1;
380     exporter->last_template_set_time = TIME_MIN;
381     exporter->cache_active_timeout = 0;
382     exporter->cache_max_flows = 0;
383 }
384
385 static void
386 dpif_ipfix_exporter_destroy(struct dpif_ipfix_exporter *exporter)
387 {
388     dpif_ipfix_exporter_clear(exporter);
389     hmap_destroy(&exporter->cache_flow_key_map);
390 }
391
392 static bool
393 dpif_ipfix_exporter_set_options(struct dpif_ipfix_exporter *exporter,
394                                 const struct sset *targets,
395                                 const uint32_t cache_active_timeout,
396                                 const uint32_t cache_max_flows)
397 {
398     collectors_destroy(exporter->collectors);
399     collectors_create(targets, IPFIX_DEFAULT_COLLECTOR_PORT,
400                       &exporter->collectors);
401     if (exporter->collectors == NULL) {
402         VLOG_WARN_RL(&rl, "no collectors could be initialized, "
403                      "IPFIX exporter disabled");
404         dpif_ipfix_exporter_clear(exporter);
405         return false;
406     }
407     exporter->cache_active_timeout = cache_active_timeout;
408     exporter->cache_max_flows = cache_max_flows;
409     return true;
410 }
411
412 static void
413 dpif_ipfix_bridge_exporter_init(struct dpif_ipfix_bridge_exporter *exporter)
414 {
415     dpif_ipfix_exporter_init(&exporter->exporter);
416     exporter->options = NULL;
417     exporter->probability = 0;
418 }
419
420 static void
421 dpif_ipfix_bridge_exporter_clear(struct dpif_ipfix_bridge_exporter *exporter)
422 {
423     dpif_ipfix_exporter_clear(&exporter->exporter);
424     ofproto_ipfix_bridge_exporter_options_destroy(exporter->options);
425     exporter->options = NULL;
426     exporter->probability = 0;
427 }
428
429 static void
430 dpif_ipfix_bridge_exporter_destroy(struct dpif_ipfix_bridge_exporter *exporter)
431 {
432     dpif_ipfix_bridge_exporter_clear(exporter);
433     dpif_ipfix_exporter_destroy(&exporter->exporter);
434 }
435
436 static void
437 dpif_ipfix_bridge_exporter_set_options(
438     struct dpif_ipfix_bridge_exporter *exporter,
439     const struct ofproto_ipfix_bridge_exporter_options *options)
440 {
441     bool options_changed;
442
443     if (!options || sset_is_empty(&options->targets)) {
444         /* No point in doing any work if there are no targets. */
445         dpif_ipfix_bridge_exporter_clear(exporter);
446         return;
447     }
448
449     options_changed = (
450         !exporter->options
451         || !ofproto_ipfix_bridge_exporter_options_equal(
452             options, exporter->options));
453
454     /* Configure collectors if options have changed or if we're
455      * shortchanged in collectors (which indicates that opening one or
456      * more of the configured collectors failed, so that we should
457      * retry). */
458     if (options_changed
459         || collectors_count(exporter->exporter.collectors)
460             < sset_count(&options->targets)) {
461         if (!dpif_ipfix_exporter_set_options(
462                 &exporter->exporter, &options->targets,
463                 options->cache_active_timeout, options->cache_max_flows)) {
464             return;
465         }
466     }
467
468     /* Avoid reconfiguring if options didn't change. */
469     if (!options_changed) {
470         return;
471     }
472
473     ofproto_ipfix_bridge_exporter_options_destroy(exporter->options);
474     exporter->options = ofproto_ipfix_bridge_exporter_options_clone(options);
475     exporter->probability =
476         MAX(1, UINT32_MAX / exporter->options->sampling_rate);
477
478     /* Run over the cache as some entries might have expired after
479      * changing the timeouts. */
480     dpif_ipfix_cache_expire_now(&exporter->exporter, false);
481 }
482
483 static struct dpif_ipfix_flow_exporter_map_node*
484 dpif_ipfix_find_flow_exporter_map_node(
485     const struct dpif_ipfix *di, const uint32_t collector_set_id)
486     OVS_REQUIRES(mutex)
487 {
488     struct dpif_ipfix_flow_exporter_map_node *exporter_node;
489
490     HMAP_FOR_EACH_WITH_HASH (exporter_node, node,
491                              hash_int(collector_set_id, 0),
492                              &di->flow_exporter_map) {
493         if (exporter_node->exporter.options->collector_set_id
494             == collector_set_id) {
495             return exporter_node;
496         }
497     }
498
499     return NULL;
500 }
501
502 static void
503 dpif_ipfix_flow_exporter_init(struct dpif_ipfix_flow_exporter *exporter)
504 {
505     dpif_ipfix_exporter_init(&exporter->exporter);
506     exporter->options = NULL;
507 }
508
509 static void
510 dpif_ipfix_flow_exporter_clear(struct dpif_ipfix_flow_exporter *exporter)
511 {
512     dpif_ipfix_exporter_clear(&exporter->exporter);
513     ofproto_ipfix_flow_exporter_options_destroy(exporter->options);
514     exporter->options = NULL;
515 }
516
517 static void
518 dpif_ipfix_flow_exporter_destroy(struct dpif_ipfix_flow_exporter *exporter)
519 {
520     dpif_ipfix_flow_exporter_clear(exporter);
521     dpif_ipfix_exporter_destroy(&exporter->exporter);
522 }
523
524 static bool
525 dpif_ipfix_flow_exporter_set_options(
526     struct dpif_ipfix_flow_exporter *exporter,
527     const struct ofproto_ipfix_flow_exporter_options *options)
528 {
529     bool options_changed;
530
531     if (sset_is_empty(&options->targets)) {
532         /* No point in doing any work if there are no targets. */
533         dpif_ipfix_flow_exporter_clear(exporter);
534         return true;
535     }
536
537     options_changed = (
538         !exporter->options
539         || !ofproto_ipfix_flow_exporter_options_equal(
540             options, exporter->options));
541
542     /* Configure collectors if options have changed or if we're
543      * shortchanged in collectors (which indicates that opening one or
544      * more of the configured collectors failed, so that we should
545      * retry). */
546     if (options_changed
547         || collectors_count(exporter->exporter.collectors)
548             < sset_count(&options->targets)) {
549         if (!dpif_ipfix_exporter_set_options(
550                 &exporter->exporter, &options->targets,
551                 options->cache_active_timeout, options->cache_max_flows)) {
552             return false;
553         }
554     }
555
556     /* Avoid reconfiguring if options didn't change. */
557     if (!options_changed) {
558         return true;
559     }
560
561     ofproto_ipfix_flow_exporter_options_destroy(exporter->options);
562     exporter->options = ofproto_ipfix_flow_exporter_options_clone(options);
563
564     /* Run over the cache as some entries might have expired after
565      * changing the timeouts. */
566     dpif_ipfix_cache_expire_now(&exporter->exporter, false);
567
568     return true;
569 }
570
571 void
572 dpif_ipfix_set_options(
573     struct dpif_ipfix *di,
574     const struct ofproto_ipfix_bridge_exporter_options *bridge_exporter_options,
575     const struct ofproto_ipfix_flow_exporter_options *flow_exporters_options,
576     size_t n_flow_exporters_options) OVS_EXCLUDED(mutex)
577 {
578     int i;
579     struct ofproto_ipfix_flow_exporter_options *options;
580     struct dpif_ipfix_flow_exporter_map_node *node, *next;
581     size_t n_broken_flow_exporters_options = 0;
582
583     ovs_mutex_lock(&mutex);
584     dpif_ipfix_bridge_exporter_set_options(&di->bridge_exporter,
585                                            bridge_exporter_options);
586
587     /* Add new flow exporters and update current flow exporters. */
588     options = (struct ofproto_ipfix_flow_exporter_options *)
589         flow_exporters_options;
590     for (i = 0; i < n_flow_exporters_options; i++) {
591         node = dpif_ipfix_find_flow_exporter_map_node(
592             di, options->collector_set_id);
593         if (!node) {
594             node = xzalloc(sizeof *node);
595             dpif_ipfix_flow_exporter_init(&node->exporter);
596             hmap_insert(&di->flow_exporter_map, &node->node,
597                         hash_int(options->collector_set_id, 0));
598         }
599         if (!dpif_ipfix_flow_exporter_set_options(&node->exporter, options)) {
600             n_broken_flow_exporters_options++;
601         }
602         options++;
603     }
604
605     ovs_assert(hmap_count(&di->flow_exporter_map) >=
606                (n_flow_exporters_options - n_broken_flow_exporters_options));
607
608     /* Remove dropped flow exporters, if any needs to be removed. */
609     if (hmap_count(&di->flow_exporter_map) > n_flow_exporters_options) {
610         HMAP_FOR_EACH_SAFE (node, next, node, &di->flow_exporter_map) {
611             /* This is slow but doesn't take any extra memory, and
612              * this table is not supposed to contain many rows anyway. */
613             options = (struct ofproto_ipfix_flow_exporter_options *)
614                 flow_exporters_options;
615             for (i = 0; i < n_flow_exporters_options; i++) {
616               if (node->exporter.options->collector_set_id
617                   == options->collector_set_id) {
618                   break;
619               }
620               options++;
621             }
622             if (i == n_flow_exporters_options) {  // Not found.
623                 hmap_remove(&di->flow_exporter_map, &node->node);
624                 dpif_ipfix_flow_exporter_destroy(&node->exporter);
625                 free(node);
626             }
627         }
628     }
629
630     ovs_assert(hmap_count(&di->flow_exporter_map) ==
631                (n_flow_exporters_options - n_broken_flow_exporters_options));
632     ovs_mutex_unlock(&mutex);
633 }
634
635 struct dpif_ipfix *
636 dpif_ipfix_create(void)
637 {
638     struct dpif_ipfix *di;
639     di = xzalloc(sizeof *di);
640     dpif_ipfix_bridge_exporter_init(&di->bridge_exporter);
641     hmap_init(&di->flow_exporter_map);
642     ovs_refcount_init(&di->ref_cnt);
643     return di;
644 }
645
646 struct dpif_ipfix *
647 dpif_ipfix_ref(const struct dpif_ipfix *di_)
648 {
649     struct dpif_ipfix *di = CONST_CAST(struct dpif_ipfix *, di_);
650     if (di) {
651         ovs_refcount_ref(&di->ref_cnt);
652     }
653     return di;
654 }
655
656 uint32_t
657 dpif_ipfix_get_bridge_exporter_probability(const struct dpif_ipfix *di)
658     OVS_EXCLUDED(mutex)
659 {
660     uint32_t ret;
661     ovs_mutex_lock(&mutex);
662     ret = di->bridge_exporter.probability;
663     ovs_mutex_unlock(&mutex);
664     return ret;
665 }
666
667 static void
668 dpif_ipfix_clear(struct dpif_ipfix *di) OVS_REQUIRES(mutex)
669 {
670     struct dpif_ipfix_flow_exporter_map_node *exp_node, *exp_next;
671
672     dpif_ipfix_bridge_exporter_clear(&di->bridge_exporter);
673
674     HMAP_FOR_EACH_SAFE (exp_node, exp_next, node, &di->flow_exporter_map) {
675         hmap_remove(&di->flow_exporter_map, &exp_node->node);
676         dpif_ipfix_flow_exporter_destroy(&exp_node->exporter);
677         free(exp_node);
678     }
679 }
680
681 void
682 dpif_ipfix_unref(struct dpif_ipfix *di) OVS_EXCLUDED(mutex)
683 {
684     if (di && ovs_refcount_unref(&di->ref_cnt) == 1) {
685         ovs_mutex_lock(&mutex);
686         dpif_ipfix_clear(di);
687         dpif_ipfix_bridge_exporter_destroy(&di->bridge_exporter);
688         hmap_destroy(&di->flow_exporter_map);
689         ovs_refcount_destroy(&di->ref_cnt);
690         free(di);
691         ovs_mutex_unlock(&mutex);
692     }
693 }
694
695 static void
696 ipfix_init_header(uint32_t export_time_sec, uint32_t seq_number,
697                   uint32_t obs_domain_id, struct ofpbuf *msg)
698 {
699     struct ipfix_header *hdr;
700
701     hdr = ofpbuf_put_zeros(msg, sizeof *hdr);
702     hdr->version = htons(IPFIX_VERSION);
703     hdr->length = htons(sizeof *hdr);  /* Updated in ipfix_send_msg. */
704     hdr->export_time = htonl(export_time_sec);
705     hdr->seq_number = htonl(seq_number);
706     hdr->obs_domain_id = htonl(obs_domain_id);
707 }
708
709 static void
710 ipfix_send_msg(const struct collectors *collectors, struct ofpbuf *msg)
711 {
712     struct ipfix_header *hdr;
713
714     /* Adjust the length in the header. */
715     hdr = msg->data;
716     hdr->length = htons(msg->size);
717
718     collectors_send(collectors, msg->data, msg->size);
719     msg->size = 0;
720 }
721
722 static uint16_t
723 ipfix_get_template_id(enum ipfix_proto_l2 l2, enum ipfix_proto_l3 l3,
724                       enum ipfix_proto_l4 l4)
725 {
726     uint16_t template_id;
727     template_id = l2;
728     template_id = template_id * NUM_IPFIX_PROTO_L3 + l3;
729     template_id = template_id * NUM_IPFIX_PROTO_L4 + l4;
730     return IPFIX_TEMPLATE_ID_MIN + template_id;
731 }
732
733 static void
734 ipfix_define_template_entity(enum ipfix_entity_id id,
735                              enum ipfix_entity_size size, struct ofpbuf *msg)
736 {
737     struct ipfix_template_field_specifier *field;
738
739     field = ofpbuf_put_zeros(msg, sizeof *field);
740     field->element_id = htons(id);
741     field->field_length = htons(size);
742 }
743
744 static uint16_t
745 ipfix_define_template_fields(enum ipfix_proto_l2 l2, enum ipfix_proto_l3 l3,
746                              enum ipfix_proto_l4 l4, struct ofpbuf *msg)
747 {
748     uint16_t count = 0;
749
750 #define DEF(ID) \
751     { \
752         ipfix_define_template_entity(IPFIX_ENTITY_ID_##ID, \
753                                      IPFIX_ENTITY_SIZE_##ID, msg); \
754         count++; \
755     }
756
757     /* 1. Flow key. */
758
759     DEF(OBSERVATION_POINT_ID);
760
761     /* Common Ethernet entities. */
762     DEF(SOURCE_MAC_ADDRESS);
763     DEF(DESTINATION_MAC_ADDRESS);
764     DEF(ETHERNET_TYPE);
765     DEF(ETHERNET_HEADER_LENGTH);
766
767     if (l2 == IPFIX_PROTO_L2_VLAN) {
768         DEF(VLAN_ID);
769         DEF(DOT1Q_VLAN_ID);
770         DEF(DOT1Q_PRIORITY);
771     }
772
773     if (l3 != IPFIX_PROTO_L3_UNKNOWN) {
774         DEF(IP_VERSION);
775         DEF(IP_TTL);
776         DEF(PROTOCOL_IDENTIFIER);
777         DEF(IP_DIFF_SERV_CODE_POINT);
778         DEF(IP_PRECEDENCE);
779         DEF(IP_CLASS_OF_SERVICE);
780
781         if (l3 == IPFIX_PROTO_L3_IPV4) {
782             DEF(SOURCE_IPV4_ADDRESS);
783             DEF(DESTINATION_IPV4_ADDRESS);
784         } else {  /* l3 == IPFIX_PROTO_L3_IPV6 */
785             DEF(SOURCE_IPV6_ADDRESS);
786             DEF(DESTINATION_IPV6_ADDRESS);
787             DEF(FLOW_LABEL_IPV6);
788         }
789     }
790
791     if (l4 != IPFIX_PROTO_L4_UNKNOWN) {
792         DEF(SOURCE_TRANSPORT_PORT);
793         DEF(DESTINATION_TRANSPORT_PORT);
794     }
795
796     /* 2. Flow aggregated data. */
797
798     DEF(FLOW_START_DELTA_MICROSECONDS);
799     DEF(FLOW_END_DELTA_MICROSECONDS);
800     DEF(PACKET_DELTA_COUNT);
801     DEF(LAYER2_OCTET_DELTA_COUNT);
802     DEF(FLOW_END_REASON);
803
804     if (l3 != IPFIX_PROTO_L3_UNKNOWN) {
805         DEF(OCTET_DELTA_SUM_OF_SQUARES);
806         DEF(MINIMUM_IP_TOTAL_LENGTH);
807         DEF(MAXIMUM_IP_TOTAL_LENGTH);
808     }
809
810 #undef DEF
811
812     return count;
813 }
814
815 static void
816 ipfix_send_template_msg(struct dpif_ipfix_exporter *exporter,
817                         uint32_t export_time_sec, uint32_t obs_domain_id)
818 {
819     uint64_t msg_stub[DIV_ROUND_UP(MAX_MESSAGE_LEN, 8)];
820     struct ofpbuf msg;
821     size_t set_hdr_offset, tmpl_hdr_offset;
822     struct ipfix_set_header *set_hdr;
823     struct ipfix_template_record_header *tmpl_hdr;
824     uint16_t field_count;
825     enum ipfix_proto_l2 l2;
826     enum ipfix_proto_l3 l3;
827     enum ipfix_proto_l4 l4;
828
829     ofpbuf_use_stub(&msg, msg_stub, sizeof msg_stub);
830
831     ipfix_init_header(export_time_sec, exporter->seq_number, obs_domain_id,
832                       &msg);
833     set_hdr_offset = msg.size;
834
835     /* Add a Template Set. */
836     set_hdr = ofpbuf_put_zeros(&msg, sizeof *set_hdr);
837     set_hdr->set_id = htons(IPFIX_SET_ID_TEMPLATE);
838
839     /* Define one template for each possible combination of
840      * protocols. */
841     for (l2 = 0; l2 < NUM_IPFIX_PROTO_L2; l2++) {
842         for (l3 = 0; l3 < NUM_IPFIX_PROTO_L3; l3++) {
843             for (l4 = 0; l4 < NUM_IPFIX_PROTO_L4; l4++) {
844                 if (l3 == IPFIX_PROTO_L3_UNKNOWN &&
845                     l4 != IPFIX_PROTO_L4_UNKNOWN) {
846                     continue;
847                 }
848                 tmpl_hdr_offset = msg.size;
849                 tmpl_hdr = ofpbuf_put_zeros(&msg, sizeof *tmpl_hdr);
850                 tmpl_hdr->template_id = htons(
851                     ipfix_get_template_id(l2, l3, l4));
852                 field_count = ipfix_define_template_fields(l2, l3, l4, &msg);
853                 tmpl_hdr = (struct ipfix_template_record_header*)
854                     ((uint8_t*)msg.data + tmpl_hdr_offset);
855                 tmpl_hdr->field_count = htons(field_count);
856             }
857         }
858     }
859
860     set_hdr = (struct ipfix_set_header*)((uint8_t*)msg.data + set_hdr_offset);
861     set_hdr->length = htons(msg.size - set_hdr_offset);
862
863     /* XXX: Add Options Template Sets, at least to define a Flow Keys
864      * Option Template. */
865
866     ipfix_send_msg(exporter->collectors, &msg);
867
868     ofpbuf_uninit(&msg);
869 }
870
871 static inline uint32_t
872 ipfix_hash_flow_key(const struct ipfix_flow_key *flow_key, uint32_t basis)
873 {
874     uint32_t hash;
875     hash = hash_int(flow_key->obs_domain_id, basis);
876     hash = hash_int(flow_key->template_id, hash);
877     hash = hash_bytes(flow_key->flow_key_msg_part,
878                       flow_key->flow_key_msg_part_size, hash);
879     return hash;
880 }
881
882 static bool
883 ipfix_flow_key_equal(const struct ipfix_flow_key *a,
884                      const struct ipfix_flow_key *b)
885 {
886     /* The template ID determines the flow key size, so not need to
887      * compare it. */
888     return (a->obs_domain_id == b->obs_domain_id
889             && a->template_id == b->template_id
890             && memcmp(a->flow_key_msg_part, b->flow_key_msg_part,
891                       a->flow_key_msg_part_size) == 0);
892 }
893
894 static struct ipfix_flow_cache_entry*
895 ipfix_cache_find_entry(const struct dpif_ipfix_exporter *exporter,
896                        const struct ipfix_flow_key *flow_key)
897 {
898     struct ipfix_flow_cache_entry *entry;
899
900     HMAP_FOR_EACH_WITH_HASH (entry, flow_key_map_node,
901                              ipfix_hash_flow_key(flow_key, 0),
902                              &exporter->cache_flow_key_map) {
903         if (ipfix_flow_key_equal(&entry->flow_key, flow_key)) {
904             return entry;
905         }
906     }
907
908     return NULL;
909 }
910
911 static bool
912 ipfix_cache_next_timeout_msec(const struct dpif_ipfix_exporter *exporter,
913                               long long int *next_timeout_msec)
914 {
915     struct ipfix_flow_cache_entry *entry;
916
917     LIST_FOR_EACH (entry, cache_flow_start_timestamp_list_node,
918                    &exporter->cache_flow_start_timestamp_list) {
919         *next_timeout_msec = entry->flow_start_timestamp_usec / 1000LL
920             + 1000LL * exporter->cache_active_timeout;
921         return true;
922     }
923
924     return false;
925 }
926
927 static void
928 ipfix_cache_aggregate_entries(struct ipfix_flow_cache_entry *from_entry,
929                               struct ipfix_flow_cache_entry *to_entry)
930 {
931     uint64_t *to_start, *to_end, *from_start, *from_end;
932     uint16_t *to_min_len, *to_max_len, *from_min_len, *from_max_len;
933
934     to_start = &to_entry->flow_start_timestamp_usec;
935     to_end = &to_entry->flow_end_timestamp_usec;
936     from_start = &from_entry->flow_start_timestamp_usec;
937     from_end = &from_entry->flow_end_timestamp_usec;
938
939     if (*to_start > *from_start) {
940         *to_start = *from_start;
941     }
942     if (*to_end < *from_end) {
943         *to_end = *from_end;
944     }
945
946     to_entry->packet_delta_count += from_entry->packet_delta_count;
947     to_entry->layer2_octet_delta_count += from_entry->layer2_octet_delta_count;
948
949     to_entry->octet_delta_sum_of_squares +=
950         from_entry->octet_delta_sum_of_squares;
951
952     to_min_len = &to_entry->minimum_ip_total_length;
953     to_max_len = &to_entry->maximum_ip_total_length;
954     from_min_len = &from_entry->minimum_ip_total_length;
955     from_max_len = &from_entry->maximum_ip_total_length;
956
957     if (!*to_min_len || (*from_min_len && *to_min_len > *from_min_len)) {
958         *to_min_len = *from_min_len;
959     }
960     if (*to_max_len < *from_max_len) {
961         *to_max_len = *from_max_len;
962     }
963 }
964
965 /* Add an entry into a flow cache.  The entry is either aggregated into
966  * an existing entry with the same flow key and free()d, or it is
967  * inserted into the cache. */
968 static void
969 ipfix_cache_update(struct dpif_ipfix_exporter *exporter,
970                    struct ipfix_flow_cache_entry *entry)
971 {
972     struct ipfix_flow_cache_entry *old_entry;
973
974     old_entry = ipfix_cache_find_entry(exporter, &entry->flow_key);
975
976     if (old_entry == NULL) {
977         hmap_insert(&exporter->cache_flow_key_map, &entry->flow_key_map_node,
978                     ipfix_hash_flow_key(&entry->flow_key, 0));
979
980         /* As the latest entry added into the cache, it should
981          * logically have the highest flow_start_timestamp_usec, so
982          * append it at the tail. */
983         list_push_back(&exporter->cache_flow_start_timestamp_list,
984                        &entry->cache_flow_start_timestamp_list_node);
985
986         /* Enforce exporter->cache_max_flows limit. */
987         if (hmap_count(&exporter->cache_flow_key_map)
988             > exporter->cache_max_flows) {
989             dpif_ipfix_cache_expire_now(exporter, false);
990         }
991     } else {
992         ipfix_cache_aggregate_entries(entry, old_entry);
993         free(entry);
994     }
995 }
996
997 static void
998 ipfix_cache_entry_init(struct ipfix_flow_cache_entry *entry,
999                        struct ofpbuf *packet, const struct flow *flow,
1000                        uint64_t packet_delta_count, uint32_t obs_domain_id,
1001                        uint32_t obs_point_id)
1002 {
1003     struct ipfix_flow_key *flow_key;
1004     struct ofpbuf msg;
1005     enum ipfix_proto_l2 l2;
1006     enum ipfix_proto_l3 l3;
1007     enum ipfix_proto_l4 l4;
1008     uint8_t ethernet_header_length;
1009     uint16_t ethernet_total_length;
1010
1011     flow_key = &entry->flow_key;
1012     ofpbuf_use_stack(&msg, flow_key->flow_key_msg_part,
1013                      sizeof flow_key->flow_key_msg_part);
1014
1015     /* Choose the right template ID matching the protocols in the
1016      * sampled packet. */
1017     l2 = (flow->vlan_tci == 0) ? IPFIX_PROTO_L2_ETH : IPFIX_PROTO_L2_VLAN;
1018
1019     switch(ntohs(flow->dl_type)) {
1020     case ETH_TYPE_IP:
1021         l3 = IPFIX_PROTO_L3_IPV4;
1022         break;
1023     case ETH_TYPE_IPV6:
1024         l3 = IPFIX_PROTO_L3_IPV6;
1025         break;
1026     default:
1027         l3 = IPFIX_PROTO_L3_UNKNOWN;
1028     }
1029
1030     l4 = IPFIX_PROTO_L4_UNKNOWN;
1031     if (l3 != IPFIX_PROTO_L3_UNKNOWN) {
1032         switch(flow->nw_proto) {
1033         case IPPROTO_TCP:  /* TCP */
1034         case IPPROTO_UDP:  /* UDP */
1035             l4 = IPFIX_PROTO_L4_TCP_UDP;
1036             break;
1037         }
1038     }
1039
1040     flow_key->obs_domain_id = obs_domain_id;
1041     flow_key->template_id = ipfix_get_template_id(l2, l3, l4);
1042
1043     /* The fields defined in the ipfix_data_record_* structs and sent
1044      * below must match exactly the templates defined in
1045      * ipfix_define_template_fields. */
1046
1047     ethernet_header_length = (l2 == IPFIX_PROTO_L2_VLAN)
1048         ? VLAN_ETH_HEADER_LEN : ETH_HEADER_LEN;
1049     ethernet_total_length = packet->size;
1050
1051     /* Common Ethernet entities. */
1052     {
1053         struct ipfix_data_record_flow_key_common *data_common;
1054
1055         data_common = ofpbuf_put_zeros(&msg, sizeof *data_common);
1056         data_common->observation_point_id = htonl(obs_point_id);
1057         memcpy(data_common->source_mac_address, flow->dl_src,
1058                sizeof flow->dl_src);
1059         memcpy(data_common->destination_mac_address, flow->dl_dst,
1060                sizeof flow->dl_dst);
1061         data_common->ethernet_type = flow->dl_type;
1062         data_common->ethernet_header_length = ethernet_header_length;
1063     }
1064
1065     if (l2 == IPFIX_PROTO_L2_VLAN) {
1066         struct ipfix_data_record_flow_key_vlan *data_vlan;
1067         uint16_t vlan_id = vlan_tci_to_vid(flow->vlan_tci);
1068         uint8_t priority = vlan_tci_to_pcp(flow->vlan_tci);
1069
1070         data_vlan = ofpbuf_put_zeros(&msg, sizeof *data_vlan);
1071         data_vlan->vlan_id = htons(vlan_id);
1072         data_vlan->dot1q_vlan_id = htons(vlan_id);
1073         data_vlan->dot1q_priority = priority;
1074     }
1075
1076     if (l3 != IPFIX_PROTO_L3_UNKNOWN) {
1077         struct ipfix_data_record_flow_key_ip *data_ip;
1078
1079         data_ip = ofpbuf_put_zeros(&msg, sizeof *data_ip);
1080         data_ip->ip_version = (l3 == IPFIX_PROTO_L3_IPV4) ? 4 : 6;
1081         data_ip->ip_ttl = flow->nw_ttl;
1082         data_ip->protocol_identifier = flow->nw_proto;
1083         data_ip->ip_diff_serv_code_point = flow->nw_tos >> 2;
1084         data_ip->ip_precedence = flow->nw_tos >> 5;
1085         data_ip->ip_class_of_service = flow->nw_tos;
1086
1087         if (l3 == IPFIX_PROTO_L3_IPV4) {
1088             struct ipfix_data_record_flow_key_ipv4 *data_ipv4;
1089             data_ipv4 = ofpbuf_put_zeros(&msg, sizeof *data_ipv4);
1090             data_ipv4->source_ipv4_address = flow->nw_src;
1091             data_ipv4->destination_ipv4_address = flow->nw_dst;
1092         } else {  /* l3 == IPFIX_PROTO_L3_IPV6 */
1093             struct ipfix_data_record_flow_key_ipv6 *data_ipv6;
1094
1095             data_ipv6 = ofpbuf_put_zeros(&msg, sizeof *data_ipv6);
1096             memcpy(data_ipv6->source_ipv6_address, &flow->ipv6_src,
1097                    sizeof flow->ipv6_src);
1098             memcpy(data_ipv6->destination_ipv6_address, &flow->ipv6_dst,
1099                    sizeof flow->ipv6_dst);
1100             data_ipv6->flow_label_ipv6 = flow->ipv6_label;
1101         }
1102     }
1103
1104     if (l4 != IPFIX_PROTO_L4_UNKNOWN) {
1105         struct ipfix_data_record_flow_key_tcpudp *data_tcpudp;
1106
1107         data_tcpudp = ofpbuf_put_zeros(&msg, sizeof *data_tcpudp);
1108         data_tcpudp->source_transport_port = flow->tp_src;
1109         data_tcpudp->destination_transport_port = flow->tp_dst;
1110     }
1111
1112     flow_key->flow_key_msg_part_size = msg.size;
1113
1114     {
1115         struct timeval now;
1116         uint64_t layer2_octet_delta_count;
1117
1118         /* Calculate the total matched octet count by considering as
1119          * an approximation that all matched packets have the same
1120          * length. */
1121         layer2_octet_delta_count = packet_delta_count * ethernet_total_length;
1122
1123         xgettimeofday(&now);
1124         entry->flow_end_timestamp_usec = now.tv_usec + 1000000LL * now.tv_sec;
1125         entry->flow_start_timestamp_usec = entry->flow_end_timestamp_usec;
1126         entry->packet_delta_count = packet_delta_count;
1127         entry->layer2_octet_delta_count = layer2_octet_delta_count;
1128     }
1129
1130     if (l3 != IPFIX_PROTO_L3_UNKNOWN) {
1131         uint16_t ip_total_length =
1132             ethernet_total_length - ethernet_header_length;
1133
1134         entry->octet_delta_sum_of_squares =
1135             packet_delta_count * ip_total_length * ip_total_length;
1136         entry->minimum_ip_total_length = ip_total_length;
1137         entry->maximum_ip_total_length = ip_total_length;
1138     } else {
1139         entry->octet_delta_sum_of_squares = 0;
1140         entry->minimum_ip_total_length = 0;
1141         entry->maximum_ip_total_length = 0;
1142     }
1143 }
1144
1145 /* Send each single data record in its own data set, to simplify the
1146  * implementation by avoiding having to group record by template ID
1147  * before sending. */
1148 static void
1149 ipfix_put_data_set(uint32_t export_time_sec,
1150                    struct ipfix_flow_cache_entry *entry,
1151                    enum ipfix_flow_end_reason flow_end_reason,
1152                    struct ofpbuf *msg)
1153 {
1154     size_t set_hdr_offset;
1155     struct ipfix_set_header *set_hdr;
1156
1157     set_hdr_offset = msg->size;
1158
1159     /* Put a Data Set. */
1160     set_hdr = ofpbuf_put_zeros(msg, sizeof *set_hdr);
1161     set_hdr->set_id = htons(entry->flow_key.template_id);
1162
1163     /* Copy the flow key part of the data record. */
1164
1165     ofpbuf_put(msg, entry->flow_key.flow_key_msg_part,
1166                entry->flow_key.flow_key_msg_part_size);
1167
1168     /* Put the non-key part of the data record. */
1169
1170     {
1171         struct ipfix_data_record_aggregated_common *data_aggregated_common;
1172         uint64_t export_time_usec, flow_start_delta_usec, flow_end_delta_usec;
1173
1174         /* Calculate the negative deltas relative to the export time
1175          * in seconds sent in the header, not the exact export
1176          * time. */
1177         export_time_usec = 1000000LL * export_time_sec;
1178         flow_start_delta_usec = export_time_usec
1179             - entry->flow_start_timestamp_usec;
1180         flow_end_delta_usec = export_time_usec
1181             - entry->flow_end_timestamp_usec;
1182
1183         data_aggregated_common = ofpbuf_put_zeros(
1184             msg, sizeof *data_aggregated_common);
1185         data_aggregated_common->flow_start_delta_microseconds = htonl(
1186             flow_start_delta_usec);
1187         data_aggregated_common->flow_end_delta_microseconds = htonl(
1188             flow_end_delta_usec);
1189         data_aggregated_common->packet_delta_count = htonll(
1190             entry->packet_delta_count);
1191         data_aggregated_common->layer2_octet_delta_count = htonll(
1192             entry->layer2_octet_delta_count);
1193         data_aggregated_common->flow_end_reason = flow_end_reason;
1194     }
1195
1196     if (entry->octet_delta_sum_of_squares) {  /* IP packet. */
1197         struct ipfix_data_record_aggregated_ip *data_aggregated_ip;
1198
1199         data_aggregated_ip = ofpbuf_put_zeros(
1200             msg, sizeof *data_aggregated_ip);
1201         data_aggregated_ip->octet_delta_sum_of_squares = htonll(
1202             entry->octet_delta_sum_of_squares);
1203         data_aggregated_ip->minimum_ip_total_length = htonll(
1204             entry->minimum_ip_total_length);
1205         data_aggregated_ip->maximum_ip_total_length = htonll(
1206             entry->maximum_ip_total_length);
1207     }
1208
1209     set_hdr = (struct ipfix_set_header*)((uint8_t*)msg->data + set_hdr_offset);
1210     set_hdr->length = htons(msg->size - set_hdr_offset);
1211 }
1212
1213 /* Send an IPFIX message with a single data record. */
1214 static void
1215 ipfix_send_data_msg(struct dpif_ipfix_exporter *exporter,
1216                     uint32_t export_time_sec,
1217                     struct ipfix_flow_cache_entry *entry,
1218                     enum ipfix_flow_end_reason flow_end_reason)
1219 {
1220     uint64_t msg_stub[DIV_ROUND_UP(MAX_MESSAGE_LEN, 8)];
1221     struct ofpbuf msg;
1222     ofpbuf_use_stub(&msg, msg_stub, sizeof msg_stub);
1223
1224     ipfix_init_header(export_time_sec, exporter->seq_number++,
1225                       entry->flow_key.obs_domain_id, &msg);
1226     ipfix_put_data_set(export_time_sec, entry, flow_end_reason, &msg);
1227     ipfix_send_msg(exporter->collectors, &msg);
1228
1229     ofpbuf_uninit(&msg);
1230 }
1231
1232 static void
1233 dpif_ipfix_sample(struct dpif_ipfix_exporter *exporter,
1234                   struct ofpbuf *packet, const struct flow *flow,
1235                   uint64_t packet_delta_count, uint32_t obs_domain_id,
1236                   uint32_t obs_point_id)
1237 {
1238     struct ipfix_flow_cache_entry *entry;
1239
1240     /* Create a flow cache entry from the sample. */
1241     entry = xmalloc(sizeof *entry);
1242     ipfix_cache_entry_init(entry, packet, flow, packet_delta_count,
1243                            obs_domain_id, obs_point_id);
1244     ipfix_cache_update(exporter, entry);
1245 }
1246
1247 void
1248 dpif_ipfix_bridge_sample(struct dpif_ipfix *di, struct ofpbuf *packet,
1249                          const struct flow *flow) OVS_EXCLUDED(mutex)
1250 {
1251     uint64_t packet_delta_count;
1252
1253     ovs_mutex_lock(&mutex);
1254     /* Use the sampling probability as an approximation of the number
1255      * of matched packets. */
1256     packet_delta_count = UINT32_MAX / di->bridge_exporter.probability;
1257     dpif_ipfix_sample(&di->bridge_exporter.exporter, packet, flow,
1258                       packet_delta_count,
1259                       di->bridge_exporter.options->obs_domain_id,
1260                       di->bridge_exporter.options->obs_point_id);
1261     ovs_mutex_unlock(&mutex);
1262 }
1263
1264 void
1265 dpif_ipfix_flow_sample(struct dpif_ipfix *di, struct ofpbuf *packet,
1266                        const struct flow *flow, uint32_t collector_set_id,
1267                        uint16_t probability, uint32_t obs_domain_id,
1268                        uint32_t obs_point_id) OVS_EXCLUDED(mutex)
1269 {
1270     struct dpif_ipfix_flow_exporter_map_node *node;
1271     /* Use the sampling probability as an approximation of the number
1272      * of matched packets. */
1273     uint64_t packet_delta_count = USHRT_MAX / probability;
1274
1275     ovs_mutex_lock(&mutex);
1276     node = dpif_ipfix_find_flow_exporter_map_node(di, collector_set_id);
1277     if (node) {
1278         dpif_ipfix_sample(&node->exporter.exporter, packet, flow,
1279                           packet_delta_count, obs_domain_id, obs_point_id);
1280     }
1281     ovs_mutex_unlock(&mutex);
1282 }
1283
1284 static void
1285 dpif_ipfix_cache_expire(struct dpif_ipfix_exporter *exporter,
1286                         bool forced_end, const uint64_t export_time_usec,
1287                         const uint32_t export_time_sec)
1288 {
1289     struct ipfix_flow_cache_entry *entry, *next_entry;
1290     uint64_t max_flow_start_timestamp_usec;
1291     bool template_msg_sent = false;
1292     enum ipfix_flow_end_reason flow_end_reason;
1293
1294     if (list_is_empty(&exporter->cache_flow_start_timestamp_list)) {
1295         return;
1296     }
1297
1298     max_flow_start_timestamp_usec = export_time_usec -
1299         1000000LL * exporter->cache_active_timeout;
1300
1301     LIST_FOR_EACH_SAFE (entry, next_entry, cache_flow_start_timestamp_list_node,
1302                         &exporter->cache_flow_start_timestamp_list) {
1303         if (forced_end) {
1304             flow_end_reason = FORCED_END;
1305         } else if (entry->flow_start_timestamp_usec
1306                    <= max_flow_start_timestamp_usec) {
1307             flow_end_reason = ACTIVE_TIMEOUT;
1308         } else if (hmap_count(&exporter->cache_flow_key_map)
1309                    > exporter->cache_max_flows) {
1310             /* Enforce exporter->cache_max_flows. */
1311             flow_end_reason = LACK_OF_RESOURCES;
1312         } else {
1313             /* Remaining flows haven't expired yet. */
1314             break;
1315         }
1316
1317         list_remove(&entry->cache_flow_start_timestamp_list_node);
1318         hmap_remove(&exporter->cache_flow_key_map,
1319                     &entry->flow_key_map_node);
1320
1321         if (!template_msg_sent
1322             && (exporter->last_template_set_time + IPFIX_TEMPLATE_INTERVAL)
1323                 <= export_time_sec) {
1324             ipfix_send_template_msg(exporter, export_time_sec,
1325                                     entry->flow_key.obs_domain_id);
1326             exporter->last_template_set_time = export_time_sec;
1327             template_msg_sent = true;
1328         }
1329
1330         /* XXX: Group multiple data records for the same obs domain id
1331          * into the same message. */
1332         ipfix_send_data_msg(exporter, export_time_sec, entry, flow_end_reason);
1333         free(entry);
1334     }
1335 }
1336
1337 static void
1338 get_export_time_now(uint64_t *export_time_usec, uint32_t *export_time_sec)
1339 {
1340     struct timeval export_time;
1341     xgettimeofday(&export_time);
1342
1343     *export_time_usec = export_time.tv_usec + 1000000LL * export_time.tv_sec;
1344
1345     /* The IPFIX start and end deltas are negative deltas relative to
1346      * the export time, so set the export time 1 second off to
1347      * calculate those deltas. */
1348     if (export_time.tv_usec == 0) {
1349         *export_time_sec = export_time.tv_sec;
1350     } else {
1351         *export_time_sec = export_time.tv_sec + 1;
1352     }
1353 }
1354
1355 static void
1356 dpif_ipfix_cache_expire_now(struct dpif_ipfix_exporter *exporter,
1357                             bool forced_end)
1358 {
1359     uint64_t export_time_usec;
1360     uint32_t export_time_sec;
1361
1362     get_export_time_now(&export_time_usec, &export_time_sec);
1363     dpif_ipfix_cache_expire(exporter, forced_end, export_time_usec,
1364                             export_time_sec);
1365 }
1366
1367 void
1368 dpif_ipfix_run(struct dpif_ipfix *di) OVS_EXCLUDED(mutex)
1369 {
1370     uint64_t export_time_usec;
1371     uint32_t export_time_sec;
1372     struct dpif_ipfix_flow_exporter_map_node *flow_exporter_node;
1373
1374     ovs_mutex_lock(&mutex);
1375     get_export_time_now(&export_time_usec, &export_time_sec);
1376     if (di->bridge_exporter.probability > 0) {  /* Bridge exporter enabled. */
1377       dpif_ipfix_cache_expire(
1378           &di->bridge_exporter.exporter, false, export_time_usec,
1379           export_time_sec);
1380     }
1381     HMAP_FOR_EACH (flow_exporter_node, node, &di->flow_exporter_map) {
1382         dpif_ipfix_cache_expire(
1383             &flow_exporter_node->exporter.exporter, false, export_time_usec,
1384             export_time_sec);
1385     }
1386     ovs_mutex_unlock(&mutex);
1387 }
1388
1389 void
1390 dpif_ipfix_wait(struct dpif_ipfix *di) OVS_EXCLUDED(mutex)
1391 {
1392     long long int next_timeout_msec = LLONG_MAX;
1393     struct dpif_ipfix_flow_exporter_map_node *flow_exporter_node;
1394
1395     ovs_mutex_lock(&mutex);
1396     if (di->bridge_exporter.probability > 0) {  /* Bridge exporter enabled. */
1397         if (ipfix_cache_next_timeout_msec(
1398                 &di->bridge_exporter.exporter, &next_timeout_msec)) {
1399             poll_timer_wait_until(next_timeout_msec);
1400         }
1401     }
1402     HMAP_FOR_EACH (flow_exporter_node, node, &di->flow_exporter_map) {
1403         if (ipfix_cache_next_timeout_msec(
1404                 &flow_exporter_node->exporter.exporter, &next_timeout_msec)) {
1405             poll_timer_wait_until(next_timeout_msec);
1406         }
1407     }
1408     ovs_mutex_unlock(&mutex);
1409 }