flowprobe: fix L3 header offset calculation for tx flows
[vpp.git] / src / plugins / flowprobe / node.c
1 /*
2  * node.c - ipfix probe graph node
3  *
4  * Copyright (c) 2017 Cisco and/or its affiliates.
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at:
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 #include <vlib/vlib.h>
18 #include <vnet/vnet.h>
19 #include <vppinfra/crc32.h>
20 #include <vppinfra/xxhash.h>
21 #include <vppinfra/error.h>
22 #include <flowprobe/flowprobe.h>
23 #include <vnet/ip/ip6_packet.h>
24 #include <vnet/udp/udp_local.h>
25 #include <vlibmemory/api.h>
26
27 static void flowprobe_export_entry (vlib_main_t * vm, flowprobe_entry_t * e);
28
29 /**
30  * @file node.c
31  * flow record generator graph node
32  */
33
34 typedef struct
35 {
36   /** interface handle */
37   u32 rx_sw_if_index;
38   u32 tx_sw_if_index;
39   /** packet timestamp */
40   u64 timestamp;
41   /** size of the buffer */
42   u16 buffer_size;
43
44   /** L2 information */
45   u8 src_mac[6];
46   u8 dst_mac[6];
47   /** Ethertype */
48   u16 ethertype;
49
50   /** L3 information */
51   ip46_address_t src_address;
52   ip46_address_t dst_address;
53   u8 protocol;
54   u8 tos;
55
56   /** L4 information */
57   u16 src_port;
58   u16 dst_port;
59
60   flowprobe_variant_t which;
61 } flowprobe_trace_t;
62
63 static char *flowprobe_variant_strings[] = {
64   [FLOW_VARIANT_IP4] = "IP4",
65   [FLOW_VARIANT_IP6] = "IP6",
66   [FLOW_VARIANT_L2] = "L2",
67   [FLOW_VARIANT_L2_IP4] = "L2-IP4",
68   [FLOW_VARIANT_L2_IP6] = "L2-IP6",
69 };
70
71 /* packet trace format function */
72 static u8 *
73 format_flowprobe_trace (u8 * s, va_list * args)
74 {
75   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
76   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
77   flowprobe_trace_t *t = va_arg (*args, flowprobe_trace_t *);
78   u32 indent = format_get_indent (s);
79
80   s = format (s,
81               "FLOWPROBE[%s]: rx_sw_if_index %d, tx_sw_if_index %d, "
82               "timestamp %lld, size %d", flowprobe_variant_strings[t->which],
83               t->rx_sw_if_index, t->tx_sw_if_index,
84               t->timestamp, t->buffer_size);
85
86   if (t->which == FLOW_VARIANT_L2)
87     s = format (s, "\n%U -> %U", format_white_space, indent,
88                 format_ethernet_address, &t->src_mac,
89                 format_ethernet_address, &t->dst_mac);
90
91   if (t->protocol > 0
92       && (t->which == FLOW_VARIANT_L2_IP4 || t->which == FLOW_VARIANT_IP4
93           || t->which == FLOW_VARIANT_L2_IP6 || t->which == FLOW_VARIANT_IP6))
94     s =
95       format (s, "\n%U%U: %U -> %U", format_white_space, indent,
96               format_ip_protocol, t->protocol, format_ip46_address,
97               &t->src_address, IP46_TYPE_ANY, format_ip46_address,
98               &t->dst_address, IP46_TYPE_ANY);
99   return s;
100 }
101
102 vlib_node_registration_t flowprobe_input_ip4_node;
103 vlib_node_registration_t flowprobe_input_ip6_node;
104 vlib_node_registration_t flowprobe_input_l2_node;
105 vlib_node_registration_t flowprobe_output_ip4_node;
106 vlib_node_registration_t flowprobe_output_ip6_node;
107 vlib_node_registration_t flowprobe_output_l2_node;
108
109 /* No counters at the moment */
110 #define foreach_flowprobe_error                 \
111 _(COLLISION, "Hash table collisions")           \
112 _(BUFFER, "Buffer allocation error")            \
113 _(EXPORTED_PACKETS, "Exported packets")         \
114 _(INPATH, "Exported packets in path")
115
116 typedef enum
117 {
118 #define _(sym,str) FLOWPROBE_ERROR_##sym,
119   foreach_flowprobe_error
120 #undef _
121     FLOWPROBE_N_ERROR,
122 } flowprobe_error_t;
123
124 static char *flowprobe_error_strings[] = {
125 #define _(sym,string) string,
126   foreach_flowprobe_error
127 #undef _
128 };
129
130 typedef enum
131 {
132   FLOWPROBE_NEXT_DROP,
133   FLOWPROBE_NEXT_IP4_LOOKUP,
134   FLOWPROBE_N_NEXT,
135 } flowprobe_next_t;
136
137 #define FLOWPROBE_NEXT_NODES {                                  \
138     [FLOWPROBE_NEXT_DROP] = "error-drop",                       \
139     [FLOWPROBE_NEXT_IP4_LOOKUP] = "ip4-lookup",         \
140 }
141
142 static inline flowprobe_variant_t
143 flowprobe_get_variant (flowprobe_variant_t which,
144                        flowprobe_record_t flags, u16 ethertype)
145 {
146   if (which == FLOW_VARIANT_L2
147       && (flags & FLOW_RECORD_L3 || flags & FLOW_RECORD_L4))
148     return ethertype == ETHERNET_TYPE_IP6 ? FLOW_VARIANT_L2_IP6 : ethertype ==
149       ETHERNET_TYPE_IP4 ? FLOW_VARIANT_L2_IP4 : FLOW_VARIANT_L2;
150   return which;
151 }
152
153 /*
154  * NTP rfc868 : 2 208 988 800 corresponds to 00:00  1 Jan 1970 GMT
155  */
156 #define NTP_TIMESTAMP 2208988800LU
157
158 static inline u32
159 flowprobe_common_add (vlib_buffer_t * to_b, flowprobe_entry_t * e, u16 offset)
160 {
161   u16 start = offset;
162
163   /* Ingress interface */
164   u32 rx_if = clib_host_to_net_u32 (e->key.rx_sw_if_index);
165   clib_memcpy_fast (to_b->data + offset, &rx_if, sizeof (rx_if));
166   offset += sizeof (rx_if);
167
168   /* Egress interface */
169   u32 tx_if = clib_host_to_net_u32 (e->key.tx_sw_if_index);
170   clib_memcpy_fast (to_b->data + offset, &tx_if, sizeof (tx_if));
171   offset += sizeof (tx_if);
172
173   /* Flow direction
174      0x00: ingress flow
175      0x01: egress flow */
176   to_b->data[offset++] = (e->key.direction == FLOW_DIRECTION_TX);
177
178   /* packet delta count */
179   u64 packetdelta = clib_host_to_net_u64 (e->packetcount);
180   clib_memcpy_fast (to_b->data + offset, &packetdelta, sizeof (u64));
181   offset += sizeof (u64);
182
183   /* flowStartNanoseconds */
184   u32 t = clib_host_to_net_u32 (e->flow_start.sec + NTP_TIMESTAMP);
185   clib_memcpy_fast (to_b->data + offset, &t, sizeof (u32));
186   offset += sizeof (u32);
187   t = clib_host_to_net_u32 (e->flow_start.nsec);
188   clib_memcpy_fast (to_b->data + offset, &t, sizeof (u32));
189   offset += sizeof (u32);
190
191   /* flowEndNanoseconds */
192   t = clib_host_to_net_u32 (e->flow_end.sec + NTP_TIMESTAMP);
193   clib_memcpy_fast (to_b->data + offset, &t, sizeof (u32));
194   offset += sizeof (u32);
195   t = clib_host_to_net_u32 (e->flow_end.nsec);
196   clib_memcpy_fast (to_b->data + offset, &t, sizeof (u32));
197   offset += sizeof (u32);
198
199   return offset - start;
200 }
201
202 static inline u32
203 flowprobe_l2_add (vlib_buffer_t * to_b, flowprobe_entry_t * e, u16 offset)
204 {
205   u16 start = offset;
206
207   /* src mac address */
208   clib_memcpy_fast (to_b->data + offset, &e->key.src_mac, 6);
209   offset += 6;
210
211   /* dst mac address */
212   clib_memcpy_fast (to_b->data + offset, &e->key.dst_mac, 6);
213   offset += 6;
214
215   /* ethertype */
216   clib_memcpy_fast (to_b->data + offset, &e->key.ethertype, 2);
217   offset += 2;
218
219   return offset - start;
220 }
221
222 static inline u32
223 flowprobe_l3_ip6_add (vlib_buffer_t * to_b, flowprobe_entry_t * e, u16 offset)
224 {
225   u16 start = offset;
226
227   /* ip6 src address */
228   clib_memcpy_fast (to_b->data + offset, &e->key.src_address,
229                     sizeof (ip6_address_t));
230   offset += sizeof (ip6_address_t);
231
232   /* ip6 dst address */
233   clib_memcpy_fast (to_b->data + offset, &e->key.dst_address,
234                     sizeof (ip6_address_t));
235   offset += sizeof (ip6_address_t);
236
237   /* Protocol */
238   to_b->data[offset++] = e->key.protocol;
239
240   /* octetDeltaCount */
241   u64 octetdelta = clib_host_to_net_u64 (e->octetcount);
242   clib_memcpy_fast (to_b->data + offset, &octetdelta, sizeof (u64));
243   offset += sizeof (u64);
244
245   return offset - start;
246 }
247
248 static inline u32
249 flowprobe_l3_ip4_add (vlib_buffer_t * to_b, flowprobe_entry_t * e, u16 offset)
250 {
251   u16 start = offset;
252
253   /* ip4 src address */
254   clib_memcpy_fast (to_b->data + offset, &e->key.src_address.ip4,
255                     sizeof (ip4_address_t));
256   offset += sizeof (ip4_address_t);
257
258   /* ip4 dst address */
259   clib_memcpy_fast (to_b->data + offset, &e->key.dst_address.ip4,
260                     sizeof (ip4_address_t));
261   offset += sizeof (ip4_address_t);
262
263   /* Protocol */
264   to_b->data[offset++] = e->key.protocol;
265
266   /* octetDeltaCount */
267   u64 octetdelta = clib_host_to_net_u64 (e->octetcount);
268   clib_memcpy_fast (to_b->data + offset, &octetdelta, sizeof (u64));
269   offset += sizeof (u64);
270
271   return offset - start;
272 }
273
274 static inline u32
275 flowprobe_l4_add (vlib_buffer_t * to_b, flowprobe_entry_t * e, u16 offset)
276 {
277   u16 start = offset;
278
279   /* src port */
280   clib_memcpy_fast (to_b->data + offset, &e->key.src_port, 2);
281   offset += 2;
282
283   /* dst port */
284   clib_memcpy_fast (to_b->data + offset, &e->key.dst_port, 2);
285   offset += 2;
286
287   /* tcp control bits */
288   u16 control_bits = htons (e->prot.tcp.flags);
289   clib_memcpy_fast (to_b->data + offset, &control_bits, 2);
290   offset += 2;
291
292   return offset - start;
293 }
294
295 static inline u32
296 flowprobe_hash (flowprobe_key_t * k)
297 {
298   flowprobe_main_t *fm = &flowprobe_main;
299   u32 h = 0;
300
301 #ifdef clib_crc32c_uses_intrinsics
302   h = clib_crc32c ((u8 *) k, sizeof (*k));
303 #else
304   int i;
305   u64 tmp = 0;
306   for (i = 0; i < sizeof (*k) / 8; i++)
307     tmp ^= ((u64 *) k)[i];
308
309   h = clib_xxhash (tmp);
310 #endif
311
312   return h >> (32 - fm->ht_log2len);
313 }
314
315 flowprobe_entry_t *
316 flowprobe_lookup (u32 my_cpu_number, flowprobe_key_t * k, u32 * poolindex,
317                   bool * collision)
318 {
319   flowprobe_main_t *fm = &flowprobe_main;
320   flowprobe_entry_t *e;
321   u32 h;
322
323   h = (fm->active_timer) ? flowprobe_hash (k) : 0;
324
325   /* Lookup in the flow state pool */
326   *poolindex = fm->hash_per_worker[my_cpu_number][h];
327   if (*poolindex != ~0)
328     {
329       e = pool_elt_at_index (fm->pool_per_worker[my_cpu_number], *poolindex);
330       if (e)
331         {
332           /* Verify key or report collision */
333           if (memcmp (k, &e->key, sizeof (flowprobe_key_t)))
334             *collision = true;
335           return e;
336         }
337     }
338
339   return 0;
340 }
341
342 flowprobe_entry_t *
343 flowprobe_create (u32 my_cpu_number, flowprobe_key_t * k, u32 * poolindex)
344 {
345   flowprobe_main_t *fm = &flowprobe_main;
346   u32 h;
347
348   flowprobe_entry_t *e;
349
350   /* Get my index */
351   h = (fm->active_timer) ? flowprobe_hash (k) : 0;
352
353   pool_get (fm->pool_per_worker[my_cpu_number], e);
354   *poolindex = e - fm->pool_per_worker[my_cpu_number];
355   fm->hash_per_worker[my_cpu_number][h] = *poolindex;
356
357   e->key = *k;
358
359   if (fm->passive_timer > 0)
360     {
361       e->passive_timer_handle = tw_timer_start_2t_1w_2048sl
362         (fm->timers_per_worker[my_cpu_number], *poolindex, 0,
363          fm->passive_timer);
364     }
365   return e;
366 }
367
368 static inline void
369 add_to_flow_record_state (vlib_main_t *vm, vlib_node_runtime_t *node,
370                           flowprobe_main_t *fm, vlib_buffer_t *b,
371                           timestamp_nsec_t timestamp, u16 length,
372                           flowprobe_variant_t which,
373                           flowprobe_direction_t direction,
374                           flowprobe_trace_t *t)
375 {
376   if (fm->disabled)
377     return;
378
379   ASSERT (direction == FLOW_DIRECTION_RX || direction == FLOW_DIRECTION_TX);
380
381   u32 my_cpu_number = vm->thread_index;
382   u16 octets = 0;
383
384   flowprobe_record_t flags = fm->context[which].flags;
385   bool collect_ip4 = false, collect_ip6 = false;
386   ASSERT (b);
387   ethernet_header_t *eth = (direction == FLOW_DIRECTION_TX) ?
388                                    vlib_buffer_get_current (b) :
389                                    ethernet_buffer_get_header (b);
390   u16 ethertype = clib_net_to_host_u16 (eth->type);
391   i16 l3_hdr_offset = (u8 *) eth - b->data + sizeof (ethernet_header_t);
392   /* *INDENT-OFF* */
393   flowprobe_key_t k = {};
394   /* *INDENT-ON* */
395   ip4_header_t *ip4 = 0;
396   ip6_header_t *ip6 = 0;
397   udp_header_t *udp = 0;
398   tcp_header_t *tcp = 0;
399   u8 tcp_flags = 0;
400
401   if (flags & FLOW_RECORD_L3 || flags & FLOW_RECORD_L4)
402     {
403       collect_ip4 = which == FLOW_VARIANT_L2_IP4 || which == FLOW_VARIANT_IP4;
404       collect_ip6 = which == FLOW_VARIANT_L2_IP6 || which == FLOW_VARIANT_IP6;
405     }
406
407   k.rx_sw_if_index = vnet_buffer (b)->sw_if_index[VLIB_RX];
408   k.tx_sw_if_index = vnet_buffer (b)->sw_if_index[VLIB_TX];
409
410   k.which = which;
411   k.direction = direction;
412
413   if (flags & FLOW_RECORD_L2)
414     {
415       clib_memcpy_fast (k.src_mac, eth->src_address, 6);
416       clib_memcpy_fast (k.dst_mac, eth->dst_address, 6);
417       k.ethertype = ethertype;
418     }
419   if (ethertype == ETHERNET_TYPE_VLAN)
420     {
421       /*VLAN TAG*/
422       ethernet_vlan_header_tv_t *ethv =
423         (ethernet_vlan_header_tv_t *) (&(eth->type));
424       /*Q in Q possibility */
425       while (clib_net_to_host_u16 (ethv->type) == ETHERNET_TYPE_VLAN)
426         {
427           ethv++;
428           l3_hdr_offset += sizeof (ethernet_vlan_header_tv_t);
429         }
430       k.ethertype = ethertype = clib_net_to_host_u16 ((ethv)->type);
431     }
432   if (collect_ip6 && ethertype == ETHERNET_TYPE_IP6)
433     {
434       ip6 = (ip6_header_t *) (b->data + l3_hdr_offset);
435       if (flags & FLOW_RECORD_L3)
436         {
437           k.src_address.as_u64[0] = ip6->src_address.as_u64[0];
438           k.src_address.as_u64[1] = ip6->src_address.as_u64[1];
439           k.dst_address.as_u64[0] = ip6->dst_address.as_u64[0];
440           k.dst_address.as_u64[1] = ip6->dst_address.as_u64[1];
441         }
442       k.protocol = ip6->protocol;
443       if (k.protocol == IP_PROTOCOL_UDP)
444         udp = (udp_header_t *) (ip6 + 1);
445       else if (k.protocol == IP_PROTOCOL_TCP)
446         tcp = (tcp_header_t *) (ip6 + 1);
447
448       octets = clib_net_to_host_u16 (ip6->payload_length)
449         + sizeof (ip6_header_t);
450     }
451   if (collect_ip4 && ethertype == ETHERNET_TYPE_IP4)
452     {
453       ip4 = (ip4_header_t *) (b->data + l3_hdr_offset);
454       if (flags & FLOW_RECORD_L3)
455         {
456           k.src_address.ip4.as_u32 = ip4->src_address.as_u32;
457           k.dst_address.ip4.as_u32 = ip4->dst_address.as_u32;
458         }
459       k.protocol = ip4->protocol;
460       if ((flags & FLOW_RECORD_L4) && k.protocol == IP_PROTOCOL_UDP)
461         udp = (udp_header_t *) (ip4 + 1);
462       else if ((flags & FLOW_RECORD_L4) && k.protocol == IP_PROTOCOL_TCP)
463         tcp = (tcp_header_t *) (ip4 + 1);
464
465       octets = clib_net_to_host_u16 (ip4->length);
466     }
467
468   if (udp)
469     {
470       k.src_port = udp->src_port;
471       k.dst_port = udp->dst_port;
472     }
473   else if (tcp)
474     {
475       k.src_port = tcp->src_port;
476       k.dst_port = tcp->dst_port;
477       tcp_flags = tcp->flags;
478     }
479
480   if (t)
481     {
482       t->rx_sw_if_index = k.rx_sw_if_index;
483       t->tx_sw_if_index = k.tx_sw_if_index;
484       clib_memcpy_fast (t->src_mac, k.src_mac, 6);
485       clib_memcpy_fast (t->dst_mac, k.dst_mac, 6);
486       t->ethertype = k.ethertype;
487       t->src_address.ip4.as_u32 = k.src_address.ip4.as_u32;
488       t->dst_address.ip4.as_u32 = k.dst_address.ip4.as_u32;
489       t->protocol = k.protocol;
490       t->src_port = k.src_port;
491       t->dst_port = k.dst_port;
492       t->which = k.which;
493     }
494
495   flowprobe_entry_t *e = 0;
496   f64 now = vlib_time_now (vm);
497   if (fm->active_timer > 0)
498     {
499       u32 poolindex = ~0;
500       bool collision = false;
501
502       e = flowprobe_lookup (my_cpu_number, &k, &poolindex, &collision);
503       if (collision)
504         {
505           /* Flush data and clean up entry for reuse. */
506           if (e->packetcount)
507             flowprobe_export_entry (vm, e);
508           e->key = k;
509           e->flow_start = timestamp;
510           vlib_node_increment_counter (vm, node->node_index,
511                                        FLOWPROBE_ERROR_COLLISION, 1);
512         }
513       if (!e)                   /* Create new entry */
514         {
515           e = flowprobe_create (my_cpu_number, &k, &poolindex);
516           e->last_exported = now;
517           e->flow_start = timestamp;
518         }
519     }
520   else
521     {
522       e = &fm->stateless_entry[my_cpu_number];
523       e->key = k;
524     }
525
526   if (e)
527     {
528       /* Updating entry */
529       e->packetcount++;
530       e->octetcount += octets;
531       e->last_updated = now;
532       e->flow_end = timestamp;
533       e->prot.tcp.flags |= tcp_flags;
534       if (fm->active_timer == 0
535           || (now > e->last_exported + fm->active_timer))
536         flowprobe_export_entry (vm, e);
537     }
538 }
539
540 static u16
541 flowprobe_get_headersize (void)
542 {
543   return sizeof (ip4_header_t) + sizeof (udp_header_t) +
544     sizeof (ipfix_message_header_t) + sizeof (ipfix_set_header_t);
545 }
546
547 static void
548 flowprobe_export_send (vlib_main_t * vm, vlib_buffer_t * b0,
549                        flowprobe_variant_t which)
550 {
551   flowprobe_main_t *fm = &flowprobe_main;
552   flow_report_main_t *frm = &flow_report_main;
553   ipfix_exporter_t *exp = pool_elt_at_index (frm->exporters, 0);
554   vlib_frame_t *f;
555   ip4_ipfix_template_packet_t *tp;
556   ipfix_set_header_t *s;
557   ipfix_message_header_t *h;
558   ip4_header_t *ip;
559   udp_header_t *udp;
560   flowprobe_record_t flags = fm->context[which].flags;
561   u32 my_cpu_number = vm->thread_index;
562
563   /* Fill in header */
564   flow_report_stream_t *stream;
565
566   /* Nothing to send */
567   if (fm->context[which].next_record_offset_per_worker[my_cpu_number] <=
568       flowprobe_get_headersize ())
569     return;
570
571   u32 i, index = vec_len (exp->streams);
572   for (i = 0; i < index; i++)
573     if (exp->streams[i].domain_id == 1)
574       {
575         index = i;
576         break;
577       }
578   if (i == vec_len (exp->streams))
579     {
580       vec_validate (exp->streams, index);
581       exp->streams[index].domain_id = 1;
582     }
583   stream = &exp->streams[index];
584
585   tp = vlib_buffer_get_current (b0);
586   ip = (ip4_header_t *) & tp->ip4;
587   udp = (udp_header_t *) (ip + 1);
588   h = (ipfix_message_header_t *) (udp + 1);
589   s = (ipfix_set_header_t *) (h + 1);
590
591   ip->ip_version_and_header_length = 0x45;
592   ip->ttl = 254;
593   ip->protocol = IP_PROTOCOL_UDP;
594   ip->flags_and_fragment_offset = 0;
595   ip->src_address.as_u32 = exp->src_address.ip.ip4.as_u32;
596   ip->dst_address.as_u32 = exp->ipfix_collector.ip.ip4.as_u32;
597   udp->src_port = clib_host_to_net_u16 (stream->src_port);
598   udp->dst_port = clib_host_to_net_u16 (exp->collector_port);
599   udp->checksum = 0;
600
601   /* FIXUP: message header export_time */
602   h->export_time = (u32)
603     (((f64) frm->unix_time_0) +
604      (vlib_time_now (frm->vlib_main) - frm->vlib_time_0));
605   h->export_time = clib_host_to_net_u32 (h->export_time);
606   h->domain_id = clib_host_to_net_u32 (stream->domain_id);
607
608   /* FIXUP: message header sequence_number */
609   h->sequence_number = stream->sequence_number++;
610   h->sequence_number = clib_host_to_net_u32 (h->sequence_number);
611
612   s->set_id_length = ipfix_set_id_length (fm->template_reports[flags],
613                                           b0->current_length -
614                                           (sizeof (*ip) + sizeof (*udp) +
615                                            sizeof (*h)));
616   h->version_length = version_length (b0->current_length -
617                                       (sizeof (*ip) + sizeof (*udp)));
618
619   ip->length = clib_host_to_net_u16 (b0->current_length);
620
621   ip->checksum = ip4_header_checksum (ip);
622   udp->length = clib_host_to_net_u16 (b0->current_length - sizeof (*ip));
623
624   if (exp->udp_checksum)
625     {
626       /* RFC 7011 section 10.3.2. */
627       udp->checksum = ip4_tcp_udp_compute_checksum (vm, b0, ip);
628       if (udp->checksum == 0)
629         udp->checksum = 0xffff;
630     }
631
632   ASSERT (ip4_header_checksum_is_valid (ip));
633
634   /* Find or allocate a frame */
635   f = fm->context[which].frames_per_worker[my_cpu_number];
636   if (PREDICT_FALSE (f == 0))
637     {
638       u32 *to_next;
639       f = vlib_get_frame_to_node (vm, ip4_lookup_node.index);
640       fm->context[which].frames_per_worker[my_cpu_number] = f;
641       u32 bi0 = vlib_get_buffer_index (vm, b0);
642
643       /* Enqueue the buffer */
644       to_next = vlib_frame_vector_args (f);
645       to_next[0] = bi0;
646       f->n_vectors = 1;
647     }
648
649   vlib_put_frame_to_node (vm, ip4_lookup_node.index, f);
650   vlib_node_increment_counter (vm, flowprobe_output_l2_node.index,
651                                FLOWPROBE_ERROR_EXPORTED_PACKETS, 1);
652
653   fm->context[which].frames_per_worker[my_cpu_number] = 0;
654   fm->context[which].buffers_per_worker[my_cpu_number] = 0;
655   fm->context[which].next_record_offset_per_worker[my_cpu_number] =
656     flowprobe_get_headersize ();
657 }
658
659 static vlib_buffer_t *
660 flowprobe_get_buffer (vlib_main_t * vm, flowprobe_variant_t which)
661 {
662   flowprobe_main_t *fm = &flowprobe_main;
663   ipfix_exporter_t *exp = pool_elt_at_index (flow_report_main.exporters, 0);
664   vlib_buffer_t *b0;
665   u32 bi0;
666   u32 my_cpu_number = vm->thread_index;
667
668   /* Find or allocate a buffer */
669   b0 = fm->context[which].buffers_per_worker[my_cpu_number];
670
671   /* Need to allocate a buffer? */
672   if (PREDICT_FALSE (b0 == 0))
673     {
674       if (vlib_buffer_alloc (vm, &bi0, 1) != 1)
675         {
676           vlib_node_increment_counter (vm, flowprobe_output_l2_node.index,
677                                        FLOWPROBE_ERROR_BUFFER, 1);
678           return 0;
679         }
680
681       /* Initialize the buffer */
682       b0 = fm->context[which].buffers_per_worker[my_cpu_number] =
683         vlib_get_buffer (vm, bi0);
684
685       b0->current_data = 0;
686       b0->current_length = flowprobe_get_headersize ();
687       b0->flags |=
688         (VLIB_BUFFER_TOTAL_LENGTH_VALID | VNET_BUFFER_F_FLOW_REPORT);
689       vnet_buffer (b0)->sw_if_index[VLIB_RX] = 0;
690       vnet_buffer (b0)->sw_if_index[VLIB_TX] = exp->fib_index;
691       fm->context[which].next_record_offset_per_worker[my_cpu_number] =
692         b0->current_length;
693     }
694
695   return b0;
696 }
697
698 static void
699 flowprobe_export_entry (vlib_main_t * vm, flowprobe_entry_t * e)
700 {
701   u32 my_cpu_number = vm->thread_index;
702   flowprobe_main_t *fm = &flowprobe_main;
703   ipfix_exporter_t *exp = pool_elt_at_index (flow_report_main.exporters, 0);
704   vlib_buffer_t *b0;
705   bool collect_ip4 = false, collect_ip6 = false;
706   bool collect_l4 = false;
707   flowprobe_variant_t which = e->key.which;
708   flowprobe_record_t flags = fm->context[which].flags;
709   u16 offset =
710     fm->context[which].next_record_offset_per_worker[my_cpu_number];
711
712   if (offset < flowprobe_get_headersize ())
713     offset = flowprobe_get_headersize ();
714
715   b0 = flowprobe_get_buffer (vm, which);
716   /* No available buffer, what to do... */
717   if (b0 == 0)
718     return;
719
720   if (flags & FLOW_RECORD_L3)
721     {
722       collect_ip4 = which == FLOW_VARIANT_L2_IP4 || which == FLOW_VARIANT_IP4;
723       collect_ip6 = which == FLOW_VARIANT_L2_IP6 || which == FLOW_VARIANT_IP6;
724     }
725   if (flags & FLOW_RECORD_L4)
726     {
727       collect_l4 = (which != FLOW_VARIANT_L2);
728     }
729
730   offset += flowprobe_common_add (b0, e, offset);
731
732   if (flags & FLOW_RECORD_L2)
733     offset += flowprobe_l2_add (b0, e, offset);
734   if (collect_ip6)
735     offset += flowprobe_l3_ip6_add (b0, e, offset);
736   if (collect_ip4)
737     offset += flowprobe_l3_ip4_add (b0, e, offset);
738   if (collect_l4)
739     offset += flowprobe_l4_add (b0, e, offset);
740
741   /* Reset per flow-export counters */
742   e->packetcount = 0;
743   e->octetcount = 0;
744   e->last_exported = vlib_time_now (vm);
745   e->prot.tcp.flags = 0;
746
747   b0->current_length = offset;
748
749   fm->context[which].next_record_offset_per_worker[my_cpu_number] = offset;
750   /* Time to flush the buffer? */
751   if (offset + fm->template_size[flags] > exp->path_mtu)
752     flowprobe_export_send (vm, b0, which);
753 }
754
755 uword
756 flowprobe_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
757                    vlib_frame_t *frame, flowprobe_variant_t which,
758                    flowprobe_direction_t direction)
759 {
760   u32 n_left_from, *from, *to_next;
761   flowprobe_next_t next_index;
762   flowprobe_main_t *fm = &flowprobe_main;
763   timestamp_nsec_t timestamp;
764
765   unix_time_now_nsec_fraction (&timestamp.sec, &timestamp.nsec);
766
767   from = vlib_frame_vector_args (frame);
768   n_left_from = frame->n_vectors;
769   next_index = node->cached_next_index;
770
771   while (n_left_from > 0)
772     {
773       u32 n_left_to_next;
774
775       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
776
777       while (n_left_from >= 4 && n_left_to_next >= 2)
778         {
779           u32 next0 = FLOWPROBE_NEXT_DROP;
780           u32 next1 = FLOWPROBE_NEXT_DROP;
781           u16 len0, len1;
782           u32 bi0, bi1;
783           vlib_buffer_t *b0, *b1;
784
785           /* Prefetch next iteration. */
786           {
787             vlib_buffer_t *p2, *p3;
788
789             p2 = vlib_get_buffer (vm, from[2]);
790             p3 = vlib_get_buffer (vm, from[3]);
791
792             vlib_prefetch_buffer_header (p2, LOAD);
793             vlib_prefetch_buffer_header (p3, LOAD);
794
795             clib_prefetch_store (p2->data);
796             clib_prefetch_store (p3->data);
797           }
798
799           /* speculatively enqueue b0 and b1 to the current next frame */
800           to_next[0] = bi0 = from[0];
801           to_next[1] = bi1 = from[1];
802           from += 2;
803           to_next += 2;
804           n_left_from -= 2;
805           n_left_to_next -= 2;
806
807           b0 = vlib_get_buffer (vm, bi0);
808           b1 = vlib_get_buffer (vm, bi1);
809
810           vnet_feature_next (&next0, b0);
811           vnet_feature_next (&next1, b1);
812
813           len0 = vlib_buffer_length_in_chain (vm, b0);
814           ethernet_header_t *eh0 = vlib_buffer_get_current (b0);
815           u16 ethertype0 = clib_net_to_host_u16 (eh0->type);
816
817           if (PREDICT_TRUE ((b0->flags & VNET_BUFFER_F_FLOW_REPORT) == 0))
818             add_to_flow_record_state (
819               vm, node, fm, b0, timestamp, len0,
820               flowprobe_get_variant (which, fm->context[which].flags,
821                                      ethertype0),
822               direction, 0);
823
824           len1 = vlib_buffer_length_in_chain (vm, b1);
825           ethernet_header_t *eh1 = vlib_buffer_get_current (b1);
826           u16 ethertype1 = clib_net_to_host_u16 (eh1->type);
827
828           if (PREDICT_TRUE ((b1->flags & VNET_BUFFER_F_FLOW_REPORT) == 0))
829             add_to_flow_record_state (
830               vm, node, fm, b1, timestamp, len1,
831               flowprobe_get_variant (which, fm->context[which].flags,
832                                      ethertype1),
833               direction, 0);
834
835           /* verify speculative enqueues, maybe switch current next frame */
836           vlib_validate_buffer_enqueue_x2 (vm, node, next_index,
837                                            to_next, n_left_to_next,
838                                            bi0, bi1, next0, next1);
839         }
840
841       while (n_left_from > 0 && n_left_to_next > 0)
842         {
843           u32 bi0;
844           vlib_buffer_t *b0;
845           u32 next0 = FLOWPROBE_NEXT_DROP;
846           u16 len0;
847
848           /* speculatively enqueue b0 to the current next frame */
849           bi0 = from[0];
850           to_next[0] = bi0;
851           from += 1;
852           to_next += 1;
853           n_left_from -= 1;
854           n_left_to_next -= 1;
855
856           b0 = vlib_get_buffer (vm, bi0);
857
858           vnet_feature_next (&next0, b0);
859
860           len0 = vlib_buffer_length_in_chain (vm, b0);
861           ethernet_header_t *eh0 = vlib_buffer_get_current (b0);
862           u16 ethertype0 = clib_net_to_host_u16 (eh0->type);
863
864           if (PREDICT_TRUE ((b0->flags & VNET_BUFFER_F_FLOW_REPORT) == 0))
865             {
866               flowprobe_trace_t *t = 0;
867               if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
868                                  && (b0->flags & VLIB_BUFFER_IS_TRACED)))
869                 t = vlib_add_trace (vm, node, b0, sizeof (*t));
870
871               add_to_flow_record_state (
872                 vm, node, fm, b0, timestamp, len0,
873                 flowprobe_get_variant (which, fm->context[which].flags,
874                                        ethertype0),
875                 direction, t);
876             }
877
878           /* verify speculative enqueue, maybe switch current next frame */
879           vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
880                                            to_next, n_left_to_next,
881                                            bi0, next0);
882         }
883
884       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
885     }
886   return frame->n_vectors;
887 }
888
889 static uword
890 flowprobe_input_ip4_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
891                              vlib_frame_t *frame)
892 {
893   return flowprobe_node_fn (vm, node, frame, FLOW_VARIANT_IP4,
894                             FLOW_DIRECTION_RX);
895 }
896
897 static uword
898 flowprobe_input_ip6_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
899                              vlib_frame_t *frame)
900 {
901   return flowprobe_node_fn (vm, node, frame, FLOW_VARIANT_IP6,
902                             FLOW_DIRECTION_RX);
903 }
904
905 static uword
906 flowprobe_input_l2_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
907                             vlib_frame_t *frame)
908 {
909   return flowprobe_node_fn (vm, node, frame, FLOW_VARIANT_L2,
910                             FLOW_DIRECTION_RX);
911 }
912
913 static uword
914 flowprobe_output_ip4_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
915                               vlib_frame_t *frame)
916 {
917   return flowprobe_node_fn (vm, node, frame, FLOW_VARIANT_IP4,
918                             FLOW_DIRECTION_TX);
919 }
920
921 static uword
922 flowprobe_output_ip6_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
923                               vlib_frame_t *frame)
924 {
925   return flowprobe_node_fn (vm, node, frame, FLOW_VARIANT_IP6,
926                             FLOW_DIRECTION_TX);
927 }
928
929 static uword
930 flowprobe_output_l2_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
931                              vlib_frame_t *frame)
932 {
933   return flowprobe_node_fn (vm, node, frame, FLOW_VARIANT_L2,
934                             FLOW_DIRECTION_TX);
935 }
936
937 static inline void
938 flush_record (flowprobe_variant_t which)
939 {
940   vlib_main_t *vm = vlib_get_main ();
941   vlib_buffer_t *b = flowprobe_get_buffer (vm, which);
942   if (b)
943     flowprobe_export_send (vm, b, which);
944 }
945
946 void
947 flowprobe_flush_callback_ip4 (void)
948 {
949   flush_record (FLOW_VARIANT_IP4);
950 }
951
952 void
953 flowprobe_flush_callback_ip6 (void)
954 {
955   flush_record (FLOW_VARIANT_IP6);
956 }
957
958 void
959 flowprobe_flush_callback_l2 (void)
960 {
961   flush_record (FLOW_VARIANT_L2);
962   flush_record (FLOW_VARIANT_L2_IP4);
963   flush_record (FLOW_VARIANT_L2_IP6);
964 }
965
966 void
967 flowprobe_delete_by_index (u32 my_cpu_number, u32 poolindex)
968 {
969   flowprobe_main_t *fm = &flowprobe_main;
970   flowprobe_entry_t *e;
971   u32 h;
972
973   e = pool_elt_at_index (fm->pool_per_worker[my_cpu_number], poolindex);
974
975   /* Get my index */
976   h = flowprobe_hash (&e->key);
977
978   /* Reset hash */
979   fm->hash_per_worker[my_cpu_number][h] = ~0;
980
981   pool_put_index (fm->pool_per_worker[my_cpu_number], poolindex);
982 }
983
984
985 /* Per worker process processing the active/passive expired entries */
986 static uword
987 flowprobe_walker_process (vlib_main_t * vm,
988                           vlib_node_runtime_t * rt, vlib_frame_t * f)
989 {
990   flowprobe_main_t *fm = &flowprobe_main;
991   flowprobe_entry_t *e;
992   ipfix_exporter_t *exp = pool_elt_at_index (flow_report_main.exporters, 0);
993
994   /*
995    * $$$$ Remove this check from here and track FRM status and disable
996    * this process if required.
997    */
998   if (ip_address_is_zero (&exp->ipfix_collector) ||
999       ip_address_is_zero (&exp->src_address))
1000     {
1001       fm->disabled = true;
1002       return 0;
1003     }
1004   fm->disabled = false;
1005
1006   u32 cpu_index = os_get_thread_index ();
1007   u32 *to_be_removed = 0, *i;
1008
1009   /*
1010    * Tick the timer when required and process the vector of expired
1011    * timers
1012    */
1013   f64 start_time = vlib_time_now (vm);
1014   u32 count = 0;
1015
1016   tw_timer_expire_timers_2t_1w_2048sl (fm->timers_per_worker[cpu_index],
1017                                        start_time);
1018
1019   vec_foreach (i, fm->expired_passive_per_worker[cpu_index])
1020   {
1021     u32 exported = 0;
1022     f64 now = vlib_time_now (vm);
1023     if (now > start_time + 100e-6
1024         || exported > FLOW_MAXIMUM_EXPORT_ENTRIES - 1)
1025       break;
1026
1027     if (pool_is_free_index (fm->pool_per_worker[cpu_index], *i))
1028       {
1029         clib_warning ("Element is %d is freed already\n", *i);
1030         continue;
1031       }
1032     else
1033       e = pool_elt_at_index (fm->pool_per_worker[cpu_index], *i);
1034
1035     /* Check last update timestamp. If it is longer than passive time nuke
1036      * entry. Otherwise restart timer with what's left
1037      * Premature passive timer by more than 10%
1038      */
1039     if ((now - e->last_updated) < (u64) (fm->passive_timer * 0.9))
1040       {
1041         u64 delta = fm->passive_timer - (now - e->last_updated);
1042         e->passive_timer_handle = tw_timer_start_2t_1w_2048sl
1043           (fm->timers_per_worker[cpu_index], *i, 0, delta);
1044       }
1045     else                        /* Nuke entry */
1046       {
1047         vec_add1 (to_be_removed, *i);
1048       }
1049     /* If anything to report send it to the exporter */
1050     if (e->packetcount && now > e->last_exported + fm->active_timer)
1051       {
1052         exported++;
1053         flowprobe_export_entry (vm, e);
1054       }
1055     count++;
1056   }
1057   if (count)
1058     vec_delete (fm->expired_passive_per_worker[cpu_index], count, 0);
1059
1060   vec_foreach (i, to_be_removed) flowprobe_delete_by_index (cpu_index, *i);
1061   vec_free (to_be_removed);
1062
1063   return 0;
1064 }
1065
1066 /* *INDENT-OFF* */
1067 VLIB_REGISTER_NODE (flowprobe_input_ip4_node) = {
1068   .function = flowprobe_input_ip4_node_fn,
1069   .name = "flowprobe-input-ip4",
1070   .vector_size = sizeof (u32),
1071   .format_trace = format_flowprobe_trace,
1072   .type = VLIB_NODE_TYPE_INTERNAL,
1073   .n_errors = ARRAY_LEN (flowprobe_error_strings),
1074   .error_strings = flowprobe_error_strings,
1075   .n_next_nodes = FLOWPROBE_N_NEXT,
1076   .next_nodes = FLOWPROBE_NEXT_NODES,
1077 };
1078 VLIB_REGISTER_NODE (flowprobe_input_ip6_node) = {
1079   .function = flowprobe_input_ip6_node_fn,
1080   .name = "flowprobe-input-ip6",
1081   .vector_size = sizeof (u32),
1082   .format_trace = format_flowprobe_trace,
1083   .type = VLIB_NODE_TYPE_INTERNAL,
1084   .n_errors = ARRAY_LEN (flowprobe_error_strings),
1085   .error_strings = flowprobe_error_strings,
1086   .n_next_nodes = FLOWPROBE_N_NEXT,
1087   .next_nodes = FLOWPROBE_NEXT_NODES,
1088 };
1089 VLIB_REGISTER_NODE (flowprobe_input_l2_node) = {
1090   .function = flowprobe_input_l2_node_fn,
1091   .name = "flowprobe-input-l2",
1092   .vector_size = sizeof (u32),
1093   .format_trace = format_flowprobe_trace,
1094   .type = VLIB_NODE_TYPE_INTERNAL,
1095   .n_errors = ARRAY_LEN (flowprobe_error_strings),
1096   .error_strings = flowprobe_error_strings,
1097   .n_next_nodes = FLOWPROBE_N_NEXT,
1098   .next_nodes = FLOWPROBE_NEXT_NODES,
1099 };
1100 VLIB_REGISTER_NODE (flowprobe_output_ip4_node) = {
1101   .function = flowprobe_output_ip4_node_fn,
1102   .name = "flowprobe-output-ip4",
1103   .vector_size = sizeof (u32),
1104   .format_trace = format_flowprobe_trace,
1105   .type = VLIB_NODE_TYPE_INTERNAL,
1106   .n_errors = ARRAY_LEN (flowprobe_error_strings),
1107   .error_strings = flowprobe_error_strings,
1108   .n_next_nodes = FLOWPROBE_N_NEXT,
1109   .next_nodes = FLOWPROBE_NEXT_NODES,
1110 };
1111 VLIB_REGISTER_NODE (flowprobe_output_ip6_node) = {
1112   .function = flowprobe_output_ip6_node_fn,
1113   .name = "flowprobe-output-ip6",
1114   .vector_size = sizeof (u32),
1115   .format_trace = format_flowprobe_trace,
1116   .type = VLIB_NODE_TYPE_INTERNAL,
1117   .n_errors = ARRAY_LEN (flowprobe_error_strings),
1118   .error_strings = flowprobe_error_strings,
1119   .n_next_nodes = FLOWPROBE_N_NEXT,
1120   .next_nodes = FLOWPROBE_NEXT_NODES,
1121 };
1122 VLIB_REGISTER_NODE (flowprobe_output_l2_node) = {
1123   .function = flowprobe_output_l2_node_fn,
1124   .name = "flowprobe-output-l2",
1125   .vector_size = sizeof (u32),
1126   .format_trace = format_flowprobe_trace,
1127   .type = VLIB_NODE_TYPE_INTERNAL,
1128   .n_errors = ARRAY_LEN (flowprobe_error_strings),
1129   .error_strings = flowprobe_error_strings,
1130   .n_next_nodes = FLOWPROBE_N_NEXT,
1131   .next_nodes = FLOWPROBE_NEXT_NODES,
1132 };
1133 VLIB_REGISTER_NODE (flowprobe_walker_node) = {
1134   .function = flowprobe_walker_process,
1135   .name = "flowprobe-walker",
1136   .type = VLIB_NODE_TYPE_INPUT,
1137   .state = VLIB_NODE_STATE_INTERRUPT,
1138 };
1139 /* *INDENT-ON* */
1140
1141 /*
1142  * fd.io coding-style-patch-verification: ON
1143  *
1144  * Local Variables:
1145  * eval: (c-set-style "gnu")
1146  * End:
1147  */