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