ipfix-export: pass an exp to flow_report_add_del
[vpp.git] / src / plugins / flowprobe / flowprobe.c
1 /*
2  * flowprobe.c - ipfix probe plugin
3  *
4  * Copyright (c) 2016 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
18 /**
19  * @file
20  * @brief Per-packet IPFIX flow record generator plugin
21  *
22  * This file implements vpp plugin registration mechanics,
23  * debug CLI, and binary API handling.
24  */
25
26 #include <vnet/vnet.h>
27 #include <vpp/app/version.h>
28 #include <vnet/plugin/plugin.h>
29 #include <vnet/udp/udp_local.h>
30 #include <flowprobe/flowprobe.h>
31
32 #include <vlibapi/api.h>
33 #include <vlibmemory/api.h>
34
35 /* define message IDs */
36 #include <flowprobe/flowprobe.api_enum.h>
37 #include <flowprobe/flowprobe.api_types.h>
38
39 flowprobe_main_t flowprobe_main;
40 static vlib_node_registration_t flowprobe_timer_node;
41 uword flowprobe_walker_process (vlib_main_t * vm, vlib_node_runtime_t * rt,
42                                 vlib_frame_t * f);
43
44 #define REPLY_MSG_ID_BASE fm->msg_id_base
45 #include <vlibapi/api_helper_macros.h>
46
47 /* Define the per-interface configurable features */
48 /* *INDENT-OFF* */
49 VNET_FEATURE_INIT (flow_perpacket_ip4, static) =
50 {
51   .arc_name = "ip4-output",
52   .node_name = "flowprobe-ip4",
53   .runs_before = VNET_FEATURES ("interface-output"),
54 };
55
56 VNET_FEATURE_INIT (flow_perpacket_ip6, static) =
57 {
58   .arc_name = "ip6-output",
59   .node_name = "flowprobe-ip6",
60   .runs_before = VNET_FEATURES ("interface-output"),
61 };
62
63 VNET_FEATURE_INIT (flow_perpacket_l2, static) = {
64   .arc_name = "interface-output",
65   .node_name = "flowprobe-l2",
66   .runs_before = VNET_FEATURES ("interface-output-arc-end"),
67 };
68 /* *INDENT-ON* */
69
70 /* Macro to finish up custom dump fns */
71 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
72 #define FINISH                                  \
73     vec_add1 (s, 0);                            \
74     vl_print (handle, (char *)s);               \
75     vec_free (s);                               \
76     return handle;
77
78 static inline ipfix_field_specifier_t *
79 flowprobe_template_ip4_fields (ipfix_field_specifier_t * f)
80 {
81 #define flowprobe_template_ip4_field_count() 4
82   /* sourceIpv4Address, TLV type 8, u32 */
83   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
84                                       sourceIPv4Address, 4);
85   f++;
86   /* destinationIPv4Address, TLV type 12, u32 */
87   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
88                                       destinationIPv4Address, 4);
89   f++;
90   /* protocolIdentifier, TLV type 4, u8 */
91   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
92                                       protocolIdentifier, 1);
93   f++;
94   /* octetDeltaCount, TLV type 1, u64 */
95   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
96                                       octetDeltaCount, 8);
97   f++;
98   return f;
99 }
100
101 static inline ipfix_field_specifier_t *
102 flowprobe_template_ip6_fields (ipfix_field_specifier_t * f)
103 {
104 #define flowprobe_template_ip6_field_count() 4
105   /* sourceIpv6Address, TLV type 27, 16 octets */
106   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
107                                       sourceIPv6Address, 16);
108   f++;
109   /* destinationIPv6Address, TLV type 28, 16 octets */
110   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
111                                       destinationIPv6Address, 16);
112   f++;
113   /* protocolIdentifier, TLV type 4, u8 */
114   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
115                                       protocolIdentifier, 1);
116   f++;
117   /* octetDeltaCount, TLV type 1, u64 */
118   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
119                                       octetDeltaCount, 8);
120   f++;
121   return f;
122 }
123
124 static inline ipfix_field_specifier_t *
125 flowprobe_template_l2_fields (ipfix_field_specifier_t * f)
126 {
127 #define flowprobe_template_l2_field_count() 3
128   /* sourceMacAddress, TLV type 56, u8[6] we hope */
129   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
130                                       sourceMacAddress, 6);
131   f++;
132   /* destinationMacAddress, TLV type 80, u8[6] we hope */
133   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
134                                       destinationMacAddress, 6);
135   f++;
136   /* ethernetType, TLV type 256, u16 */
137   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
138                                       ethernetType, 2);
139   f++;
140   return f;
141 }
142
143 static inline ipfix_field_specifier_t *
144 flowprobe_template_common_fields (ipfix_field_specifier_t * f)
145 {
146 #define flowprobe_template_common_field_count() 5
147   /* ingressInterface, TLV type 10, u32 */
148   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
149                                       ingressInterface, 4);
150   f++;
151
152   /* egressInterface, TLV type 14, u32 */
153   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
154                                       egressInterface, 4);
155   f++;
156
157   /* packetDeltaCount, TLV type 2, u64 */
158   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
159                                       packetDeltaCount, 8);
160   f++;
161
162   /* flowStartNanoseconds, TLV type 156, u64 */
163   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
164                                       flowStartNanoseconds, 8);
165   f++;
166
167   /* flowEndNanoseconds, TLV type 157, u64 */
168   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
169                                       flowEndNanoseconds, 8);
170   f++;
171
172   return f;
173 }
174
175 static inline ipfix_field_specifier_t *
176 flowprobe_template_l4_fields (ipfix_field_specifier_t * f)
177 {
178 #define flowprobe_template_l4_field_count() 3
179   /* sourceTransportPort, TLV type 7, u16 */
180   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
181                                       sourceTransportPort, 2);
182   f++;
183   /* destinationTransportPort, TLV type 11, u16 */
184   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
185                                       destinationTransportPort, 2);
186   f++;
187   /* tcpControlBits, TLV type 6, u16 */
188   f->e_id_length = ipfix_e_id_length (0 /* enterprise */ ,
189                                       tcpControlBits, 2);
190   f++;
191
192   return f;
193 }
194
195 /**
196  * @brief Create an IPFIX template packet rewrite string
197  * @param frm flow_report_main_t *
198  * @param fr flow_report_t *
199  * @param collector_address ip4_address_t * the IPFIX collector address
200  * @param src_address ip4_address_t * the source address we should use
201  * @param collector_port u16 the collector port we should use, host byte order
202  * @returns u8 * vector containing the indicated IPFIX template packet
203  */
204 static inline u8 *
205 flowprobe_template_rewrite_inline (ipfix_exporter_t *exp, flow_report_t *fr,
206                                    ip4_address_t *collector_address,
207                                    ip4_address_t *src_address,
208                                    u16 collector_port,
209                                    flowprobe_variant_t which)
210 {
211   ip4_header_t *ip;
212   udp_header_t *udp;
213   ipfix_message_header_t *h;
214   ipfix_set_header_t *s;
215   ipfix_template_header_t *t;
216   ipfix_field_specifier_t *f;
217   ipfix_field_specifier_t *first_field;
218   u8 *rewrite = 0;
219   ip4_ipfix_template_packet_t *tp;
220   u32 field_count = 0;
221   flow_report_stream_t *stream;
222   flowprobe_main_t *fm = &flowprobe_main;
223   flowprobe_record_t flags = fr->opaque.as_uword;
224   bool collect_ip4 = false, collect_ip6 = false;
225
226   stream = &exp->streams[fr->stream_index];
227
228   if (flags & FLOW_RECORD_L3)
229     {
230       collect_ip4 = which == FLOW_VARIANT_L2_IP4 || which == FLOW_VARIANT_IP4;
231       collect_ip6 = which == FLOW_VARIANT_L2_IP6 || which == FLOW_VARIANT_IP6;
232       if (which == FLOW_VARIANT_L2_IP4)
233         flags |= FLOW_RECORD_L2_IP4;
234       if (which == FLOW_VARIANT_L2_IP6)
235         flags |= FLOW_RECORD_L2_IP6;
236     }
237
238   field_count += flowprobe_template_common_field_count ();
239   if (flags & FLOW_RECORD_L2)
240     field_count += flowprobe_template_l2_field_count ();
241   if (collect_ip4)
242     field_count += flowprobe_template_ip4_field_count ();
243   if (collect_ip6)
244     field_count += flowprobe_template_ip6_field_count ();
245   if (flags & FLOW_RECORD_L4)
246     field_count += flowprobe_template_l4_field_count ();
247
248   /* allocate rewrite space */
249   vec_validate_aligned
250     (rewrite, sizeof (ip4_ipfix_template_packet_t)
251      + field_count * sizeof (ipfix_field_specifier_t) - 1,
252      CLIB_CACHE_LINE_BYTES);
253
254   tp = (ip4_ipfix_template_packet_t *) rewrite;
255   ip = (ip4_header_t *) & tp->ip4;
256   udp = (udp_header_t *) (ip + 1);
257   h = (ipfix_message_header_t *) (udp + 1);
258   s = (ipfix_set_header_t *) (h + 1);
259   t = (ipfix_template_header_t *) (s + 1);
260   first_field = f = (ipfix_field_specifier_t *) (t + 1);
261
262   ip->ip_version_and_header_length = 0x45;
263   ip->ttl = 254;
264   ip->protocol = IP_PROTOCOL_UDP;
265   ip->src_address.as_u32 = src_address->as_u32;
266   ip->dst_address.as_u32 = collector_address->as_u32;
267   udp->src_port = clib_host_to_net_u16 (stream->src_port);
268   udp->dst_port = clib_host_to_net_u16 (collector_port);
269   udp->length = clib_host_to_net_u16 (vec_len (rewrite) - sizeof (*ip));
270
271   /* FIXUP: message header export_time */
272   /* FIXUP: message header sequence_number */
273   h->domain_id = clib_host_to_net_u32 (stream->domain_id);
274
275   /* Add TLVs to the template */
276   f = flowprobe_template_common_fields (f);
277
278   if (flags & FLOW_RECORD_L2)
279     f = flowprobe_template_l2_fields (f);
280   if (collect_ip4)
281     f = flowprobe_template_ip4_fields (f);
282   if (collect_ip6)
283     f = flowprobe_template_ip6_fields (f);
284   if (flags & FLOW_RECORD_L4)
285     f = flowprobe_template_l4_fields (f);
286
287   /* Back to the template packet... */
288   ip = (ip4_header_t *) & tp->ip4;
289   udp = (udp_header_t *) (ip + 1);
290
291   ASSERT (f - first_field);
292   /* Field count in this template */
293   t->id_count = ipfix_id_count (fr->template_id, f - first_field);
294
295   fm->template_size[flags] = (u8 *) f - (u8 *) s;
296
297   /* set length in octets */
298   s->set_id_length =
299     ipfix_set_id_length (2 /* set_id */ , (u8 *) f - (u8 *) s);
300
301   /* message length in octets */
302   h->version_length = version_length ((u8 *) f - (u8 *) h);
303
304   ip->length = clib_host_to_net_u16 ((u8 *) f - (u8 *) ip);
305   ip->checksum = ip4_header_checksum (ip);
306
307   return rewrite;
308 }
309
310 static u8 *
311 flowprobe_template_rewrite_ip6 (ipfix_exporter_t *exp, flow_report_t *fr,
312                                 ip4_address_t *collector_address,
313                                 ip4_address_t *src_address, u16 collector_port,
314                                 ipfix_report_element_t *elts, u32 n_elts,
315                                 u32 *stream_index)
316 {
317   return flowprobe_template_rewrite_inline (
318     exp, fr, collector_address, src_address, collector_port, FLOW_VARIANT_IP6);
319 }
320
321 static u8 *
322 flowprobe_template_rewrite_ip4 (ipfix_exporter_t *exp, flow_report_t *fr,
323                                 ip4_address_t *collector_address,
324                                 ip4_address_t *src_address, u16 collector_port,
325                                 ipfix_report_element_t *elts, u32 n_elts,
326                                 u32 *stream_index)
327 {
328   return flowprobe_template_rewrite_inline (
329     exp, fr, collector_address, src_address, collector_port, FLOW_VARIANT_IP4);
330 }
331
332 static u8 *
333 flowprobe_template_rewrite_l2 (ipfix_exporter_t *exp, flow_report_t *fr,
334                                ip4_address_t *collector_address,
335                                ip4_address_t *src_address, u16 collector_port,
336                                ipfix_report_element_t *elts, u32 n_elts,
337                                u32 *stream_index)
338 {
339   return flowprobe_template_rewrite_inline (
340     exp, fr, collector_address, src_address, collector_port, FLOW_VARIANT_L2);
341 }
342
343 static u8 *
344 flowprobe_template_rewrite_l2_ip4 (ipfix_exporter_t *exp, flow_report_t *fr,
345                                    ip4_address_t *collector_address,
346                                    ip4_address_t *src_address,
347                                    u16 collector_port,
348                                    ipfix_report_element_t *elts, u32 n_elts,
349                                    u32 *stream_index)
350 {
351   return flowprobe_template_rewrite_inline (exp, fr, collector_address,
352                                             src_address, collector_port,
353                                             FLOW_VARIANT_L2_IP4);
354 }
355
356 static u8 *
357 flowprobe_template_rewrite_l2_ip6 (ipfix_exporter_t *exp, flow_report_t *fr,
358                                    ip4_address_t *collector_address,
359                                    ip4_address_t *src_address,
360                                    u16 collector_port,
361                                    ipfix_report_element_t *elts, u32 n_elts,
362                                    u32 *stream_index)
363 {
364   return flowprobe_template_rewrite_inline (exp, fr, collector_address,
365                                             src_address, collector_port,
366                                             FLOW_VARIANT_L2_IP6);
367 }
368
369 /**
370  * @brief Flush accumulated data
371  * @param frm flow_report_main_t *
372  * @param fr flow_report_t *
373  * @param f vlib_frame_t *
374  *
375  * <em>Notes:</em>
376  * This function must simply return the incoming frame, or no template packets
377  * will be sent.
378  */
379 vlib_frame_t *
380 flowprobe_data_callback_ip4 (flow_report_main_t *frm, ipfix_exporter_t *exp,
381                              flow_report_t *fr, vlib_frame_t *f, u32 *to_next,
382                              u32 node_index)
383 {
384   flowprobe_flush_callback_ip4 ();
385   return f;
386 }
387
388 vlib_frame_t *
389 flowprobe_data_callback_ip6 (flow_report_main_t *frm, ipfix_exporter_t *exp,
390                              flow_report_t *fr, vlib_frame_t *f, u32 *to_next,
391                              u32 node_index)
392 {
393   flowprobe_flush_callback_ip6 ();
394   return f;
395 }
396
397 vlib_frame_t *
398 flowprobe_data_callback_l2 (flow_report_main_t *frm, ipfix_exporter_t *exp,
399                             flow_report_t *fr, vlib_frame_t *f, u32 *to_next,
400                             u32 node_index)
401 {
402   flowprobe_flush_callback_l2 ();
403   return f;
404 }
405
406 static int
407 flowprobe_template_add_del (u32 domain_id, u16 src_port,
408                             flowprobe_record_t flags,
409                             vnet_flow_data_callback_t * flow_data_callback,
410                             vnet_flow_rewrite_callback_t * rewrite_callback,
411                             bool is_add, u16 * template_id)
412 {
413   ipfix_exporter_t *exp = &flow_report_main.exporters[0];
414   vnet_flow_report_add_del_args_t a = {
415     .rewrite_callback = rewrite_callback,
416     .flow_data_callback = flow_data_callback,
417     .is_add = is_add,
418     .domain_id = domain_id,
419     .src_port = src_port,
420     .opaque.as_uword = flags,
421   };
422   return vnet_flow_report_add_del (exp, &a, template_id);
423 }
424
425 static void
426 flowprobe_expired_timer_callback (u32 * expired_timers)
427 {
428   vlib_main_t *vm = vlib_get_main ();
429   flowprobe_main_t *fm = &flowprobe_main;
430   u32 my_cpu_number = vm->thread_index;
431   int i;
432   u32 poolindex;
433
434   for (i = 0; i < vec_len (expired_timers); i++)
435     {
436       poolindex = expired_timers[i] & 0x7FFFFFFF;
437       vec_add1 (fm->expired_passive_per_worker[my_cpu_number], poolindex);
438     }
439 }
440
441 static clib_error_t *
442 flowprobe_create_state_tables (u32 active_timer)
443 {
444   flowprobe_main_t *fm = &flowprobe_main;
445   vlib_thread_main_t *tm = &vlib_thread_main;
446   vlib_main_t *vm = vlib_get_main ();
447   clib_error_t *error = 0;
448   u32 num_threads;
449   int i;
450
451   /* Decide how many worker threads we have */
452   num_threads = 1 /* main thread */  + tm->n_threads;
453
454   /* Hash table per worker */
455   fm->ht_log2len = FLOWPROBE_LOG2_HASHSIZE;
456
457   /* Init per worker flow state and timer wheels */
458   if (active_timer)
459     {
460       vec_validate (fm->timers_per_worker, num_threads - 1);
461       vec_validate (fm->expired_passive_per_worker, num_threads - 1);
462       vec_validate (fm->hash_per_worker, num_threads - 1);
463       vec_validate (fm->pool_per_worker, num_threads - 1);
464
465       for (i = 0; i < num_threads; i++)
466         {
467           int j;
468           pool_alloc (fm->pool_per_worker[i], 1 << fm->ht_log2len);
469           vec_resize (fm->hash_per_worker[i], 1 << fm->ht_log2len);
470           for (j = 0; j < (1 << fm->ht_log2len); j++)
471             fm->hash_per_worker[i][j] = ~0;
472           fm->timers_per_worker[i] =
473             clib_mem_alloc (sizeof (TWT (tw_timer_wheel)));
474           tw_timer_wheel_init_2t_1w_2048sl (fm->timers_per_worker[i],
475                                             flowprobe_expired_timer_callback,
476                                             1.0, 1024);
477         }
478       fm->disabled = true;
479     }
480   else
481     {
482       f64 now = vlib_time_now (vm);
483       vec_validate (fm->stateless_entry, num_threads - 1);
484       for (i = 0; i < num_threads; i++)
485         fm->stateless_entry[i].last_exported = now;
486       fm->disabled = false;
487     }
488   fm->initialized = true;
489   return error;
490 }
491
492 static int
493 validate_feature_on_interface (flowprobe_main_t * fm, u32 sw_if_index,
494                                u8 which)
495 {
496   vec_validate_init_empty (fm->flow_per_interface, sw_if_index, ~0);
497
498   if (fm->flow_per_interface[sw_if_index] == (u8) ~ 0)
499     return -1;
500   else if (fm->flow_per_interface[sw_if_index] != which)
501     return 0;
502   else
503     return 1;
504 }
505
506 /**
507  * @brief configure / deconfigure the IPFIX flow-per-packet
508  * @param fm flowprobe_main_t * fm
509  * @param sw_if_index u32 the desired interface
510  * @param is_add int 1 to enable the feature, 0 to disable it
511  * @returns 0 if successful, non-zero otherwise
512  */
513
514 static int
515 flowprobe_tx_interface_add_del_feature (flowprobe_main_t * fm,
516                                         u32 sw_if_index, u8 which, int is_add)
517 {
518   vlib_main_t *vm = vlib_get_main ();
519   int rv = 0;
520   u16 template_id = 0;
521   flowprobe_record_t flags = fm->record;
522
523   fm->flow_per_interface[sw_if_index] = (is_add) ? which : (u8) ~ 0;
524   fm->template_per_flow[which] += (is_add) ? 1 : -1;
525   if (is_add && fm->template_per_flow[which] > 1)
526     template_id = fm->template_reports[flags];
527
528   if ((is_add && fm->template_per_flow[which] == 1) ||
529       (!is_add && fm->template_per_flow[which] == 0))
530     {
531       if (which == FLOW_VARIANT_L2)
532         {
533           if (fm->record & FLOW_RECORD_L2)
534             {
535               rv = flowprobe_template_add_del (1, UDP_DST_PORT_ipfix, flags,
536                                                flowprobe_data_callback_l2,
537                                                flowprobe_template_rewrite_l2,
538                                                is_add, &template_id);
539             }
540           if (fm->record & FLOW_RECORD_L3 || fm->record & FLOW_RECORD_L4)
541             {
542               rv = flowprobe_template_add_del (1, UDP_DST_PORT_ipfix, flags,
543                                                flowprobe_data_callback_l2,
544                                                flowprobe_template_rewrite_l2_ip4,
545                                                is_add, &template_id);
546               fm->template_reports[flags | FLOW_RECORD_L2_IP4] =
547                 (is_add) ? template_id : 0;
548               rv =
549                 flowprobe_template_add_del (1, UDP_DST_PORT_ipfix, flags,
550                                             flowprobe_data_callback_l2,
551                                             flowprobe_template_rewrite_l2_ip6,
552                                             is_add, &template_id);
553               fm->template_reports[flags | FLOW_RECORD_L2_IP6] =
554                 (is_add) ? template_id : 0;
555
556               /* Special case L2 */
557               fm->context[FLOW_VARIANT_L2_IP4].flags =
558                 flags | FLOW_RECORD_L2_IP4;
559               fm->context[FLOW_VARIANT_L2_IP6].flags =
560                 flags | FLOW_RECORD_L2_IP6;
561
562               fm->template_reports[flags] = template_id;
563             }
564         }
565       else if (which == FLOW_VARIANT_IP4)
566         rv = flowprobe_template_add_del (1, UDP_DST_PORT_ipfix, flags,
567                                          flowprobe_data_callback_ip4,
568                                          flowprobe_template_rewrite_ip4,
569                                          is_add, &template_id);
570       else if (which == FLOW_VARIANT_IP6)
571         rv = flowprobe_template_add_del (1, UDP_DST_PORT_ipfix, flags,
572                                          flowprobe_data_callback_ip6,
573                                          flowprobe_template_rewrite_ip6,
574                                          is_add, &template_id);
575     }
576   if (rv && rv != VNET_API_ERROR_VALUE_EXIST)
577     {
578       clib_warning ("vnet_flow_report_add_del returned %d", rv);
579       return -1;
580     }
581
582   if (which != (u8) ~ 0)
583     {
584       fm->context[which].flags = fm->record;
585       fm->template_reports[flags] = (is_add) ? template_id : 0;
586     }
587
588   if (which == FLOW_VARIANT_IP4)
589     vnet_feature_enable_disable ("ip4-output", "flowprobe-ip4",
590                                  sw_if_index, is_add, 0, 0);
591   else if (which == FLOW_VARIANT_IP6)
592     vnet_feature_enable_disable ("ip6-output", "flowprobe-ip6",
593                                  sw_if_index, is_add, 0, 0);
594   else if (which == FLOW_VARIANT_L2)
595     vnet_feature_enable_disable ("interface-output", "flowprobe-l2",
596                                  sw_if_index, is_add, 0, 0);
597
598   /* Stateful flow collection */
599   if (is_add && !fm->initialized)
600     {
601       flowprobe_create_state_tables (fm->active_timer);
602       if (fm->active_timer)
603         vlib_process_signal_event (vm, flowprobe_timer_node.index, 1, 0);
604     }
605
606   return 0;
607 }
608
609 /**
610  * @brief API message handler
611  * @param mp vl_api_flowprobe_tx_interface_add_del_t * mp the api message
612  */
613 void vl_api_flowprobe_tx_interface_add_del_t_handler
614   (vl_api_flowprobe_tx_interface_add_del_t * mp)
615 {
616   flowprobe_main_t *fm = &flowprobe_main;
617   vl_api_flowprobe_tx_interface_add_del_reply_t *rmp;
618   u32 sw_if_index = ntohl (mp->sw_if_index);
619   int rv = 0;
620
621   VALIDATE_SW_IF_INDEX (mp);
622
623   if (fm->record == 0)
624     {
625       clib_warning ("Please specify flowprobe params record first...");
626       rv = VNET_API_ERROR_CANNOT_ENABLE_DISABLE_FEATURE;
627       goto out;
628     }
629
630   rv = validate_feature_on_interface (fm, sw_if_index, mp->which);
631   if ((rv == 1 && mp->is_add == 1) || rv == 0)
632     {
633       rv = VNET_API_ERROR_CANNOT_ENABLE_DISABLE_FEATURE;
634       goto out;
635     }
636
637   rv = flowprobe_tx_interface_add_del_feature
638     (fm, sw_if_index, mp->which, mp->is_add);
639
640 out:
641   BAD_SW_IF_INDEX_LABEL;
642
643   REPLY_MACRO (VL_API_FLOWPROBE_TX_INTERFACE_ADD_DEL_REPLY);
644 }
645
646 #define vec_neg_search(v,E)         \
647 ({              \
648   word _v(i) = 0;         \
649   while (_v(i) < vec_len(v) && v[_v(i)] == E)        \
650   {             \
651     _v(i)++;            \
652   }             \
653   if (_v(i) == vec_len(v))        \
654     _v(i) = ~0;                 \
655   _v(i);            \
656 })
657
658 static int
659 flowprobe_params (flowprobe_main_t * fm, u8 record_l2,
660                   u8 record_l3, u8 record_l4,
661                   u32 active_timer, u32 passive_timer)
662 {
663   flowprobe_record_t flags = 0;
664
665   if (vec_neg_search (fm->flow_per_interface, (u8) ~ 0) != ~0)
666     return ~0;
667
668   if (record_l2)
669     flags |= FLOW_RECORD_L2;
670   if (record_l3)
671     flags |= FLOW_RECORD_L3;
672   if (record_l4)
673     flags |= FLOW_RECORD_L4;
674
675   fm->record = flags;
676
677   /*
678    * Timers: ~0 is default, 0 is off
679    */
680   fm->active_timer =
681     (active_timer == (u32) ~ 0 ? FLOWPROBE_TIMER_ACTIVE : active_timer);
682   fm->passive_timer =
683     (passive_timer == (u32) ~ 0 ? FLOWPROBE_TIMER_PASSIVE : passive_timer);
684
685   return 0;
686 }
687
688 void
689 vl_api_flowprobe_params_t_handler (vl_api_flowprobe_params_t * mp)
690 {
691   flowprobe_main_t *fm = &flowprobe_main;
692   vl_api_flowprobe_params_reply_t *rmp;
693   int rv = 0;
694
695   rv = flowprobe_params
696     (fm,
697      mp->record_flags & FLOWPROBE_RECORD_FLAG_L2,
698      mp->record_flags & FLOWPROBE_RECORD_FLAG_L3,
699      mp->record_flags & FLOWPROBE_RECORD_FLAG_L4,
700      clib_net_to_host_u32 (mp->active_timer),
701      clib_net_to_host_u32 (mp->passive_timer));
702
703   REPLY_MACRO (VL_API_FLOWPROBE_PARAMS_REPLY);
704 }
705
706 /* *INDENT-OFF* */
707 VLIB_PLUGIN_REGISTER () = {
708     .version = VPP_BUILD_VER,
709     .description = "Flow per Packet",
710 };
711 /* *INDENT-ON* */
712
713 u8 *
714 format_flowprobe_entry (u8 * s, va_list * args)
715 {
716   flowprobe_entry_t *e = va_arg (*args, flowprobe_entry_t *);
717   s = format (s, " %d/%d", e->key.rx_sw_if_index, e->key.tx_sw_if_index);
718
719   s = format (s, " %U %U", format_ethernet_address, &e->key.src_mac,
720               format_ethernet_address, &e->key.dst_mac);
721   s = format (s, " %U -> %U",
722               format_ip46_address, &e->key.src_address, IP46_TYPE_ANY,
723               format_ip46_address, &e->key.dst_address, IP46_TYPE_ANY);
724   s = format (s, " %d", e->key.protocol);
725   s = format (s, " %d %d\n", clib_net_to_host_u16 (e->key.src_port),
726               clib_net_to_host_u16 (e->key.dst_port));
727
728   return s;
729 }
730
731 u8 *
732 format_flowprobe_feature (u8 * s, va_list * args)
733 {
734   u8 *which = va_arg (*args, u8 *);
735   if (*which == FLOW_VARIANT_IP4)
736     s = format (s, "ip4");
737   else if (*which == FLOW_VARIANT_IP6)
738     s = format (s, "ip6");
739   else if (*which == FLOW_VARIANT_L2)
740     s = format (s, "l2");
741
742   return s;
743 }
744
745 u8 *
746 format_flowprobe_params (u8 * s, va_list * args)
747 {
748   flowprobe_record_t flags = va_arg (*args, flowprobe_record_t);
749   u32 active_timer = va_arg (*args, u32);
750   u32 passive_timer = va_arg (*args, u32);
751
752   if (flags & FLOW_RECORD_L2)
753     s = format (s, " l2");
754   if (flags & FLOW_RECORD_L3)
755     s = format (s, " l3");
756   if (flags & FLOW_RECORD_L4)
757     s = format (s, " l4");
758
759   if (active_timer != (u32) ~ 0)
760     s = format (s, " active: %d", active_timer);
761
762   if (passive_timer != (u32) ~ 0)
763     s = format (s, " passive: %d", passive_timer);
764
765   return s;
766 }
767
768 static clib_error_t *
769 flowprobe_show_table_fn (vlib_main_t * vm,
770                          unformat_input_t * input, vlib_cli_command_t * cm)
771 {
772   flowprobe_main_t *fm = &flowprobe_main;
773   int i;
774   flowprobe_entry_t *e;
775
776   vlib_cli_output (vm, "Dumping IPFIX table");
777
778   for (i = 0; i < vec_len (fm->pool_per_worker); i++)
779     {
780       /* *INDENT-OFF* */
781       pool_foreach (e, fm->pool_per_worker[i])
782         {
783           vlib_cli_output (vm, "%U",
784                            format_flowprobe_entry,
785                            e);
786         }
787       /* *INDENT-ON* */
788
789     }
790   return 0;
791 }
792
793 static clib_error_t *
794 flowprobe_show_stats_fn (vlib_main_t * vm,
795                          unformat_input_t * input, vlib_cli_command_t * cm)
796 {
797   flowprobe_main_t *fm = &flowprobe_main;
798   int i;
799
800   vlib_cli_output (vm, "IPFIX table statistics");
801   vlib_cli_output (vm, "Flow entry size: %d\n", sizeof (flowprobe_entry_t));
802   vlib_cli_output (vm, "Flow pool size per thread: %d\n",
803                    0x1 << FLOWPROBE_LOG2_HASHSIZE);
804
805   for (i = 0; i < vec_len (fm->pool_per_worker); i++)
806     vlib_cli_output (vm, "Pool utilisation thread %d is %d%%\n", i,
807                      (100 * pool_elts (fm->pool_per_worker[i])) /
808                      (0x1 << FLOWPROBE_LOG2_HASHSIZE));
809   return 0;
810 }
811
812 static clib_error_t *
813 flowprobe_tx_interface_add_del_feature_command_fn (vlib_main_t * vm,
814                                                    unformat_input_t * input,
815                                                    vlib_cli_command_t * cmd)
816 {
817   flowprobe_main_t *fm = &flowprobe_main;
818   u32 sw_if_index = ~0;
819   int is_add = 1;
820   u8 which = FLOW_VARIANT_IP4;
821   int rv;
822
823   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
824     {
825       if (unformat (input, "disable"))
826         is_add = 0;
827       else if (unformat (input, "%U", unformat_vnet_sw_interface,
828                          fm->vnet_main, &sw_if_index));
829       else if (unformat (input, "ip4"))
830         which = FLOW_VARIANT_IP4;
831       else if (unformat (input, "ip6"))
832         which = FLOW_VARIANT_IP6;
833       else if (unformat (input, "l2"))
834         which = FLOW_VARIANT_L2;
835       else
836         break;
837     }
838
839   if (fm->record == 0)
840     return clib_error_return (0,
841                               "Please specify flowprobe params record first...");
842
843   if (sw_if_index == ~0)
844     return clib_error_return (0, "Please specify an interface...");
845
846   rv = validate_feature_on_interface (fm, sw_if_index, which);
847   if (rv == 1)
848     {
849       if (is_add)
850         return clib_error_return (0,
851                                   "Datapath is already enabled for given interface...");
852     }
853   else if (rv == 0)
854     return clib_error_return (0,
855                               "Interface has enable different datapath ...");
856
857   rv =
858     flowprobe_tx_interface_add_del_feature (fm, sw_if_index, which, is_add);
859   switch (rv)
860     {
861     case 0:
862       break;
863
864     case VNET_API_ERROR_INVALID_SW_IF_INDEX:
865       return clib_error_return
866         (0, "Invalid interface, only works on physical ports");
867       break;
868
869     case VNET_API_ERROR_UNIMPLEMENTED:
870       return clib_error_return (0, "ip6 not supported");
871       break;
872
873     default:
874       return clib_error_return (0, "flowprobe_enable_disable returned %d",
875                                 rv);
876     }
877   return 0;
878 }
879
880 static clib_error_t *
881 flowprobe_show_feature_command_fn (vlib_main_t * vm,
882                                    unformat_input_t * input,
883                                    vlib_cli_command_t * cmd)
884 {
885   flowprobe_main_t *fm = &flowprobe_main;
886   u8 *which;
887   u32 sw_if_index;
888
889   vec_foreach (which, fm->flow_per_interface)
890   {
891     if (*which == (u8) ~ 0)
892       continue;
893
894     sw_if_index = which - fm->flow_per_interface;
895     vlib_cli_output (vm, " %U %U", format_vnet_sw_if_index_name,
896                      vnet_get_main (), sw_if_index, format_flowprobe_feature,
897                      which);
898   }
899   return 0;
900 }
901
902 static clib_error_t *
903 flowprobe_params_command_fn (vlib_main_t * vm,
904                              unformat_input_t * input,
905                              vlib_cli_command_t * cmd)
906 {
907   flowprobe_main_t *fm = &flowprobe_main;
908   bool record_l2 = false, record_l3 = false, record_l4 = false;
909   u32 active_timer = ~0;
910   u32 passive_timer = ~0;
911
912   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
913     {
914       if (unformat (input, "active %d", &active_timer))
915         ;
916       else if (unformat (input, "passive %d", &passive_timer))
917         ;
918       else if (unformat (input, "record"))
919         while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
920           {
921             if (unformat (input, "l2"))
922               record_l2 = true;
923             else if (unformat (input, "l3"))
924               record_l3 = true;
925             else if (unformat (input, "l4"))
926               record_l4 = true;
927             else
928               break;
929           }
930       else
931         break;
932     }
933
934   if (passive_timer > 0 && active_timer > passive_timer)
935     return clib_error_return (0,
936                               "Passive timer has to be greater than active one...");
937
938   if (flowprobe_params (fm, record_l2, record_l3, record_l4,
939                         active_timer, passive_timer))
940     return clib_error_return (0,
941                               "Couldn't change flowperpacket params when feature is enabled on some interface ...");
942   return 0;
943 }
944
945 static clib_error_t *
946 flowprobe_show_params_command_fn (vlib_main_t * vm,
947                                   unformat_input_t * input,
948                                   vlib_cli_command_t * cmd)
949 {
950   flowprobe_main_t *fm = &flowprobe_main;
951   flowprobe_record_t flags = fm->record;
952   u32 active_timer = fm->active_timer;
953   u32 passive_timer = fm->passive_timer;
954
955   vlib_cli_output (vm, "%U", format_flowprobe_params, flags, active_timer,
956                    passive_timer);
957   return 0;
958 }
959
960 /*?
961  * '<em>flowprobe feature add-del</em>' commands to enable/disable
962  * per-packet IPFIX flow record generation on an interface
963  *
964  * @cliexpar
965  * @parblock
966  * To enable per-packet IPFIX flow-record generation on an interface:
967  * @cliexcmd{flowprobe feature add-del GigabitEthernet2/0/0}
968  *
969  * To disable per-packet IPFIX flow-record generation on an interface:
970  * @cliexcmd{flowprobe feature add-del GigabitEthernet2/0/0 disable}
971  * @cliexend
972  * @endparblock
973 ?*/
974 /* *INDENT-OFF* */
975 VLIB_CLI_COMMAND (flowprobe_enable_disable_command, static) = {
976     .path = "flowprobe feature add-del",
977     .short_help =
978     "flowprobe feature add-del <interface-name> <l2|ip4|ip6> disable",
979     .function = flowprobe_tx_interface_add_del_feature_command_fn,
980 };
981 VLIB_CLI_COMMAND (flowprobe_params_command, static) = {
982     .path = "flowprobe params",
983     .short_help =
984     "flowprobe params record <[l2] [l3] [l4]> [active <timer> passive <timer>]",
985     .function = flowprobe_params_command_fn,
986 };
987
988 VLIB_CLI_COMMAND (flowprobe_show_feature_command, static) = {
989     .path = "show flowprobe feature",
990     .short_help =
991     "show flowprobe feature",
992     .function = flowprobe_show_feature_command_fn,
993 };
994 VLIB_CLI_COMMAND (flowprobe_show_params_command, static) = {
995     .path = "show flowprobe params",
996     .short_help =
997     "show flowprobe params",
998     .function = flowprobe_show_params_command_fn,
999 };
1000 VLIB_CLI_COMMAND (flowprobe_show_table_command, static) = {
1001     .path = "show flowprobe table",
1002     .short_help = "show flowprobe table",
1003     .function = flowprobe_show_table_fn,
1004 };
1005 VLIB_CLI_COMMAND (flowprobe_show_stats_command, static) = {
1006     .path = "show flowprobe statistics",
1007     .short_help = "show flowprobe statistics",
1008     .function = flowprobe_show_stats_fn,
1009 };
1010 /* *INDENT-ON* */
1011
1012 /*
1013  * Main-core process, sending an interrupt to the per worker input
1014  * process that spins the per worker timer wheel.
1015  */
1016 static uword
1017 timer_process (vlib_main_t * vm, vlib_node_runtime_t * rt, vlib_frame_t * f)
1018 {
1019   uword *event_data = 0;
1020   vlib_main_t **worker_vms = 0, *worker_vm;
1021   flowprobe_main_t *fm = &flowprobe_main;
1022
1023   /* Wait for Godot... */
1024   vlib_process_wait_for_event_or_clock (vm, 1e9);
1025   uword event_type = vlib_process_get_events (vm, &event_data);
1026   if (event_type != 1)
1027     clib_warning ("bogus kickoff event received, %d", event_type);
1028   vec_reset_length (event_data);
1029
1030   int i;
1031   if (vlib_get_n_threads () == 0)
1032     vec_add1 (worker_vms, vm);
1033   else
1034     {
1035       for (i = 0; i < vlib_get_n_threads (); i++)
1036         {
1037           worker_vm = vlib_get_main_by_index (i);
1038           if (worker_vm)
1039             vec_add1 (worker_vms, worker_vm);
1040         }
1041     }
1042   f64 sleep_duration = 0.1;
1043
1044   while (1)
1045     {
1046       /* Send an interrupt to each timer input node */
1047       sleep_duration = 0.1;
1048       for (i = 0; i < vec_len (worker_vms); i++)
1049         {
1050           worker_vm = worker_vms[i];
1051           if (worker_vm)
1052             {
1053               vlib_node_set_interrupt_pending (worker_vm,
1054                                                flowprobe_walker_node.index);
1055               sleep_duration =
1056                 (fm->expired_passive_per_worker[i] > 0) ? 1e-4 : 0.1;
1057             }
1058         }
1059       vlib_process_suspend (vm, sleep_duration);
1060     }
1061   return 0;                     /* or not */
1062 }
1063
1064 /* *INDENT-OFF* */
1065 VLIB_REGISTER_NODE (flowprobe_timer_node,static) = {
1066   .function = timer_process,
1067   .name = "flowprobe-timer-process",
1068   .type = VLIB_NODE_TYPE_PROCESS,
1069 };
1070 /* *INDENT-ON* */
1071
1072 #include <flowprobe/flowprobe.api.c>
1073
1074 /**
1075  * @brief Set up the API message handling tables
1076  * @param vm vlib_main_t * vlib main data structure pointer
1077  * @returns 0 to indicate all is well, or a clib_error_t
1078  */
1079 static clib_error_t *
1080 flowprobe_init (vlib_main_t * vm)
1081 {
1082   flowprobe_main_t *fm = &flowprobe_main;
1083   vlib_thread_main_t *tm = &vlib_thread_main;
1084   clib_error_t *error = 0;
1085   u32 num_threads;
1086   int i;
1087
1088   fm->vnet_main = vnet_get_main ();
1089
1090   /* Ask for a correctly-sized block of API message decode slots */
1091   fm->msg_id_base = setup_message_id_table ();
1092
1093   /* Set up time reference pair */
1094   fm->vlib_time_0 = vlib_time_now (vm);
1095   fm->nanosecond_time_0 = unix_time_now_nsec ();
1096
1097   clib_memset (fm->template_reports, 0, sizeof (fm->template_reports));
1098   clib_memset (fm->template_size, 0, sizeof (fm->template_size));
1099   clib_memset (fm->template_per_flow, 0, sizeof (fm->template_per_flow));
1100
1101   /* Decide how many worker threads we have */
1102   num_threads = 1 /* main thread */  + tm->n_threads;
1103
1104   /* Allocate per worker thread vectors per flavour */
1105   for (i = 0; i < FLOW_N_VARIANTS; i++)
1106     {
1107       vec_validate (fm->context[i].buffers_per_worker, num_threads - 1);
1108       vec_validate (fm->context[i].frames_per_worker, num_threads - 1);
1109       vec_validate (fm->context[i].next_record_offset_per_worker,
1110                     num_threads - 1);
1111     }
1112
1113   fm->active_timer = FLOWPROBE_TIMER_ACTIVE;
1114   fm->passive_timer = FLOWPROBE_TIMER_PASSIVE;
1115
1116   return error;
1117 }
1118
1119 VLIB_INIT_FUNCTION (flowprobe_init);
1120
1121 /*
1122  * fd.io coding-style-patch-verification: ON
1123  *
1124  * Local Variables:
1125  * eval: (c-set-style "gnu")
1126  * End:
1127  */