nsim: add packet loss simulation, docs
[vpp.git] / src / plugins / nsim / nsim.c
1 /*
2  * nsim.c - skeleton vpp engine plug-in
3  *
4  * Copyright (c) <current-year> <your-organization>
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 Network Delay Simulator
21  */
22 /*? %%clicmd:group_label Network Delay Simulator %% ?*/
23
24 #include <vnet/vnet.h>
25 #include <vnet/plugin/plugin.h>
26 #include <nsim/nsim.h>
27
28 #include <vlibapi/api.h>
29 #include <vlibmemory/api.h>
30 #include <vpp/app/version.h>
31
32 /* define message IDs */
33 #include <nsim/nsim_msg_enum.h>
34
35 /* define message structures */
36 #define vl_typedefs
37 #include <nsim/nsim_all_api_h.h>
38 #undef vl_typedefs
39
40 /* define generated endian-swappers */
41 #define vl_endianfun
42 #include <nsim/nsim_all_api_h.h>
43 #undef vl_endianfun
44
45 /* instantiate all the print functions we know about */
46 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
47 #define vl_printfun
48 #include <nsim/nsim_all_api_h.h>
49 #undef vl_printfun
50
51 /* Get the API version number */
52 #define vl_api_version(n,v) static u32 api_version=(v);
53 #include <nsim/nsim_all_api_h.h>
54 #undef vl_api_version
55
56 #define REPLY_MSG_ID_BASE nsm->msg_id_base
57 #include <vlibapi/api_helper_macros.h>
58
59 nsim_main_t nsim_main;
60
61 /* List of message types that this plugin understands */
62
63 #define foreach_nsim_plugin_api_msg             \
64 _(NSIM_ENABLE_DISABLE, nsim_enable_disable)     \
65 _(NSIM_CONFIGURE, nsim_configure)
66
67 /* Action function shared between message handler and debug CLI */
68
69 int
70 nsim_enable_disable (nsim_main_t * nsm, u32 sw_if_index0,
71                      u32 sw_if_index1, int enable_disable)
72 {
73   vnet_sw_interface_t *sw;
74   vnet_hw_interface_t *hw;
75   int rv = 0;
76
77   if (nsm->is_configured == 0)
78     return VNET_API_ERROR_CANNOT_ENABLE_DISABLE_FEATURE;
79
80   /* Utterly wrong? */
81   if (pool_is_free_index (nsm->vnet_main->interface_main.sw_interfaces,
82                           sw_if_index0))
83     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
84
85   if (pool_is_free_index (nsm->vnet_main->interface_main.sw_interfaces,
86                           sw_if_index1))
87     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
88
89   /* Not a physical port? */
90   sw = vnet_get_sw_interface (nsm->vnet_main, sw_if_index0);
91   if (sw->type != VNET_SW_INTERFACE_TYPE_HARDWARE)
92     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
93
94   sw = vnet_get_sw_interface (nsm->vnet_main, sw_if_index1);
95   if (sw->type != VNET_SW_INTERFACE_TYPE_HARDWARE)
96     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
97
98   /* Add graph arcs for the input / wheel scraper node */
99   hw = vnet_get_hw_interface (nsm->vnet_main, sw_if_index0);
100   nsm->output_next_index0 =
101     vlib_node_add_next (nsm->vlib_main,
102                         nsim_input_node.index, hw->output_node_index);
103
104   hw = vnet_get_hw_interface (nsm->vnet_main, sw_if_index1);
105   nsm->output_next_index1 =
106     vlib_node_add_next (nsm->vlib_main,
107                         nsim_input_node.index, hw->output_node_index);
108
109   nsm->sw_if_index0 = sw_if_index0;
110   nsm->sw_if_index1 = sw_if_index1;
111
112   vnet_feature_enable_disable ("device-input", "nsim",
113                                sw_if_index0, enable_disable, 0, 0);
114   vnet_feature_enable_disable ("device-input", "nsim",
115                                sw_if_index1, enable_disable, 0, 0);
116
117   return rv;
118 }
119
120 static int
121 nsim_configure (nsim_main_t * nsm, f64 bandwidth, f64 delay, f64 packet_size,
122                 f64 drop_fraction)
123 {
124   u64 total_buffer_size_in_bytes, per_worker_buffer_size;
125   u64 wheel_slots_per_worker;
126   int i;
127   int num_workers = vlib_num_workers ();
128   u32 pagesize = getpagesize ();
129   vlib_main_t *vm = nsm->vlib_main;
130
131   if (bandwidth == 0.0)
132     return VNET_API_ERROR_INVALID_VALUE;
133
134   if (delay == 0.0)
135     return VNET_API_ERROR_INVALID_VALUE_2;
136
137   if (packet_size < 64.0 || packet_size > (f64) WHEEL_ENTRY_DATA_SIZE)
138     return VNET_API_ERROR_INVALID_VALUE_3;
139
140   /* Toss the old wheel(s)... */
141   if (nsm->is_configured)
142     {
143       for (i = 0; i < vec_len (nsm->wheel_by_thread); i++)
144         {
145           nsim_wheel_t *wp = nsm->wheel_by_thread[i];
146           munmap (wp, nsm->mmap_size);
147           nsm->wheel_by_thread[i] = 0;
148         }
149     }
150
151   nsm->delay = delay;
152   nsm->drop_fraction = drop_fraction;
153
154   /* delay in seconds, bandwidth in bits/sec */
155   total_buffer_size_in_bytes = (u32) ((delay * bandwidth) / 8.0) + 0.5;
156
157   /*
158    * Work out how much buffering each worker needs, assuming decent
159    * RSS behavior.
160    */
161   if (num_workers)
162     per_worker_buffer_size = total_buffer_size_in_bytes / num_workers;
163   else
164     per_worker_buffer_size = total_buffer_size_in_bytes;
165
166   wheel_slots_per_worker = per_worker_buffer_size / packet_size;
167   wheel_slots_per_worker++;
168
169   /* Save these for the show command */
170   nsm->bandwidth = bandwidth;
171   nsm->packet_size = packet_size;
172
173   vec_validate (nsm->wheel_by_thread, num_workers);
174   vec_validate (nsm->buffer_indices_by_thread, num_workers);
175
176   /* Initialize the output scheduler wheels */
177   for (i = num_workers ? 1 : 0; i < num_workers + 1; i++)
178     {
179       nsim_wheel_t *wp;
180
181       nsm->mmap_size = sizeof (nsim_wheel_t)
182         + wheel_slots_per_worker * sizeof (nsim_wheel_entry_t);
183
184       nsm->mmap_size += pagesize - 1;
185       nsm->mmap_size &= ~(pagesize - 1);
186
187       wp = clib_mem_vm_alloc (nsm->mmap_size);
188       ASSERT (wp != 0);
189       wp->wheel_size = wheel_slots_per_worker;
190       wp->cursize = 0;
191       wp->head = 0;
192       wp->tail = 0;
193       wp->entries = (void *) (wp + 1);
194       nsm->wheel_by_thread[i] = wp;
195       vec_validate (nsm->buffer_indices_by_thread[i], VLIB_FRAME_SIZE - 1);
196       _vec_len (nsm->buffer_indices_by_thread[i]) = 0;
197     }
198
199   vlib_worker_thread_barrier_sync (vm);
200
201   /* turn on the ring scrapers */
202   for (i = num_workers ? 1 : 0; i < num_workers + 1; i++)
203     {
204       vlib_main_t *this_vm = vlib_mains[i];
205
206       vlib_node_set_state (this_vm, nsim_input_node.index,
207                            VLIB_NODE_STATE_POLLING);
208     }
209
210   vlib_worker_thread_barrier_release (vm);
211
212   nsm->is_configured = 1;
213   return 0;
214 }
215
216 /*
217  * enable or disable the cross-connect
218  */
219 static clib_error_t *
220 nsim_enable_disable_command_fn (vlib_main_t * vm,
221                                 unformat_input_t * input,
222                                 vlib_cli_command_t * cmd)
223 {
224   nsim_main_t *nsm = &nsim_main;
225   u32 sw_if_index0 = ~0;
226   u32 sw_if_index1 = ~0;
227   int enable_disable = 1;
228   u32 tmp;
229   int rv;
230
231   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
232     {
233       if (unformat (input, "disable"))
234         enable_disable = 0;
235       else if (unformat (input, "%U", unformat_vnet_sw_interface,
236                          nsm->vnet_main, &tmp))
237         {
238           if (sw_if_index0 == ~0)
239             sw_if_index0 = tmp;
240           else
241             sw_if_index1 = tmp;
242         }
243       else
244         break;
245     }
246
247   if (sw_if_index0 == ~0 || sw_if_index1 == ~0)
248     return clib_error_return (0, "Please specify two interfaces...");
249
250   rv = nsim_enable_disable (nsm, sw_if_index0, sw_if_index1, enable_disable);
251
252   switch (rv)
253     {
254     case 0:
255       break;
256
257     case VNET_API_ERROR_CANNOT_ENABLE_DISABLE_FEATURE:
258       return clib_error_return (0, "Not configured, please 'set nsim' first");
259
260     case VNET_API_ERROR_INVALID_SW_IF_INDEX:
261       return clib_error_return
262         (0, "Invalid interface, only works on physical ports");
263       break;
264
265     case VNET_API_ERROR_UNIMPLEMENTED:
266       return clib_error_return (0,
267                                 "Device driver doesn't support redirection");
268       break;
269
270     default:
271       return clib_error_return (0, "nsim_enable_disable returned %d", rv);
272     }
273   return 0;
274 }
275
276 /*?
277  * Enable or disable network simulation cross-connect on two interfaces
278  * The network simulator must have already been configured, see
279  * the "nsim_configure" command.
280  *
281  * Place the interfaces into a bridge group, to ensure that
282  * interfaces are in promiscuous mode.
283  *
284  * @cliexpar
285  * To enable or disable network simulation cross-connect
286  * @clistart
287  * nsim enable-disable TenGigabitEthernet2/0/0 TenGigabitEthernet2/0
288  * nsim enable-disable TenGigabitEthernet2/0/0 TenGigabitEthernet2/0 disable
289  * @cliend
290  * @cliexcmd{nsim enable-disable <intfc> <intfc> [disable]}
291 ?*/
292 /* *INDENT-OFF* */
293 VLIB_CLI_COMMAND (nsim_enable_disable_command, static) =
294 {
295   .path = "nsim enable-disable",
296   .short_help =
297   "nsim enable-disable <interface-name-1> <interface-name-2> [disable]",
298   .function = nsim_enable_disable_command_fn,
299 };
300 /* *INDENT-ON* */
301
302 /* API message handler */
303 static void vl_api_nsim_enable_disable_t_handler
304   (vl_api_nsim_enable_disable_t * mp)
305 {
306   vl_api_nsim_enable_disable_reply_t *rmp;
307   nsim_main_t *nsm = &nsim_main;
308   int rv;
309
310   rv = nsim_enable_disable (nsm, ntohl (mp->sw_if_index0),
311                             ntohl (mp->sw_if_index1),
312                             (int) (mp->enable_disable));
313
314   REPLY_MACRO (VL_API_NSIM_ENABLE_DISABLE_REPLY);
315 }
316
317 /* API message handler */
318 static void
319 vl_api_nsim_configure_t_handler (vl_api_nsim_configure_t * mp)
320 {
321   vl_api_nsim_configure_reply_t *rmp;
322   nsim_main_t *nsm = &nsim_main;
323   f64 delay, bandwidth, packet_size, drop_fraction;
324   u32 packets_per_drop;
325   int rv;
326
327   delay = ((f64) (ntohl (mp->delay_in_usec))) * 1e-6;
328   bandwidth = (f64) (clib_net_to_host_u64 (mp->bandwidth_in_bits_per_second));
329   packet_size = (f64) (ntohl (mp->average_packet_size));
330
331   packets_per_drop = ntohl (mp->packets_per_drop);
332   if (packets_per_drop > 0)
333     drop_fraction = 1.0 / (f64) (packets_per_drop);
334   else
335     drop_fraction = 0.0;
336
337   rv = nsim_configure (nsm, bandwidth, delay, packet_size, drop_fraction);
338
339   REPLY_MACRO (VL_API_NSIM_CONFIGURE_REPLY);
340 }
341
342
343 /* Set up the API message handling tables */
344 static clib_error_t *
345 nsim_plugin_api_hookup (vlib_main_t * vm)
346 {
347   nsim_main_t *nsm = &nsim_main;
348 #define _(N,n)                                                  \
349     vl_msg_api_set_handlers((VL_API_##N + nsm->msg_id_base),     \
350                            #n,                                  \
351                            vl_api_##n##_t_handler,              \
352                            vl_noop_handler,                     \
353                            vl_api_##n##_t_endian,               \
354                            vl_api_##n##_t_print,                \
355                            sizeof(vl_api_##n##_t), 1);
356   foreach_nsim_plugin_api_msg;
357 #undef _
358
359   return 0;
360 }
361
362 #define vl_msg_name_crc_list
363 #include <nsim/nsim_all_api_h.h>
364 #undef vl_msg_name_crc_list
365
366 static void
367 setup_message_id_table (nsim_main_t * nsm, api_main_t * am)
368 {
369 #define _(id,n,crc)   vl_msg_api_add_msg_name_crc (am, #n "_" #crc, id + nsm->msg_id_base);
370   foreach_vl_msg_name_crc_nsim;
371 #undef _
372 }
373
374 static clib_error_t *
375 nsim_init (vlib_main_t * vm)
376 {
377   nsim_main_t *nsm = &nsim_main;
378   clib_error_t *error = 0;
379   u8 *name;
380
381   nsm->vlib_main = vm;
382   nsm->vnet_main = vnet_get_main ();
383
384   name = format (0, "nsim_%08x%c", api_version, 0);
385
386   /* Ask for a correctly-sized block of API message decode slots */
387   nsm->msg_id_base = vl_msg_api_get_msg_ids
388     ((char *) name, VL_MSG_FIRST_AVAILABLE);
389
390   error = nsim_plugin_api_hookup (vm);
391
392   /* Add our API messages to the global name_crc hash table */
393   setup_message_id_table (nsm, &api_main);
394
395   vec_free (name);
396
397   return error;
398 }
399
400 VLIB_INIT_FUNCTION (nsim_init);
401
402 /* *INDENT-OFF* */
403 VNET_FEATURE_INIT (nsim, static) =
404 {
405   .arc_name = "device-input",
406   .node_name = "nsim",
407   .runs_before = VNET_FEATURES ("ethernet-input"),
408 };
409 /* *INDENT-ON */
410
411 /* *INDENT-OFF* */
412 VLIB_PLUGIN_REGISTER () =
413 {
414   .version = VPP_BUILD_VER,
415   .description = "network delay simulator plugin",
416 };
417 /* *INDENT-ON* */
418
419 static uword
420 unformat_delay (unformat_input_t * input, va_list * args)
421 {
422   f64 *result = va_arg (*args, f64 *);
423   f64 tmp;
424
425   if (unformat (input, "%f us", &tmp))
426     *result = tmp * 1e-6;
427   else if (unformat (input, "%f ms", &tmp))
428     *result = tmp * 1e-3;
429   else if (unformat (input, "%f sec", &tmp))
430     *result = tmp;
431   else
432     return 0;
433
434   return 1;
435 }
436
437 static uword
438 unformat_bandwidth (unformat_input_t * input, va_list * args)
439 {
440   f64 *result = va_arg (*args, f64 *);
441   f64 tmp;
442
443   if (unformat (input, "%f gbit", &tmp))
444     *result = tmp * 1e9;
445   else if (unformat (input, "%f gbyte", &tmp))
446     *result = tmp * 8e9;
447   else
448     return 0;
449   return 1;
450 }
451
452 static clib_error_t *
453 set_nsim_command_fn (vlib_main_t * vm,
454                      unformat_input_t * input, vlib_cli_command_t * cmd)
455 {
456   nsim_main_t *nsm = &nsim_main;
457   f64 delay, bandwidth;
458   f64 packet_size = 1500.0;
459   f64 drop_fraction = 0.0;
460   u32 packets_per_drop;
461   u32 num_workers = vlib_num_workers ();
462   int rv;
463
464   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
465     {
466       if (unformat (input, "delay %U", unformat_delay, &delay))
467         ;
468       else if (unformat (input, "bandwidth %U", unformat_bandwidth,
469                          &bandwidth))
470         ;
471       else if (unformat (input, "packet-size %f", &packet_size))
472         ;
473       else if (unformat (input, "packets-per-drop %d", &packets_per_drop))
474         {
475           if (packets_per_drop > 0)
476             drop_fraction = 1.0 / ((f64) packets_per_drop);
477         }
478       else if (unformat (input, "drop-fraction %f", &drop_fraction))
479         {
480           if (drop_fraction < 0.0 || drop_fraction > 1.0)
481             return clib_error_return
482               (0, "drop fraction must be between zero and 1");
483         }
484       else
485         break;
486     }
487
488   rv = nsim_configure (nsm, bandwidth, delay, packet_size, drop_fraction);
489
490   switch (rv)
491     {
492     case VNET_API_ERROR_INVALID_VALUE:
493       return clib_error_return (0, "invalid bandwidth %.2f", bandwidth);
494
495     case VNET_API_ERROR_INVALID_VALUE_2:
496       return clib_error_return (0, "invalid delay %.2f", delay);
497
498     case VNET_API_ERROR_INVALID_VALUE_3:
499       return clib_error_return (0, "invalid packet size %.2f", packet_size);
500
501     default:
502       return clib_error_return (0, "error %d", rv);
503
504     case 0:
505       break;
506     }
507
508   vlib_cli_output (vm, "Configured link delay %.2f ms, %.2f ms round-trip",
509                    nsm->delay * 1e3, 2.0 * nsm->delay * 1e3);
510   if (nsm->drop_fraction > 0.0)
511     vlib_cli_output (vm, "... simulating a network drop fraction of %.5f",
512                      nsm->drop_fraction);
513
514
515   if (num_workers)
516     vlib_cli_output (vm, "Sim uses %llu bytes per thread, %llu bytes total",
517                      nsm->mmap_size, nsm->mmap_size * num_workers);
518   else
519     vlib_cli_output (vm, "Sim uses %llu bytes total", nsm->mmap_size);
520
521   return 0;
522 }
523
524 /*?
525  * Configure the network simulation cross-connect
526  * Once the simulator is configured, use the "nsim enable-disable" command
527  * to set up a cross-connect with the supplied delay characteristics.
528  *
529  * The cross connect configuration may be changed without restarting vpp
530  * but it is good practice to shut down the interfaces.
531  *
532  * @cliexpar
533  * To configure the network delay simulator:
534  * @clistart
535  * set nsim delay 10.0 ms bandwidth 5.5 gbit packet-size 128
536  *
537  * @cliend
538  * @cliexcmd{set nsim delay <nn> bandwidth <bb> packet-size <nn>}
539 ?*/
540 /* *INDENT-OFF* */
541 VLIB_CLI_COMMAND (set_nsim_command, static) =
542 {
543   .path = "set nsim",
544   .short_help = "set nsim delay <time> bandwidth <bps> packet-size <nbytes>",
545   .function = set_nsim_command_fn,
546 };
547 /* *INDENT-ON*/
548
549
550 static clib_error_t *
551 show_nsim_command_fn (vlib_main_t * vm,
552                       unformat_input_t * input, vlib_cli_command_t * cmd)
553 {
554   nsim_main_t *nsm = &nsim_main;
555   u32 num_workers = vlib_num_workers ();
556   int verbose = 0;
557
558   if (nsm->is_configured == 0)
559     return clib_error_return (0, "Network simulator not configured");
560
561   if (nsm->sw_if_index0 == 0)
562     return clib_error_return (0, "Network simulator not enabled");
563
564   if (unformat (input, "verbose"))
565     verbose = 1;
566
567   vlib_cli_output (vm, "Network simulator cross-connects %U and %U",
568                    format_vnet_sw_if_index_name,
569                    nsm->vnet_main, nsm->sw_if_index0,
570                    format_vnet_sw_if_index_name,
571                    nsm->vnet_main, nsm->sw_if_index1);
572
573   vlib_cli_output (vm,
574                    "...inserting link delay of %.2f ms, %.2f ms round-trip",
575                    nsm->delay * 1e3, 2.0 * nsm->delay * 1e3);
576
577   if (nsm->drop_fraction > 0.0)
578     vlib_cli_output (vm, "... simulating a network drop fraction of %.5f",
579                      nsm->drop_fraction);
580
581   if (verbose)
582     {
583
584       vlib_cli_output (vm, "  Configured bandwidth: %.2f gbit/sec",
585                        nsm->bandwidth / 1e9);
586       vlib_cli_output (vm, "  Configured packet size: %f", nsm->packet_size);
587       if (num_workers)
588         vlib_cli_output
589           (vm, "  Sim uses %llu bytes per thread, %llu bytes total",
590            nsm->mmap_size, nsm->mmap_size * num_workers);
591       else
592         vlib_cli_output (vm, "  Sim uses %llu bytes total", nsm->mmap_size);
593     }
594
595   return 0;
596 }
597
598 /*?
599  * Display state info for the network delay simulator.
600  *
601  * @cliexpar
602  * To display the state of the network simulator
603  * @clistart
604  * show nsim verbose
605  * Network simulator cross-connects TenGigabitEthernet2/0/0 and TenGigabitEthernet2/0/1
606  * ...inserting link delay of 10.00 ms, 20.00 ms round-trip
607  *  Configured bandwidth: 10.10 gbit/sec
608  *  Configured packet size: 128
609  *  Sim uses 157814784 bytes total
610  * @cliend
611  * @cliexcmd{show nsim}
612 ?*/
613
614 /* *INDENT-OFF* */
615 VLIB_CLI_COMMAND (show_nsim_command, static) =
616 {
617   .path = "show nsim",
618   .short_help = "Display network delay simulator configuration",
619   .function = show_nsim_command_fn,
620 };
621 /* *INDENT-ON* */
622
623 /*
624  * fd.io coding-style-patch-verification: ON
625  *
626  * Local Variables:
627  * eval: (c-set-style "gnu")
628  * End:
629  */